The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.
Cra: native macOS browser on CEF
Victorfac5c68735ef
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..1783e49--- /dev/null+++ b/.gitignore@@ -0,0 +1,7 @@+.build/+build/+vendor/+*.xcodeproj+*.xcworkspace+.DS_Store+.swiftpm/diff --git a/Package.swift b/Package.swiftnew file mode 100644index 0000000..9aa45b2--- /dev/null+++ b/Package.swift@@ -0,0 +1,66 @@+// swift-tools-version:5.10+import PackageDescription++// CEF (Chromium Embedded Framework) lives in vendor/cef, fetched by+// scripts/fetch-cef.sh, with its C++ wrapper built by CMake into+// vendor/cef/build/libcef_dll_wrapper.+let cefRoot = "\(Context.packageDirectory)/vendor/cef"++// Same flags CEF uses for its own wrapper (vendor/cef/cmake/cef_variables.cmake),+// so the ABI of the wrapper classes matches.+let cefCXXFlags: [String] = [+ "-fno-exceptions", "-fno-rtti", "-fno-threadsafe-statics",+ "-fobjc-call-cxx-cdtors", "-fno-strict-aliasing",+ "-Wno-unused-parameter", "-Wno-deprecated-declarations",+ "-I", cefRoot,+]++let cefLinkerFlags: [String] = [+ "-L\(cefRoot)/build/libcef_dll_wrapper",+]++let package = Package(+ name: "Cra",+ platforms: [.macOS(.v14)],+ products: [+ .executable(name: "Cra", targets: ["Cra"]),+ .executable(name: "CraHelper", targets: ["CraHelper"]),+ ],+ targets: [+ // Objective-C++ bridge between Swift and CEF.+ .target(+ name: "CraCEF",+ path: "Sources/CraCEF",+ publicHeadersPath: "include",+ cxxSettings: [.unsafeFlags(cefCXXFlags + ["-fobjc-arc"])],+ linkerSettings: [+ .unsafeFlags(cefLinkerFlags),+ .linkedLibrary("cef_dll_wrapper"),+ .linkedFramework("AppKit"),+ .linkedFramework("IOSurface"),+ ]+ ),+ // Subprocess executable (renderer, GPU, utility...). Bundled five+ // times as "Cra Helper*.app" inside Cra.app/Contents/Frameworks.+ .executableTarget(+ name: "CraHelper",+ path: "Sources/CraHelper",+ cxxSettings: [.unsafeFlags(cefCXXFlags)],+ linkerSettings: [+ .unsafeFlags(cefLinkerFlags),+ .linkedLibrary("cef_dll_wrapper"),+ .linkedFramework("AppKit"),+ .linkedFramework("IOSurface"),+ ]+ ),+ // The browser itself: AppKit window, SwiftUI sidebar and command bar.+ .executableTarget(+ name: "Cra",+ dependencies: ["CraCEF"],+ path: "Sources/Cra",+ swiftSettings: [.unsafeFlags(["-Onone"], .when(configuration: .debug))]+ ),+ ],+ swiftLanguageVersions: [.v5],+ cxxLanguageStandard: .cxx20+)diff --git a/README.md b/README.mdnew file mode 100644index 0000000..e99c2b1--- /dev/null+++ b/README.md@@ -0,0 +1,88 @@+# Cra++A native macOS browser built on Chromium (CEF), shaped after the parts of Arc+worth keeping: a sidebar instead of a tab strip, spaces, pinned tabs with a+home URL, favorites shared across spaces, a command bar for new tabs that+searches open and archived tabs, auto-archiving, folders, and Chrome DevTools.++Shell: Swift (AppKit + SwiftUI). Engine: Chromium Embedded Framework.++## Build++ scripts/build.sh # fetches CEF on first run, builds build/Cra.app+ scripts/run.sh # build if needed, then open++Requirements: Xcode 16+, CMake (`brew install cmake`).++## Layout++- `Sources/Cra` — the app (model, store, sidebar, command bar, windows)+- `Sources/CraCEF` — Objective-C++ bridge to CEF+- `Sources/CraHelper` — Chromium subprocess executable+- `docs/arc-reverse-engineering.md` — what was learned from Arc and how+- `vendor/cef` — CEF binary distribution (not committed)++Data lives in `~/Library/Application Support/Cra`.++## Scripting hooks++Cra registers the `cra://` scheme so it can be driven from a shell (handy for+testing without touching the keyboard):++ open "cra://action/newTab" # any action id from KeyBindings.swift+ open "cra://commandbar?query=github" # open the command bar with text+ open "cra://open?url=https://example.com&background=1"+ open "cra://dismiss" # close sheets, command bar, find bar++## Import++Cra menu → Import from Arc or Dia…, or Settings → Import. Reads Arc's+StorableSidebar.json / StorableArchiveItems.json and Dia's profile containers ++bookmarks. Spaces with the same name merge; tabs already present are skipped.+Headless: `open "cra://import?source=arc&archive=1&settings=1"`.++## Account (Convex)++Backend in `backend/convex` (team victor-kildahl, project cra): dev+`helpful-stoat-265`, prod `artful-albatross-857` (eu-west-1). The app uses prod;+set `CRA_CONVEX_DEV=1` to use dev. Email/password and Google sign-in (the Google+OAuth client needs `https://<deployment>.convex.site/google-callback` as an+authorized redirect URI). Settings sync on change; the sidebar is backed up+every 10 minutes while signed in (Settings → Account → Restore).++Deploy changes to both deployments: `cd backend && npx convex dev --once && npx convex deploy -y`.++## Keyboard++Arc's defaults: ⌘T new tab · ⌘L command bar / edit URL · ⌘W close tab (window+when no tab) · ⇧⌘W close window · ⇧⌘T restore closed tab · ⌘S sidebar ·+⇧⌘D toolbar · ⌘D pin/unpin · ⇧⌘C copy URL · ⇧⌥⌘C copy as Markdown ·+⌘1…9 go to tab · ⌃1…9 go to space · ⌥⌘←/→ spaces · ⌥⌘↑/↓ tabs · ⌃Tab recent+tab · ⇧⌘K clear Today · ⌘[ / ⌘] back/forward · ⌘Y history · ⇧⌘L library ·+⇧⌘J downloads · ⌥⌘I DevTools · ⌥⌘J console · ⌥⌘U source · ⌘F find.+Like Chrome, pages get first chance at unreserved shortcuts (⌘F in Docs works).+Shortcuts can be changed in `~/Library/Application Support/Cra/keybindings.json`.++## Rendering calibration hook++`open "cra://debug?lift=0&liftInactive=0.75&alpha=1&material=13&state=follows&appearance=dark"`+changes the vibrancy parameters live (see `Sources/Cra/UI/Tuning.swift`). `material` is the+raw `NSVisualEffectView.Material` value, `alpha` scales the gradient opacity.++## DevTools++⌥⌘I toggles Chrome DevTools docked on the right of the page (drag the divider to resize);+Inspect Element from the context menu opens it at the clicked node. Each tab keeps its own+DevTools; the dock follows the selected tab.++## Brand++`brand/` holds the marks; `resources/brand/*.png` are WebKit renders of them (so the+multiply blends survive) used by `BrandMark`, and `resources/AppIcon.icns` is built from+`brand/cra-segments-icon.svg` (render at 1024 px, `iconutil`).++## Website and brand++The marketing site lives in a separate private repository (VictorKildahl/cra-website).+Logo sources are in `brand/` (see `brand/README.md`); `resources/brand` holds the PNGs the+app loads and `resources/AppIcon.icns` the app icon.diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swiftnew file mode 100644index 0000000..3446461--- /dev/null+++ b/Sources/Cra/App/AppDelegate.swift@@ -0,0 +1,549 @@+import AppKit+import CraCEF+import SwiftUI++@MainActor+final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {+ let store = SidebarStore()+ let bindings = KeyBindingRegistry()+ let favicons = FaviconCache()+ let account = AccountStore()+ lazy var engine = SuggestionEngine(store: store, bindings: bindings)++ private(set) var main: MainWindowController!+ private var bootstrapped = false+ private var pendingURLs: [String] = []+ private var autoArchiveTimer: Timer?+ private var backupTimer: Timer?+ private var settingsWindow: NSWindow?+ private var archiveWindow: NSWindow?+ private var accountWindow: NSWindow?+ private var lastPushedSettings: AppSettings?++ /// Shortcuts the app takes before the web page sees them (Chrome calls+ /// these reserved). Everything else goes to the page first.+ static let reservedActions: Set<String> = Set([+ "newTab", "newWindow", "closeTab", "closeWindow", "reopenClosedTab", "editURL", "toggleSidebar", "toggleToolbar",+ "nextTab", "previousTab", "recentTab", "nextSpace", "previousSpace", "devTools", "jsConsole", "inspectElement",+ "viewArchive", "openLibrary", "settings", "clearToday",+ ] + (1...9).flatMap { ["item\($0)", "space\($0)"] })++ // MARK: Lifecycle++ func applicationDidFinishLaunching(_ notification: Notification) { bootstrapIfNeeded() }++ func bootstrapIfNeeded() {+ guard !bootstrapped else { return }+ bootstrapped = true+ NSApp.setActivationPolicy(.regular)+ installURLEventHandler()+ buildMenus()+ NotificationCenter.default.addObserver(forName: .craKeyBindingsChanged, object: nil, queue: .main) { [weak self] _ in+ Task { @MainActor in self?.buildMenus() }+ }+ main = MainWindowController(app: self)+ main.showWindow(nil)+ store.runAutoArchive()+ autoArchiveTimer = Timer.scheduledTimer(withTimeInterval: 1800, repeats: true) { [weak self] _ in+ Task { @MainActor in self?.store.runAutoArchive() }+ }+ backupTimer = Timer.scheduledTimer(withTimeInterval: 600, repeats: true) { [weak self] _ in+ Task { @MainActor in await self?.backupIfSignedIn() }+ }+ NSApp.activate(ignoringOtherApps: true)+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in self?.installURLEventHandler() }+ CraCEFRuntime.setRelaunchHandler { [weak self] urls in+ Task { @MainActor in+ guard let self else { return }+ self.main.showWindow(nil)+ NSApp.activate(ignoringOtherApps: true)+ for u in urls { self.openExternalURL(u) }+ }+ }+ let urls = pendingURLs+ pendingURLs = []+ for u in urls { openExternalURL(u) }++ Task { await account.restore(); await pullSettingsIfNewer() }+ observeSettingsForSync()+ maybeOfferImport()+ }++ private func maybeOfferImport() {+ guard !store.settings.hasSeenImportPrompt, ArcImporter.isAvailable || DiaImporter.isAvailable, store.allTabs().count <= 2 else { return }+ store.settings.hasSeenImportPrompt = true+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { [weak self] in self?.main.showImport() }+ }++ private func observeSettingsForSync() {+ withObservationTracking {+ _ = store.settings+ } onChange: { [weak self] in+ Task { @MainActor in+ guard let self else { return }+ if self.account.isSignedIn, self.lastPushedSettings != self.store.settings {+ self.lastPushedSettings = self.store.settings+ self.account.pushSettings(self.store.settings)+ }+ self.observeSettingsForSync()+ }+ }+ }++ private func pullSettingsIfNewer() async {+ guard account.isSignedIn, let remote = await account.pullSettings() else { return }+ var merged = remote+ merged.hasSeenImportPrompt = store.settings.hasSeenImportPrompt || remote.hasSeenImportPrompt+ if merged != store.settings {+ lastPushedSettings = merged+ store.settings = merged+ }+ }++ private func backupIfSignedIn() async {+ guard account.isSignedIn else { return }+ await account.backupSidebar(store.document, tabCount: store.allTabs().count)+ }++ private func installURLEventHandler() {+ NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(handleGetURLEvent(_:reply:)),+ forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))+ }++ func applicationDidBecomeActive(_ notification: Notification) { installURLEventHandler() }++ @objc private func handleGetURLEvent(_ event: NSAppleEventDescriptor, reply: NSAppleEventDescriptor) {+ guard let s = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue else { return }+ if bootstrapped { openExternalURL(s) } else { pendingURLs.append(s) }+ }++ func application(_ application: NSApplication, open urls: [URL]) {+ for u in urls {+ if bootstrapped { openExternalURL(u.absoluteString) } else { pendingURLs.append(u.absoluteString) }+ }+ }++ func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {+ main?.showWindow(nil)+ return true+ }++ func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {+ store.saveAll()+ return .terminateNow+ }++ func applicationWillShutdown() { store.saveAll() }++ func openExternalURL(_ url: String) {+ if let u = URL(string: url), u.scheme == "cra" {+ handleInternalURL(u)+ return+ }+ store.createTab(url: url, select: true)+ main.showWindow(nil)+ NSApp.activate(ignoringOtherApps: true)+ }++ /// cra://commandbar?query=…&mode=edit, cra://action/<id>, cra://open?url=…,+ /// cra://dismiss, cra://auth-callback?data=… (Google sign-in return).+ /// Arc marks a tab chosen from the keyboard with its yellow/black focus ring.+ private func markKeyboardFocus() { main.sidebarUI.keyboardFocusID = store.selectedTabID }++ func handleInternalURL(_ u: URL) {+ let comps = URLComponents(url: u, resolvingAgainstBaseURL: false)+ func q(_ name: String) -> String? { comps?.queryItems?.first { $0.name == name }?.value }+ main.showWindow(nil)+ NSApp.activate(ignoringOtherApps: true)+ switch u.host {+ case "commandbar":+ main.openCommandBar(q("mode") == "edit" ? .editURL : .newTab)+ if let text = q("query") { main.commandBar.setQuery(text) }+ case "action":+ perform(String(u.path.dropFirst()))+ case "open":+ if let url = q("url") {+ let tab = store.createTab(url: url, select: q("background") != "1")+ if q("background") == "1" { store.markUnread(tab.id, true); main.browsers.ensureRuntime(for: tab.id) }+ }+ case "key":+ // Scripted key press through the normal event path (testing).+ guard let chars = q("chars"), let window = main.window else { break }+ var flags: NSEvent.ModifierFlags = []+ if q("cmd") == "1" { flags.insert(.command) }+ if q("shift") == "1" { flags.insert(.shift) }+ if q("opt") == "1" { flags.insert(.option) }+ if q("ctrl") == "1" { flags.insert(.control) }+ let codes: [String: UInt16] = ["a": 0, "s": 1, "d": 2, "f": 3, "h": 4, "g": 5, "z": 6, "x": 7, "c": 8, "v": 9, "b": 11, "q": 12, "w": 13,+ "e": 14, "r": 15, "y": 16, "t": 17, "1": 18, "2": 19, "3": 20, "4": 21, "6": 22, "5": 23, "=": 24, "9": 25,+ "7": 26, "-": 27, "8": 28, "0": 29, "]": 30, "o": 31, "u": 32, "[": 33, "i": 34, "p": 35, "l": 37, "j": 38,+ "k": 40, ";": 41, ",": 43, "/": 44, "n": 45, "m": 46, ".": 47, "\t": 48]+ let code = codes[chars] ?? 0+ window.makeKeyAndOrderFront(nil)+ for type in [NSEvent.EventType.keyDown, .keyUp] {+ if let ev = NSEvent.keyEvent(with: type, location: .zero, modifierFlags: flags, timestamp: ProcessInfo.processInfo.systemUptime,+ windowNumber: window.windowNumber, context: nil, characters: chars, charactersIgnoringModifiers: chars,+ isARepeat: false, keyCode: code) {+ NSApp.sendEvent(ev)+ }+ }+ case "import":+ // Headless import (scripting): cra://import?source=arc&archive=1&settings=1+ let plan = try? (q("source") == "dia" ? DiaImporter.plan() : ArcImporter.plan())+ if let plan {+ let r = store.apply(plan, includeArchive: q("archive") != "0", includeSettings: q("settings") != "0")+ favicons.reset()+ NSLog("Cra: imported %d spaces, %d tabs, %d folders, %d archived", r.spaces, r.tabs, r.folders, r.archived)+ }+ case "debug":+ var dict: [String: String] = [:]+ for item in comps?.queryItems ?? [] { if let v = item.value { dict[item.name] = v } }+ CraTuning.shared.apply(dict)+ main.refresh()+ if let w = main.window {+ let v = main.shell.vibrancy+ NSLog("Cra debug: opaque=%d bg=%@ key=%d main=%d vibHidden=%d state=%ld material=%ld blend=%ld appearance=%@ shellLayerOpaque=%d contentViewIsShell=%d",+ w.isOpaque ? 1 : 0, String(describing: w.backgroundColor), w.isKeyWindow ? 1 : 0, w.isMainWindow ? 1 : 0,+ v.isHidden ? 1 : 0, v.state.rawValue, v.material.rawValue, v.blendingMode.rawValue, String(describing: v.effectiveAppearance.name.rawValue),+ (main.shell.layer?.isOpaque ?? false) ? 1 : 0, (w.contentView === main.shell) ? 1 : 0)+ }+ case "dismiss":+ main.dismissTransientUI()+ settingsWindow?.close()+ archiveWindow?.close()+ accountWindow?.close()+ case "auth-callback":+ if account.handleAuthCallback(u) {+ // Close the Google consent tab, if it is still around.+ for t in store.allTabs() where (t.tab?.url ?? "").contains("/google-callback") || (t.tab?.url ?? "").contains("accounts.google.com") {+ store.archiveTab(t.id, reason: .manual)+ }+ Task { await pullSettingsIfNewer(); await account.refreshBackups() }+ showAccountWindow()+ }+ default:+ break+ }+ }++ // MARK: Actions++ @objc func menuAction(_ sender: NSMenuItem) {+ guard let id = sender.representedObject as? String else { return }+ perform(id)+ }++ func validateMenuItem(_ item: NSMenuItem) -> Bool {+ switch item.representedObject as? String {+ case "toggleSidebar": item.title = store.prefs.sidebarVisible ? "Hide Sidebar" : "Show Sidebar"+ case "toggleToolbar": item.title = store.settings.showToolbar ? "Hide Toolbar" : "Show Toolbar"+ case "toggleDeveloperMode":+ let on = store.selectedTab?.tab.map { store.settings.isDeveloperMode(url: $0.url) } ?? false+ item.title = on ? "Turn off Developer Mode for this Site" : "Turn on Developer Mode for this Site"+ case "pinTab": item.title = store.selectedTabID.map { store.isPinned($0) ? "Unpin Tab" : "Pin Tab" } ?? "Pin/Unpin Tab"+ case "signIn": item.title = account.isSignedIn ? "Account…" : "Sign In…"+ default: break+ }+ return true+ }++ /// Reserved shortcuts (CEF OnPreKeyEvent).+ func handleReservedKey(_ event: NSEvent) -> Bool {+ guard let action = bindings.action(for: event), Self.reservedActions.contains(action.id) else { return false }+ perform(action.id)+ return true+ }++ /// Keys the page let through (CEF OnKeyEvent). Anything we know runs here;+ /// returning false lets CEF pass the key on to the menu bar (⌘Q, ⌘H…).+ func handleUnhandledKey(_ event: NSEvent) -> Bool {+ guard let action = bindings.action(for: event) else { return false }+ perform(action.id)+ return true+ }++ func perform(_ id: String) {+ store.recordCommandUse(id)+ let current = store.selectedTabID+ switch id {+ case "newTab", "newWindow": main.openCommandBar(.newTab)+ case "editURL": main.openCommandBar(.editURL)+ case "newFolder":+ let f = store.createFolder(named: "New Folder", in: store.focusedSpace.pinnedContainerID, index: 0)+ main.sidebarUI.renamingID = f.id+ case "newSpace": main.showSpaceEditor(space: nil)+ case "editSpace": main.showSpaceEditor(space: store.focusedSpace)+ case "deleteSpace": confirmDeleteSpace(store.focusedSpace)+ case "closeTab":+ // Arc: "Close current tab or window".+ if current != nil { main.closeCurrentTab() } else { main.window?.performClose(nil) }+ case "closeWindow": main.window?.performClose(nil)+ case "reopenClosedTab": store.reopenLastArchived()+ case "copyURL":+ if let url = current.flatMap({ store.item($0)?.tab?.url }) { copy(url) }+ case "copyURLMarkdown":+ if let c = current, let it = store.item(c), let url = it.tab?.url { copy("[\(it.displayTitle)](\(url))") }+ case "print": main.currentBrowser?.print()+ case "capturePage": main.capturePage()+ case "find": main.showFindBar()+ case "findNext": main.findNext(forward: true)+ case "findPrevious": main.findNext(forward: false)+ case "toggleSidebar": main.toggleSidebar()+ case "toggleToolbar": store.settings.showToolbar.toggle()+ case "toggleDeveloperMode": if let url = store.selectedTab?.tab?.url { store.settings.toggleDeveloperMode(url: url) }+ case "reload": main.currentBrowser?.reload()+ case "hardReload": main.currentBrowser?.reloadIgnoringCache()+ case "stop": main.currentBrowser?.stopLoading()+ case "zoomIn": main.zoom(by: 0.5)+ case "zoomOut": main.zoom(by: -0.5)+ case "resetZoom": main.currentBrowser?.setZoomLevel(0)+ case "viewSource": main.currentBrowser?.viewSource()+ case "devTools", "jsConsole":+ // Toggle, like Chrome: ⌥⌘I closes the dock when it is already open.+ if let b = main.currentBrowser { b.hasDevTools ? b.closeDevTools() : b.showDevTools() }+ case "inspectElement": main.currentBrowser?.showDevTools()+ case "viewArchive", "openLibrary": showArchiveWindow()+ case "viewDownloads":+ NSWorkspace.shared.open(FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0])+ case "goBack": main.currentBrowser?.goBack()+ case "goForward": main.currentBrowser?.goForward()+ case "pinTab": if let c = current { store.togglePinned(c) }+ case "favoriteTab":+ if let c = current { store.isFavorite(c) ? store.removeFromFavorites(c) : store.addToFavorites(c) }+ case "renameTab": main.sidebarUI.renamingID = current+ case "duplicateTab": if let c = current { store.duplicateTab(c) }+ case "resetTab": if let c = current { main.resetPinnedTab(c) }+ case "muteTab":+ if let c = current, let t = store.item(c)?.tab {+ store.setMuted(c, !t.muted)+ main.browsers.runtime(for: c)?.browser.setAudioMuted(!t.muted)+ }+ case "clearToday": store.clearToday()+ case "nextTab": main.cycleTab(1); markKeyboardFocus()+ case "previousTab": main.cycleTab(-1); markKeyboardFocus()+ case "recentTab": if let id = store.mostRecentOtherTab() { store.selectTab(id); markKeyboardFocus() }+ case "nextSpace": store.focusSpace(offset: 1)+ case "previousSpace": store.focusSpace(offset: -1)+ case "settings": showSettingsWindow()+ case "signIn": showAccountWindow()+ case "importData": main.showImport()+ default:+ if id.hasPrefix("item"), let n = Int(id.dropFirst(4)) {+ let tabs = store.visibleTabs(in: store.focusedSpaceID)+ if n - 1 < tabs.count { store.selectTab(tabs[n - 1].id); markKeyboardFocus() }+ } else if id.hasPrefix("space"), let n = Int(id.dropFirst(5)) {+ if n - 1 < store.spaceOrder.count { store.focusSpace(store.spaceOrder[n - 1]) }+ }+ }+ }++ private func copy(_ s: String) {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(s, forType: .string)+ }++ func confirmDeleteSpace(_ space: Space) {+ guard store.spaceOrder.count > 1 else {+ let a = NSAlert()+ a.messageText = "You need at least one space."+ a.runModal()+ return+ }+ let a = NSAlert()+ a.messageText = "Delete “\(space.title)”?"+ a.informativeText = "Its tabs move to the archive, where you can restore them."+ a.addButton(withTitle: "Delete")+ a.addButton(withTitle: "Cancel")+ a.alertStyle = .warning+ if a.runModal() == .alertFirstButtonReturn { store.deleteSpace(space.id) }+ }++ func startGoogleSignIn() {+ Task {+ guard let url = await account.googleSignInURL() else {+ account.lastError = "Google sign-in is not configured on the server."+ return+ }+ store.createTab(url: url.absoluteString, select: true)+ main.showWindow(nil)+ }+ }++ // MARK: Windows++ func showSettingsWindow() {+ if settingsWindow == nil {+ let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 540, height: 640), styleMask: [.titled, .closable], backing: .buffered, defer: false)+ w.title = "Settings"+ w.contentView = NSHostingView(rootView: SettingsView(onImport: { [weak self] in self?.main.showImport() },+ onAccount: { [weak self] in self?.showAccountWindow() })+ .environment(store).environment(bindings).environment(account))+ w.isReleasedWhenClosed = false+ w.center()+ settingsWindow = w+ }+ settingsWindow?.makeKeyAndOrderFront(nil)+ }++ func showAccountWindow() {+ if accountWindow == nil {+ let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 420, height: 360), styleMask: [.titled, .closable], backing: .buffered, defer: false)+ w.title = "Cra Account"+ w.contentView = NSHostingView(rootView: AccountView(onGoogle: { [weak self] in self?.startGoogleSignIn() },+ onRestore: { [weak self] doc in self?.store.replaceDocument(doc) })+ .environment(account).environment(store))+ w.isReleasedWhenClosed = false+ w.center()+ accountWindow = w+ }+ accountWindow?.makeKeyAndOrderFront(nil)+ }++ func showArchiveWindow() {+ if archiveWindow == nil {+ let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 720, height: 560), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)+ w.title = "Library"+ w.contentView = NSHostingView(rootView: ArchiveView(onRestore: { [weak self] id in+ self?.store.restoreArchived(id)+ self?.archiveWindow?.close()+ self?.main.showWindow(nil)+ }).environment(store).environment(favicons))+ w.isReleasedWhenClosed = false+ w.center()+ archiveWindow = w+ }+ archiveWindow?.makeKeyAndOrderFront(nil)+ }++ // MARK: Menus (Arc's layout)++ private func item(_ id: String) -> NSMenuItem {+ guard let a = bindings.action(id) else { return NSMenuItem() }+ let m = NSMenuItem(title: a.name, action: #selector(menuAction(_:)), keyEquivalent: "")+ m.representedObject = a.id+ m.target = self+ if let s = a.primary {+ m.keyEquivalent = s.key+ m.keyEquivalentModifierMask = s.flags+ }+ return m+ }++ private func std(_ title: String, _ sel: Selector, _ key: String = "", _ mods: NSEvent.ModifierFlags = .command) -> NSMenuItem {+ let m = NSMenuItem(title: title, action: sel, keyEquivalent: key)+ m.keyEquivalentModifierMask = mods+ return m+ }++ func buildMenus() {+ let menubar = NSMenu()++ let appMenu = NSMenu(title: "Cra")+ appMenu.addItem(withTitle: "About Cra", action: #selector(showAbout), keyEquivalent: "").target = self+ appMenu.addItem(.separator())+ appMenu.addItem(item("settings"))+ appMenu.addItem(item("signIn"))+ appMenu.addItem(item("importData"))+ appMenu.addItem(.separator())+ appMenu.addItem(std("Hide Cra", #selector(NSApplication.hide(_:)), "h"))+ appMenu.addItem(std("Hide Others", #selector(NSApplication.hideOtherApplications(_:)), "h", [.command, .option]))+ appMenu.addItem(std("Show All", #selector(NSApplication.unhideAllApplications(_:))))+ appMenu.addItem(.separator())+ appMenu.addItem(std("Quit Cra", #selector(NSApplication.terminate(_:)), "q"))+ menubar.addItem(submenu: appMenu, title: "Cra")++ let file = NSMenu(title: "File")+ for id in ["newTab", "newWindow", "reopenClosedTab", "editURL", "newFolder", "newSpace"] { file.addItem(item(id)) }+ file.addItem(.separator())+ file.addItem(item("closeWindow")); file.addItem(item("closeTab"))+ file.addItem(.separator())+ file.addItem(item("capturePage")); file.addItem(item("print"))+ menubar.addItem(submenu: file, title: "File")++ let edit = NSMenu(title: "Edit")+ edit.addItem(std("Undo", Selector(("undo:")), "z"))+ edit.addItem(std("Redo", Selector(("redo:")), "z", [.command, .shift]))+ edit.addItem(.separator())+ edit.addItem(std("Cut", #selector(NSText.cut(_:)), "x"))+ edit.addItem(std("Copy", #selector(NSText.copy(_:)), "c"))+ edit.addItem(item("copyURL")); edit.addItem(item("copyURLMarkdown"))+ edit.addItem(std("Paste", #selector(NSText.paste(_:)), "v"))+ edit.addItem(std("Paste and Match Style", Selector(("pasteAsPlainText:")), "v", [.command, .shift]))+ edit.addItem(std("Delete", #selector(NSText.delete(_:))))+ edit.addItem(std("Select All", #selector(NSText.selectAll(_:)), "a"))+ edit.addItem(.separator())+ let find = NSMenu(title: "Find")+ find.addItem(item("find")); find.addItem(item("findNext")); find.addItem(item("findPrevious"))+ edit.addItem(submenu: find, title: "Find")+ menubar.addItem(submenu: edit, title: "Edit")++ let view = NSMenu(title: "View")+ view.addItem(item("toggleSidebar")); view.addItem(item("toggleToolbar"))+ view.addItem(.separator())+ view.addItem(item("stop")); view.addItem(item("reload")); view.addItem(item("hardReload"))+ view.addItem(.separator())+ view.addItem(item("resetZoom")); view.addItem(item("zoomIn")); view.addItem(item("zoomOut"))+ view.addItem(.separator())+ let dev = NSMenu(title: "Developer")+ for id in ["viewSource", "devTools", "inspectElement", "jsConsole"] { dev.addItem(item(id)) }+ dev.addItem(.separator())+ dev.addItem(item("toggleDeveloperMode"))+ view.addItem(submenu: dev, title: "Developer")+ view.addItem(.separator())+ view.addItem(std("Enter Full Screen", #selector(NSWindow.toggleFullScreen(_:)), "f", [.command, .control]))+ menubar.addItem(submenu: view, title: "View")++ let spaces = NSMenu(title: "Spaces")+ spaces.addItem(item("nextSpace")); spaces.addItem(item("previousSpace"))+ spaces.addItem(.separator())+ spaces.addItem(item("editSpace")); spaces.addItem(item("deleteSpace"))+ spaces.addItem(.separator())+ for n in 1...9 { spaces.addItem(item("space\(n)")) }+ menubar.addItem(submenu: spaces, title: "Spaces")++ let tabs = NSMenu(title: "Tabs")+ for id in ["newTab", "pinTab", "nextTab", "previousTab", "recentTab", "clearToday"] { tabs.addItem(item(id)) }+ tabs.addItem(.separator())+ for id in ["favoriteTab", "renameTab", "duplicateTab", "resetTab", "muteTab"] { tabs.addItem(item(id)) }+ tabs.addItem(.separator())+ for n in 1...9 { tabs.addItem(item("item\(n)")) }+ menubar.addItem(submenu: tabs, title: "Tabs")++ let archive = NSMenu(title: "Archive")+ archive.addItem(item("goBack")); archive.addItem(item("goForward")); archive.addItem(item("viewArchive"))+ menubar.addItem(submenu: archive, title: "Archive")++ let window = NSMenu(title: "Window")+ window.addItem(std("Minimize Window", #selector(NSWindow.performMiniaturize(_:)), "m"))+ window.addItem(std("Zoom", #selector(NSWindow.performZoom(_:))))+ window.addItem(.separator())+ window.addItem(item("openLibrary")); window.addItem(item("viewDownloads"))+ window.addItem(.separator())+ window.addItem(std("Bring All to Front", #selector(NSApplication.arrangeInFront(_:))))+ menubar.addItem(submenu: window, title: "Window")+ NSApp.windowsMenu = window++ let help = NSMenu(title: "Help")+ help.addItem(withTitle: "Chromium \(CraCEFRuntime.chromiumVersion()) · CEF \(CraCEFRuntime.cefVersion())", action: nil, keyEquivalent: "")+ menubar.addItem(submenu: help, title: "Help")+ NSApp.helpMenu = help++ NSApp.mainMenu = menubar+ }++ @objc private func showAbout() {+ NSApp.orderFrontStandardAboutPanel(options: [+ .applicationName: "Cra",+ .applicationVersion: "0.2",+ .version: "Chromium \(CraCEFRuntime.chromiumVersion())",+ ])+ }+}++private extension NSMenu {+ func addItem(submenu: NSMenu, title: String) {+ let item = NSMenuItem(title: title, action: nil, keyEquivalent: "")+ item.submenu = submenu+ addItem(item)+ }+}diff --git a/Sources/Cra/App/KeyBindings.swift b/Sources/Cra/App/KeyBindings.swiftnew file mode 100644index 0000000..5b1be13--- /dev/null+++ b/Sources/Cra/App/KeyBindings.swift@@ -0,0 +1,227 @@+import AppKit+import Observation++/// A keyboard shortcut. `key` is the lowercase character or a special key+/// (see `Shortcut.tab`, `.left`...), `modifiers` the device-independent flags.+struct Shortcut: Codable, Hashable {+ var key: String+ var modifiers: UInt++ init(_ key: String, _ mods: NSEvent.ModifierFlags) {+ self.key = key+ self.modifiers = mods.intersection(.deviceIndependentFlagsMask).rawValue+ }++ static let tab = "\t"+ static let left = String(UnicodeScalar(NSLeftArrowFunctionKey)!)+ static let right = String(UnicodeScalar(NSRightArrowFunctionKey)!)+ static let up = String(UnicodeScalar(NSUpArrowFunctionKey)!)+ static let down = String(UnicodeScalar(NSDownArrowFunctionKey)!)++ var flags: NSEvent.ModifierFlags { NSEvent.ModifierFlags(rawValue: modifiers) }++ /// Shift turns "[" into "{" in charactersIgnoringModifiers; undo that.+ private static let unshift: [String: String] = ["{": "[", "}": "]", "<": ",", ">": ".", "?": "/", "+": "=", "_": "-", "~": "`", ":": ";", "\"": "'", "|": "\\"]++ /// Physical-key fallbacks so ⌘[ / ⌘] work on layouts (Danish, German...)+ /// where those characters live on other keys. Key codes are ANSI positions.+ private static let keyCodeFor: [String: UInt16] = ["[": 33, "]": 30, "=": 24, "-": 27, ",": 43, ".": 47, "/": 44, ";": 41, "'": 39, "`": 50, "\\": 42]++ func matches(_ event: NSEvent) -> Bool {+ // charactersIgnoringModifiers throws on flagsChanged events, which+ // Chromium forwards as raw key-downs for modifier keys.+ guard event.type == .keyDown else { return false }+ let evFlags = event.modifierFlags.intersection([.command, .shift, .option, .control])+ guard evFlags == flags.intersection([.command, .shift, .option, .control]) else { return false }+ guard var chars = event.charactersIgnoringModifiers, !chars.isEmpty else { return false }+ chars = chars.lowercased()+ if let u = Self.unshift[chars] { chars = u }+ if chars == key { return true }+ if let code = Self.keyCodeFor[key], event.keyCode == code { return true }+ return false+ }++ /// Build a shortcut from a recorded key press (nil for bare letters without ⌘/⌃/⌥).+ static func from(event e: NSEvent) -> Shortcut? {+ guard e.type == .keyDown, var chars = e.charactersIgnoringModifiers, !chars.isEmpty else { return nil }+ let flags = e.modifierFlags.intersection([.command, .shift, .option, .control])+ chars = chars.lowercased()+ if let u = unshift[chars] { chars = u }+ let special = [tab, left, right, up, down].contains(chars) || (chars.unicodeScalars.first.map { $0.value >= 0xF704 && $0.value <= 0xF71F } ?? false)+ guard special || !flags.intersection([.command, .control, .option]).isEmpty else { return nil }+ return Shortcut(chars, flags)+ }++ var display: String {+ var s = ""+ if flags.contains(.control) { s += "⌃" }+ if flags.contains(.option) { s += "⌥" }+ if flags.contains(.shift) { s += "⇧" }+ if flags.contains(.command) { s += "⌘" }+ switch key {+ case Shortcut.tab: s += "⇥"+ case Shortcut.left: s += "←"+ case Shortcut.right: s += "→"+ case Shortcut.up: s += "↑"+ case Shortcut.down: s += "↓"+ default: s += key.uppercased()+ }+ return s+ }+}++enum MenuSection: String, Codable {+ case app, file, edit, view, tabs, spaces, archive, window, help, none+}++/// An app command. Arc keeps the same shape: identifier + name + default+/// shortcut + the phrases type-travel matches ("typeTravelTriggers").+struct KeyAction: Identifiable, Hashable {+ let id: String+ let name: String+ let section: MenuSection+ var shortcuts: [Shortcut]+ var triggers: [String] = []+ var inCommandBar: Bool = true++ var primary: Shortcut? { shortcuts.first }+}++/// The action table plus user overrides (keybindings.json).+@MainActor+@Observable+final class KeyBindingRegistry {+ private(set) var actions: [KeyAction]+ @ObservationIgnored private let overridesFile = JSONStore<[String: [Shortcut]]>("keybindings.json")+ @ObservationIgnored private var overrides: [String: [Shortcut]]++ init() {+ actions = KeyBindingRegistry.defaults+ overrides = overridesFile.load(or: { [:] })+ apply()+ }++ private func apply() {+ for i in actions.indices {+ if let o = overrides[actions[i].id] { actions[i].shortcuts = o }+ }+ }++ func action(_ id: String) -> KeyAction? { actions.first { $0.id == id } }++ func setShortcuts(_ shortcuts: [Shortcut], for id: String) {+ overrides[id] = shortcuts+ overridesFile.save(overrides)+ apply()+ NotificationCenter.default.post(name: .craKeyBindingsChanged, object: nil)+ }++ func isOverridden(_ id: String) -> Bool { overrides[id] != nil }++ func resetShortcuts(for id: String) {+ overrides[id] = nil+ overridesFile.save(overrides)+ if let d = KeyBindingRegistry.defaults.first(where: { $0.id == id }), let i = actions.firstIndex(where: { $0.id == id }) {+ actions[i].shortcuts = d.shortcuts+ }+ NotificationCenter.default.post(name: .craKeyBindingsChanged, object: nil)+ }++ func resetOverrides() {+ overrides = [:]+ overridesFile.saveNow(overrides)+ actions = KeyBindingRegistry.defaults+ NotificationCenter.default.post(name: .craKeyBindingsChanged, object: nil)+ }++ /// First action whose shortcut matches the key event.+ func action(for event: NSEvent) -> KeyAction? {+ for a in actions where a.shortcuts.contains(where: { $0.matches(event) }) { return a }+ return nil+ }++ func actions(in section: MenuSection) -> [KeyAction] { actions.filter { $0.section == section } }++ // Arc's defaults, read from Arc 1.168's menu bar on this Mac (see+ // docs/arc-reverse-engineering.md, "Key bindings"). Items Cra doesn't+ // have (Little Arc, Easels, Split View, Capture) are left out.+ static let defaults: [KeyAction] = {+ let cmd: NSEvent.ModifierFlags = .command+ let cmdShift: NSEvent.ModifierFlags = [.command, .shift]+ let cmdOpt: NSEvent.ModifierFlags = [.command, .option]+ let cmdOptShift: NSEvent.ModifierFlags = [.command, .option, .shift]+ var list: [KeyAction] = [+ // File+ KeyAction(id: "newTab", name: "New Tab…", section: .file, shortcuts: [Shortcut("t", cmd)], triggers: ["new tab"]),+ KeyAction(id: "newWindow", name: "New Window", section: .file, shortcuts: [Shortcut("n", cmd)], inCommandBar: false),+ KeyAction(id: "reopenClosedTab", name: "Restore Last Closed Tab", section: .file, shortcuts: [Shortcut("t", cmdShift)], triggers: ["reopen", "undo close", "restore"]),+ KeyAction(id: "editURL", name: "Open Command Bar", section: .file, shortcuts: [Shortcut("l", cmd)], triggers: ["url", "address", "command bar"]),+ KeyAction(id: "newFolder", name: "New Folder", section: .file, shortcuts: [], triggers: ["folder"]),+ KeyAction(id: "newSpace", name: "New Space…", section: .file, shortcuts: [], triggers: ["space"]),+ KeyAction(id: "closeWindow", name: "Close Window", section: .file, shortcuts: [Shortcut("w", cmdShift)], inCommandBar: false),+ KeyAction(id: "closeTab", name: "Close Tab", section: .file, shortcuts: [Shortcut("w", cmd)], triggers: ["close", "archive tab"]),+ KeyAction(id: "capturePage", name: "Capture…", section: .file, shortcuts: [Shortcut("2", cmdShift)], triggers: ["capture", "screenshot"]),+ KeyAction(id: "print", name: "Print", section: .file, shortcuts: [Shortcut("p", cmd)]),+ // Edit+ KeyAction(id: "copyURL", name: "Copy URL", section: .edit, shortcuts: [Shortcut("c", cmdShift)], triggers: ["copy link"]),+ KeyAction(id: "copyURLMarkdown", name: "Copy URL as Markdown", section: .edit, shortcuts: [Shortcut("c", cmdOptShift)], triggers: ["markdown"]),+ KeyAction(id: "find", name: "Find…", section: .edit, shortcuts: [Shortcut("f", cmd)], triggers: ["find", "search page"]),+ KeyAction(id: "findNext", name: "Find Next", section: .edit, shortcuts: [Shortcut("g", cmd)], inCommandBar: false),+ KeyAction(id: "findPrevious", name: "Find Previous", section: .edit, shortcuts: [Shortcut("g", cmdShift)], inCommandBar: false),+ // View+ KeyAction(id: "toggleSidebar", name: "Hide Sidebar", section: .view, shortcuts: [Shortcut("s", cmd)], triggers: ["sidebar", "hide sidebar", "show sidebar"]),+ KeyAction(id: "toggleToolbar", name: "Hide Toolbar", section: .view, shortcuts: [Shortcut("d", cmdShift)], triggers: ["toolbar"]),+ KeyAction(id: "stop", name: "Stop Loading", section: .view, shortcuts: [Shortcut(".", cmd)], inCommandBar: false),+ KeyAction(id: "reload", name: "Refresh the Page", section: .view, shortcuts: [Shortcut("r", cmd)], triggers: ["refresh", "reload"]),+ KeyAction(id: "hardReload", name: "Force Refresh the Page", section: .view, shortcuts: [Shortcut("r", cmdShift)]),+ // Arc: View ▸ Developer ▸ "Turn on/off Developer Mode for this site" (⌃D).+ KeyAction(id: "toggleDeveloperMode", name: "Toggle Developer Mode for this Site", section: .view, shortcuts: [Shortcut("d", .control)], triggers: ["developer mode", "dev mode"]),+ KeyAction(id: "resetZoom", name: "Zoom to Actual Size", section: .view, shortcuts: [Shortcut("0", cmd)], triggers: ["reset zoom"]),+ KeyAction(id: "zoomIn", name: "Zoom In", section: .view, shortcuts: [Shortcut("=", cmd), Shortcut("=", cmdShift)]),+ KeyAction(id: "zoomOut", name: "Zoom Out", section: .view, shortcuts: [Shortcut("-", cmd)]),+ KeyAction(id: "viewSource", name: "View Source", section: .view, shortcuts: [Shortcut("u", cmdOpt)]),+ KeyAction(id: "devTools", name: "Developer Tools", section: .view, shortcuts: [Shortcut("i", cmdOpt)], triggers: ["devtools", "inspect", "console"]),+ KeyAction(id: "inspectElement", name: "Inspect Elements", section: .view, shortcuts: [Shortcut("c", cmdOpt)], inCommandBar: false),+ KeyAction(id: "jsConsole", name: "JavaScript Console", section: .view, shortcuts: [Shortcut("j", cmdOpt)], inCommandBar: false),+ // Spaces+ KeyAction(id: "nextSpace", name: "Next Space", section: .spaces, shortcuts: [Shortcut(Shortcut.right, cmdOpt)], inCommandBar: false),+ KeyAction(id: "previousSpace", name: "Previous Space", section: .spaces, shortcuts: [Shortcut(Shortcut.left, cmdOpt)], inCommandBar: false),+ KeyAction(id: "editSpace", name: "Edit Space…", section: .spaces, shortcuts: [], triggers: ["theme", "color", "emoji", "edit space"]),+ KeyAction(id: "deleteSpace", name: "Delete Space…", section: .spaces, shortcuts: [], triggers: ["delete space", "remove space"]),+ // Tabs+ KeyAction(id: "pinTab", name: "Pin/Unpin Tab", section: .tabs, shortcuts: [Shortcut("d", cmd)], triggers: ["pin", "unpin"]),+ KeyAction(id: "nextTab", name: "Next Tab", section: .tabs, shortcuts: [Shortcut(Shortcut.down, cmdOpt)], inCommandBar: false),+ KeyAction(id: "previousTab", name: "Previous Tab", section: .tabs, shortcuts: [Shortcut(Shortcut.up, cmdOpt)], inCommandBar: false),+ KeyAction(id: "recentTab", name: "Toggle Recent Tabs", section: .tabs, shortcuts: [Shortcut(Shortcut.tab, .control)], inCommandBar: false),+ KeyAction(id: "clearToday", name: "Clear Today", section: .tabs, shortcuts: [Shortcut("k", cmdShift)], triggers: ["clear", "tidy"]),+ KeyAction(id: "favoriteTab", name: "Add to Favorites", section: .tabs, shortcuts: [], triggers: ["favorite", "top app"]),+ KeyAction(id: "renameTab", name: "Rename Tab…", section: .tabs, shortcuts: [], triggers: ["rename"]),+ KeyAction(id: "duplicateTab", name: "Duplicate Tab", section: .tabs, shortcuts: [], triggers: ["duplicate"]),+ KeyAction(id: "resetTab", name: "Reset Pinned Tab", section: .tabs, shortcuts: [], triggers: ["reset", "home"]),+ KeyAction(id: "muteTab", name: "Mute / Unmute Tab", section: .tabs, shortcuts: [], triggers: ["mute"]),+ // Archive+ KeyAction(id: "goBack", name: "Go Back", section: .archive, shortcuts: [Shortcut("[", cmd), Shortcut(Shortcut.left, cmd)]),+ KeyAction(id: "goForward", name: "Go Forward", section: .archive, shortcuts: [Shortcut("]", cmd), Shortcut(Shortcut.right, cmd)]),+ KeyAction(id: "viewArchive", name: "View History", section: .archive, shortcuts: [Shortcut("y", cmd)], triggers: ["archive", "history", "closed tabs"]),+ // Window+ KeyAction(id: "openLibrary", name: "Open Library…", section: .window, shortcuts: [Shortcut("l", cmdShift)], triggers: ["library"]),+ KeyAction(id: "viewDownloads", name: "View Downloads…", section: .window, shortcuts: [Shortcut("j", cmdShift)], triggers: ["downloads"]),+ // App+ KeyAction(id: "settings", name: "Settings…", section: .app, shortcuts: [Shortcut(",", cmd)], triggers: ["preferences", "settings"]),+ KeyAction(id: "signIn", name: "Sign In…", section: .app, shortcuts: [], triggers: ["account", "login", "sign in"]),+ KeyAction(id: "importData", name: "Import from Arc or Dia…", section: .app, shortcuts: [], triggers: ["import", "arc", "dia"]),+ ]+ for n in 1...9 {+ list.append(KeyAction(id: "item\(n)", name: "Go to Tab \(n)", section: .tabs,+ shortcuts: [Shortcut("\(n)", cmd)], triggers: ["\(n). tab", "\(n). item"], inCommandBar: false))+ list.append(KeyAction(id: "space\(n)", name: "Go to Space \(n)", section: .spaces,+ shortcuts: [Shortcut("\(n)", .control)], inCommandBar: false))+ }+ return list+ }()+}++extension Notification.Name {+ /// Posted when the user edits shortcuts; the app rebuilds its menus.+ static let craKeyBindingsChanged = Notification.Name("craKeyBindingsChanged")+}diff --git a/Sources/Cra/App/main.swift b/Sources/Cra/App/main.swiftnew file mode 100644index 0000000..a7498b7--- /dev/null+++ b/Sources/Cra/App/main.swift@@ -0,0 +1,37 @@+import AppKit+import CraCEF++MainActor.assumeIsolated {+ // Order matters: the CefAppProtocol NSApplication must exist before Chromium+ // initializes, and Chromium must be initialized before any browser is made.+ let app = CraApplication.shared+ let delegate = AppDelegate()+ app.delegate = delegate++ let useChromeStyle = ProcessInfo.processInfo.environment["CRA_CHROME_STYLE"] == "1"+ let started = CraCEFRuntime.initialize(withCachePath: AppPaths.chromiumCache.path,+ userAgentProduct: "",+ logPath: AppPaths.log.path,+ useChromeStyle: useChromeStyle)+ if !started && CraCEFRuntime.anotherInstanceWasNotified() {+ // The running Cra got our command line; just activate it.+ NSRunningApplication.runningApplications(withBundleIdentifier: Bundle.main.bundleIdentifier ?? "dk.kildahl.cra")+ .first { $0.processIdentifier != ProcessInfo.processInfo.processIdentifier }?+ .activate()+ exit(0)+ }+ if !started {+ let alert = NSAlert()+ alert.messageText = "Cra could not start Chromium"+ alert.informativeText = "Chromium Embedded Framework failed to initialize. See \(AppPaths.log.path)."+ alert.runModal()+ exit(1)+ }++ // Belt and braces: Chromium's run loop drives NSApplication and should call+ // applicationDidFinishLaunching, but bootstrapping is idempotent either way.+ DispatchQueue.main.async { delegate.bootstrapIfNeeded() }+ CraCEFRuntime.runMessageLoop()+ delegate.applicationWillShutdown()+ CraCEFRuntime.shutdown()+}diff --git a/Sources/Cra/Model/SidebarModel.swift b/Sources/Cra/Model/SidebarModel.swiftnew file mode 100644index 0000000..e1cad46--- /dev/null+++ b/Sources/Cra/Model/SidebarModel.swift@@ -0,0 +1,346 @@+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.++typealias ItemID = UUID++enum ContainerKind: Codable, Equatable, Hashable {+ case favorites+ case pinned(spaceID: UUID)+ case today(spaceID: UUID)++ var spaceID: UUID? {+ switch self {+ case .favorites: return nil+ case .pinned(let id), .today(let id): return id+ }+ }+}++struct TabData: Codable, Equatable {+ /// Where the tab currently is. Restored on relaunch.+ var url: String+ /// The "home" of the tab. For pinned tabs this is what reset returns to;+ /// for today tabs it is just the URL the tab was created with.+ var savedURL: String+ /// Last known page title.+ var savedTitle: String+ var muted: Bool = false+ var timeLastActiveAt: Date?+ var activeTabBeforeCreationID: UUID?+ /// Host used as favicon cache key.+ var faviconKey: String?++ init(url: String, title: String = "") {+ self.url = url+ self.savedURL = url+ self.savedTitle = title+ self.faviconKey = URL(string: url)?.host+ }+}++enum ItemData: Codable, Equatable {+ case tab(TabData)+ case folder+ case container(ContainerKind)+}++struct SidebarItem: Identifiable, Codable, Equatable {+ var id: UUID+ var parentID: UUID?+ /// Custom title set by renaming. nil means "use the page title".+ var title: String?+ var children: [UUID]+ var isUnread: Bool+ var createdAt: Date+ var data: ItemData++ var tab: TabData? {+ if case .tab(let t) = data { return t }+ return nil+ }+ var isTab: Bool { tab != nil }+ var isFolder: Bool { if case .folder = data { return true }; return false }+ var container: ContainerKind? {+ if case .container(let c) = data { return c }+ return nil+ }++ /// What the sidebar shows: the custom name wins over the page title,+ /// which wins over the host.+ var displayTitle: String {+ if let t = title, !t.isEmpty { return t }+ if let tab {+ if !tab.savedTitle.isEmpty { return tab.savedTitle }+ if let host = URL(string: tab.url)?.host { return host }+ return tab.url+ }+ return "Untitled"+ }++ static func tab(_ url: String, title: String = "", parent: UUID?) -> SidebarItem {+ SidebarItem(id: UUID(), parentID: parent, title: nil, children: [], isUnread: false,+ createdAt: Date(), data: .tab(TabData(url: url, title: title)))+ }++ static func folder(_ name: String, parent: UUID?) -> SidebarItem {+ SidebarItem(id: UUID(), parentID: parent, title: name, children: [], isUnread: false,+ createdAt: Date(), data: .folder)+ }++ static func container(_ kind: ContainerKind, id: UUID = UUID()) -> SidebarItem {+ SidebarItem(id: id, parentID: nil, title: nil, children: [], isUnread: false,+ createdAt: Date(), data: .container(kind))+ }+}++struct SpaceTheme: Codable, Equatable {+ /// One or two hex colors blended into a gradient (Arc: blendedGradient.baseColors).+ var colors: [String]+ /// 0...1, how saturated the gradient is rendered (Arc: intensityFactor).+ var intensity: Double+ /// 0...1 grain overlay (Arc: noiseFactor).+ var noise: Double+ /// "auto" | "light" | "dark" (Arc: contentOverBackgroundAppearance).+ var appearance: String+ /// Arc's isVibrant: the gradient is laid over the blurred desktop at+ /// `intensity` opacity instead of being painted opaque.+ var vibrant: Bool = false+ /// The theme's raw first colour (Arc's base colour); drives the toolbar band.+ var accent: String? = nil++ init(colors: [String], intensity: Double, noise: Double, appearance: String, vibrant: Bool = false, accent: String? = nil) {+ self.colors = colors+ self.intensity = intensity+ self.noise = noise+ self.appearance = appearance+ self.vibrant = vibrant+ self.accent = accent+ }++ init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ colors = try c.decodeIfPresent([String].self, forKey: .colors) ?? ["#1C242B", "#3A3660"]+ intensity = try c.decodeIfPresent(Double.self, forKey: .intensity) ?? 0.8+ noise = try c.decodeIfPresent(Double.self, forKey: .noise) ?? 0.15+ appearance = try c.decodeIfPresent(String.self, forKey: .appearance) ?? "auto"+ vibrant = try c.decodeIfPresent(Bool.self, forKey: .vibrant) ?? false+ accent = try c.decodeIfPresent(String.self, forKey: .accent)+ }++ /// Dark first: colors borrowed from Victor's other projects (GhostWriter+ /// ink + brand purple, Spook's "wall" browns, Phantom's greys, moss, gold,+ /// ember), then a few lighter Arc-style gradients.+ static let presets: [SpaceTheme] = [+ SpaceTheme(colors: ["#1C242B", "#3A3660"], intensity: 0.85, noise: 0.18, appearance: "dark"), // Ink+ SpaceTheme(colors: ["#1C1712", "#2E2620"], intensity: 0.9, noise: 0.22, appearance: "dark"), // Wall+ SpaceTheme(colors: ["#181818", "#262626"], intensity: 0.9, noise: 0.12, appearance: "dark"), // Phantom+ SpaceTheme(colors: ["#0F2420", "#2F6F5E"], intensity: 0.75, noise: 0.18, appearance: "dark"), // Moss+ SpaceTheme(colors: ["#2A1A14", "#A2481D"], intensity: 0.7, noise: 0.2, appearance: "dark"), // Ember+ SpaceTheme(colors: ["#2A2310", "#7A5C0F"], intensity: 0.75, noise: 0.2, appearance: "dark"), // Gold+ SpaceTheme(colors: ["#241C3A", "#6944AE"], intensity: 0.75, noise: 0.18, appearance: "dark"), // Brand+ SpaceTheme(colors: ["#F8D558", "#A4F554"], intensity: 0.45, noise: 0.25, appearance: "light"),+ SpaceTheme(colors: ["#C7CAFF", "#FFE5E5"], intensity: 0.5, noise: 0.1, appearance: "light"),+ SpaceTheme(colors: ["#F4F1EA", "#E6DCC8"], intensity: 0.6, noise: 0.15, appearance: "light"), // Parchment+ ]++ var isDark: Bool {+ if appearance == "dark" { return true }+ if appearance == "light" { return false }+ // auto: judge by the first color's luminance+ return (colors.first.flatMap(HexColor.luminance) ?? 1) < 0.45+ }+}++enum HexColor {+ static func components(_ hex: String) -> (r: Double, g: Double, b: Double)? {+ var s = hex.trimmingCharacters(in: .whitespaces)+ if s.hasPrefix("#") { s.removeFirst() }+ guard s.count == 6, let v = UInt32(s, radix: 16) else { return nil }+ return (Double((v >> 16) & 0xff) / 255, Double((v >> 8) & 0xff) / 255, Double(v & 0xff) / 255)+ }+ static func luminance(_ hex: String) -> Double? {+ guard let c = components(hex) else { return nil }+ return 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b+ }+}++struct Space: Identifiable, Codable, Equatable {+ var id: UUID+ var title: String+ var emoji: String+ var theme: SpaceTheme+ var pinnedContainerID: UUID+ var todayContainerID: UUID+ var createdAt: Date+}++struct SidebarDocument: Codable {+ var version: Int = 1+ var spaceOrder: [UUID]+ var spaces: [Space]+ var favoritesContainerID: UUID+ var items: [SidebarItem]++ static func fresh() -> SidebarDocument {+ let fav = SidebarItem.container(.favorites)+ let spaceID = UUID()+ 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],+ pinnedContainerID: pinned.id, todayContainerID: today.id, createdAt: Date())+ return SidebarDocument(spaceOrder: [spaceID], spaces: [space], favoritesContainerID: fav.id,+ items: [fav, pinned, today])+ }+}++enum ArchiveReason: String, Codable {+ case manual, auto, clear, spaceDeleted+}++struct ArchivedItem: Codable, Identifiable, Equatable {+ var id: UUID { item.id }+ var archivedAt: Date+ var reason: ArchiveReason+ var sourceSpaceID: UUID?+ var wasPinned: Bool+ var item: SidebarItem+}++enum AutoArchiveThreshold: String, Codable, CaseIterable, Identifiable {+ case twelveHours, twentyFourHours, sevenDays, thirtyDays+ var id: String { rawValue }+ var seconds: TimeInterval {+ switch self {+ case .twelveHours: return 12 * 3600+ case .twentyFourHours: return 24 * 3600+ case .sevenDays: return 7 * 86400+ case .thirtyDays: return 30 * 86400+ }+ }+ var label: String {+ switch self {+ case .twelveHours: return "12 hours"+ case .twentyFourHours: return "24 hours"+ case .sevenDays: return "7 days"+ case .thirtyDays: return "30 days"+ }+ }+}++enum SearchEngine: String, Codable, CaseIterable, Identifiable {+ case google, duckduckgo, bing, kagi+ var id: String { rawValue }+ var label: String {+ switch self {+ case .google: return "Google"+ case .duckduckgo: return "DuckDuckGo"+ case .bing: return "Bing"+ case .kagi: return "Kagi"+ }+ }+ func searchURL(_ query: String) -> String {+ let q = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)?+ .replacingOccurrences(of: "&", with: "%26") ?? query+ switch self {+ case .google: return "https://www.google.com/search?q=\(q)"+ case .duckduckgo: return "https://duckduckgo.com/?q=\(q)"+ case .bing: return "https://www.bing.com/search?q=\(q)"+ case .kagi: return "https://kagi.com/search?q=\(q)"+ }+ }+}++struct AppSettings: Codable, Equatable {+ var autoArchive: AutoArchiveThreshold = .twelveHours+ var searchEngine: SearchEngine = .google+ var newTabsAtTop: Bool = true+ var showStatusBar: Bool = true+ /// Arc's toolbar above the page (URL, copy link, DevTools). ⇧⌘D toggles.+ var showToolbar: Bool = true+ var hasSeenImportPrompt: Bool = false+ /// Arc's per-site Developer Mode (⌃D): the toolbar shows the full URL in+ /// monospace with the developer icons, and the nav buttons move to the sidebar.+ var developerHosts: Set<String> = []++ init() {}++ static func siteKey(for url: String) -> String? {+ URL(string: url)?.host?.lowercased().replacingOccurrences(of: "www.", with: "")+ }+ func isDeveloperMode(url: String) -> Bool { AppSettings.siteKey(for: url).map(developerHosts.contains) ?? false }+ mutating func toggleDeveloperMode(url: String) {+ guard let k = AppSettings.siteKey(for: url) else { return }+ if developerHosts.contains(k) { developerHosts.remove(k) } else { developerHosts.insert(k) }+ }+}++struct WindowPrefs: Codable, Equatable {+ var sidebarWidth: Double = 328+ var sidebarVisible: Bool = true+ var focusedSpaceID: UUID?+ var expandedFolders: Set<UUID> = []+ var collapsedPinnedSpaces: Set<UUID> = []+ var selectedTabPerSpace: [UUID: UUID] = [:]+ var windowFrame: String?+}++struct HistoryEntry: Codable, Equatable {+ var url: String+ var title: String+ var lastVisit: Date+ var visitCount: Int+}++/// Signals the command bar learns from, mirroring Arc's+/// StorableCommandBarAdditionalRanking.json (recentlySwitchedToTabs,+/// queriesToSelectedArchetype, typeTravelUsage).+struct RankingData: Codable, Equatable {+ var recentlySwitchedToTabs: [UUID: [Date]] = [:]+ var queriesToSelected: [String: String] = [:]+ var commandUsage: [String: Int] = [:]+}+++// Tolerant decoding so new preference keys never reset the file.+extension AppSettings {+ init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ autoArchive = try c.decodeIfPresent(AutoArchiveThreshold.self, forKey: .autoArchive) ?? .twelveHours+ searchEngine = try c.decodeIfPresent(SearchEngine.self, forKey: .searchEngine) ?? .google+ newTabsAtTop = try c.decodeIfPresent(Bool.self, forKey: .newTabsAtTop) ?? true+ showStatusBar = try c.decodeIfPresent(Bool.self, forKey: .showStatusBar) ?? true+ showToolbar = try c.decodeIfPresent(Bool.self, forKey: .showToolbar) ?? true+ hasSeenImportPrompt = try c.decodeIfPresent(Bool.self, forKey: .hasSeenImportPrompt) ?? false+ developerHosts = try c.decodeIfPresent(Set<String>.self, forKey: .developerHosts) ?? []+ }+}++extension WindowPrefs {+ init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ sidebarWidth = try c.decodeIfPresent(Double.self, forKey: .sidebarWidth) ?? 328+ sidebarVisible = try c.decodeIfPresent(Bool.self, forKey: .sidebarVisible) ?? true+ focusedSpaceID = try c.decodeIfPresent(UUID.self, forKey: .focusedSpaceID)+ expandedFolders = try c.decodeIfPresent(Set<UUID>.self, forKey: .expandedFolders) ?? []+ collapsedPinnedSpaces = try c.decodeIfPresent(Set<UUID>.self, forKey: .collapsedPinnedSpaces) ?? []+ selectedTabPerSpace = try c.decodeIfPresent([UUID: UUID].self, forKey: .selectedTabPerSpace) ?? [:]+ windowFrame = try c.decodeIfPresent(String.self, forKey: .windowFrame)+ }+}++extension TabData {+ init(from decoder: Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ url = try c.decodeIfPresent(String.self, forKey: .url) ?? ""+ savedURL = try c.decodeIfPresent(String.self, forKey: .savedURL) ?? url+ savedTitle = try c.decodeIfPresent(String.self, forKey: .savedTitle) ?? ""+ muted = try c.decodeIfPresent(Bool.self, forKey: .muted) ?? false+ timeLastActiveAt = try c.decodeIfPresent(Date.self, forKey: .timeLastActiveAt)+ activeTabBeforeCreationID = try c.decodeIfPresent(UUID.self, forKey: .activeTabBeforeCreationID)+ faviconKey = try c.decodeIfPresent(String.self, forKey: .faviconKey) ?? URL(string: url)?.host+ }+}diff --git a/Sources/Cra/Services/Account/AccountStore.swift b/Sources/Cra/Services/Account/AccountStore.swiftnew file mode 100644index 0000000..de462ff--- /dev/null+++ b/Sources/Cra/Services/Account/AccountStore.swift@@ -0,0 +1,234 @@+import AppKit+import Foundation+import Observation+import Security++struct AccountUser: Codable, Equatable {+ var userId: String+ var email: String+ var name: String?+ var firstName: String?+ var lastName: String?+ var profileImageUrl: String?+ var isAdmin: Bool+ var emailVerified: Bool+ var authProvider: String++ init?(json: Any?) {+ guard let d = json as? [String: Any], let id = d["userId"] as? String, let email = d["email"] as? String else { return nil }+ userId = id+ self.email = email+ name = d["name"] as? String+ firstName = d["firstName"] as? String+ lastName = d["lastName"] as? String+ profileImageUrl = d["profileImageUrl"] as? String+ isAdmin = d["isAdmin"] as? Bool ?? false+ emailVerified = d["emailVerified"] as? Bool ?? false+ authProvider = d["authProvider"] as? String ?? "email"+ }+}++/// Sign-in state, session token in the Keychain, settings sync and sidebar+/// backups. Mirrors GhostWriter's useAuth: validate the stored session on+/// launch, keep local state in sync with the server.+@MainActor+@Observable+final class AccountStore {+ private(set) var user: AccountUser?+ private(set) var isBusy = false+ var lastError: String?+ private(set) var googleConfigured = false+ private(set) var backups: [(device: String, tabCount: Int, updatedAt: Date)] = []+ private(set) var lastBackupAt: Date?++ @ObservationIgnored private let client = ConvexClient()+ @ObservationIgnored private var token: String? {+ didSet { if let t = token { Keychain.set(t) } else { Keychain.delete() } }+ }+ @ObservationIgnored private let userFile = JSONStore<AccountUser?>("account.json")+ @ObservationIgnored private var settingsPushTask: Task<Void, Never>?++ static let deviceID: String = {+ let key = "cra.deviceID"+ if let v = UserDefaults.standard.string(forKey: key) { return v }+ let v = (Host.current().localizedName ?? "Mac") + "-" + String(UUID().uuidString.prefix(6))+ UserDefaults.standard.set(v, forKey: key)+ return v+ }()++ var isSignedIn: Bool { user != nil }++ init() {+ token = Keychain.get()+ if token != nil { user = userFile.load(or: { nil }) }+ }++ // MARK: Session++ func restore() async {+ guard let token else { return }+ do {+ let v = try await client.mutation("auth:touch", ["token": token])+ if let u = AccountUser(json: v) {+ user = u+ userFile.save(u)+ } else {+ // Session gone on the server.+ await clearLocal()+ }+ } catch {+ // Keep the cached user; transient failures should not log out (GhostWriter grace period).+ }+ await refreshGoogleConfig()+ }++ func refreshGoogleConfig() async {+ if let cfg = try? await client.query("auth:googleConfig") as? [String: Any] {+ googleConfigured = cfg["configured"] as? Bool ?? false+ }+ }++ func signIn(email: String, password: String) async {+ await run {+ let v = try await self.client.mutation("auth:login", ["email": email, "password": password, "device": Self.deviceID])+ try self.adopt(v)+ }+ }++ func signUp(email: String, password: String, name: String) async {+ await run {+ let v = try await self.client.mutation("auth:signUp", ["email": email, "password": password, "name": name, "device": Self.deviceID])+ try self.adopt(v)+ }+ }++ func signOut() async {+ if let token { _ = try? await client.mutation("auth:logout", ["token": token]) }+ await clearLocal()+ }++ private func clearLocal() async {+ token = nil+ user = nil+ backups = []+ try? FileManager.default.removeItem(at: AppPaths.file("account.json"))+ }++ private func adopt(_ value: Any?) throws {+ guard let d = value as? [String: Any], let t = d["token"] as? String, let u = AccountUser(json: d["user"]) else {+ throw ConvexError(message: "Unexpected sign-in response.")+ }+ token = t+ user = u+ userFile.save(u)+ }++ private func run(_ body: @escaping () async throws -> Void) async {+ isBusy = true+ lastError = nil+ do { try await body() } catch { lastError = error.localizedDescription }+ isBusy = false+ }++ // MARK: Google++ /// Builds the Google consent URL. The Convex /google-callback route finishes+ /// the flow and deep-links back with cra://auth-callback?data=…+ func googleSignInURL() async -> URL? {+ guard let cfg = try? await client.query("auth:googleConfig") as? [String: Any], let clientId = cfg["clientId"] as? String else { return nil }+ let redirect = ConvexConfig.siteURL.appendingPathComponent("google-callback").absoluteString+ var comps = URLComponents(string: "https://accounts.google.com/o/oauth2/v2/auth")!+ comps.queryItems = [+ .init(name: "client_id", value: clientId),+ .init(name: "redirect_uri", value: redirect),+ .init(name: "response_type", value: "code"),+ .init(name: "scope", value: "openid email profile"),+ .init(name: "access_type", value: "offline"),+ .init(name: "prompt", value: "select_account"),+ .init(name: "state", value: Self.deviceID),+ ]+ return comps.url+ }++ /// cra://auth-callback?data=<base64 json {token,user}>+ func handleAuthCallback(_ url: URL) -> Bool {+ guard url.host == "auth-callback",+ let data = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.first(where: { $0.name == "data" })?.value,+ let raw = Data(base64Encoded: data.removingPercentEncoding ?? data),+ let json = try? JSONSerialization.jsonObject(with: raw) else { return false }+ do { try adopt(json); return true } catch { lastError = error.localizedDescription; return false }+ }++ // MARK: Sync++ func pushSettings(_ settings: AppSettings) {+ guard let token, let data = try? JSONEncoder().encode(settings),+ let obj = try? JSONSerialization.jsonObject(with: data) else { return }+ settingsPushTask?.cancel()+ settingsPushTask = Task { [client] in+ try? await Task.sleep(nanoseconds: 1_500_000_000)+ guard !Task.isCancelled else { return }+ _ = try? await client.mutation("settings:set", ["token": token, "settings": obj])+ }+ }++ func pullSettings() async -> AppSettings? {+ guard let token, let v = try? await client.query("settings:get", ["token": token]) as? [String: Any],+ let s = v["settings"], let data = try? JSONSerialization.data(withJSONObject: s) else { return nil }+ return try? JSONDecoder().decode(AppSettings.self, from: data)+ }++ func backupSidebar(_ document: SidebarDocument, tabCount: Int) async {+ guard let token else { return }+ let enc = JSONEncoder()+ enc.dateEncodingStrategy = .iso8601+ guard let data = try? enc.encode(document), let obj = try? JSONSerialization.jsonObject(with: data) else { return }+ if (try? await client.mutation("settings:backupSidebar", ["token": token, "device": Self.deviceID, "document": obj, "tabCount": tabCount])) != nil {+ lastBackupAt = Date()+ }+ await refreshBackups()+ }++ func refreshBackups() async {+ guard let token, let rows = try? await client.query("settings:listBackups", ["token": token]) as? [[String: Any]] else { return }+ backups = rows.compactMap { r in+ guard let d = r["device"] as? String else { return nil }+ return (d, r["tabCount"] as? Int ?? 0, Date(timeIntervalSince1970: (r["updatedAt"] as? Double ?? 0) / 1000))+ }+ }++ func fetchBackup(device: String) async -> SidebarDocument? {+ guard let token, let v = try? await client.query("settings:getBackup", ["token": token, "device": device]) as? [String: Any],+ let doc = v["document"], let data = try? JSONSerialization.data(withJSONObject: doc) else { return nil }+ let dec = JSONDecoder()+ dec.dateDecodingStrategy = .iso8601+ return try? dec.decode(SidebarDocument.self, from: data)+ }+}++/// Session token storage.+enum Keychain {+ private static let service = "dk.kildahl.cra"+ private static let account = "session"++ static func get() -> String? {+ let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service,+ kSecAttrAccount as String: account, kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitOne]+ var out: AnyObject?+ guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let d = out as? Data else { return nil }+ return String(data: d, encoding: .utf8)+ }++ static func set(_ value: String) {+ delete()+ let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service,+ kSecAttrAccount as String: account, kSecValueData as String: Data(value.utf8),+ kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock]+ SecItemAdd(q as CFDictionary, nil)+ }++ static func delete() {+ let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account]+ SecItemDelete(q as CFDictionary)+ }+}diff --git a/Sources/Cra/Services/Account/ConvexClient.swift b/Sources/Cra/Services/Account/ConvexClient.swiftnew file mode 100644index 0000000..a57b12d--- /dev/null+++ b/Sources/Cra/Services/Account/ConvexClient.swift@@ -0,0 +1,56 @@+import Foundation++/// Which Convex deployment Cra talks to. Prod by default; set CRA_CONVEX_URL /+/// CRA_CONVEX_SITE_URL to point at dev (helpful-stoat-265).+enum ConvexConfig {+ static let prodURL = URL(string: "https://artful-albatross-857.eu-west-1.convex.cloud")!+ static let prodSiteURL = URL(string: "https://artful-albatross-857.eu-west-1.convex.site")!+ static let devURL = URL(string: "https://helpful-stoat-265.eu-west-1.convex.cloud")!+ static let devSiteURL = URL(string: "https://helpful-stoat-265.eu-west-1.convex.site")!++ static var url: URL {+ if let s = ProcessInfo.processInfo.environment["CRA_CONVEX_URL"], let u = URL(string: s) { return u }+ return ProcessInfo.processInfo.environment["CRA_CONVEX_DEV"] == "1" ? devURL : prodURL+ }+ static var siteURL: URL {+ if let s = ProcessInfo.processInfo.environment["CRA_CONVEX_SITE_URL"], let u = URL(string: s) { return u }+ return ProcessInfo.processInfo.environment["CRA_CONVEX_DEV"] == "1" ? devSiteURL : prodSiteURL+ }+}++struct ConvexError: LocalizedError {+ let message: String+ var errorDescription: String? { message }+}++/// Minimal Convex HTTP client: /api/query, /api/mutation, /api/action.+struct ConvexClient {+ var baseURL: URL = ConvexConfig.url+ private let session = URLSession(configuration: .ephemeral)++ func query(_ path: String, _ args: [String: Any] = [:]) async throws -> Any? { try await call("query", path, args) }+ func mutation(_ path: String, _ args: [String: Any] = [:]) async throws -> Any? { try await call("mutation", path, args) }+ func action(_ path: String, _ args: [String: Any] = [:]) async throws -> Any? { try await call("action", path, args) }++ private func call(_ kind: String, _ path: String, _ args: [String: Any]) async throws -> Any? {+ var req = URLRequest(url: baseURL.appendingPathComponent("api/\(kind)"))+ req.httpMethod = "POST"+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")+ req.setValue("cra-macos-0.1", forHTTPHeaderField: "Convex-Client")+ req.httpBody = try JSONSerialization.data(withJSONObject: ["path": path, "args": args, "format": "json"])+ req.timeoutInterval = 20+ let (data, response) = try await session.data(for: req)+ guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {+ throw ConvexError(message: "Unexpected response from the server.")+ }+ if json["status"] as? String == "success" {+ let v = json["value"]+ return v is NSNull ? nil : v+ }+ let raw = json["errorMessage"] as? String ?? "Request failed"+ // Convex wraps thrown errors: "[CONVEX M(auth:login)] [Request ID: …] Server Error\nUncaught Error: Invalid email…"+ let cleaned = raw.components(separatedBy: "Uncaught Error: ").last?.components(separatedBy: "\n").first ?? raw+ _ = response+ throw ConvexError(message: cleaned.trimmingCharacters(in: .whitespacesAndNewlines))+ }+}diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swiftnew file mode 100644index 0000000..23e485d--- /dev/null+++ b/Sources/Cra/Services/BrowserManager.swift@@ -0,0 +1,270 @@+import AppKit+import CraCEF++/// One live Chromium browser for a tab. Tabs that have not been opened since+/// launch have no runtime; archiving a tab destroys its runtime.+@MainActor+final class TabRuntime {+ let tabID: UUID+ let browser: CraBrowser+ var progress: Double = 0+ var themeColor: String = ""+ init(tabID: UUID, browser: CraBrowser) {+ self.tabID = tabID+ self.browser = browser+ }+}++@MainActor+protocol BrowserManagerDelegate: AnyObject {+ func browserManagerDidUpdate(_ tabID: UUID)+ func browserManager(statusMessage: String)+ func browserManager(download: CraDownloadInfo)+ func browserManager(fullscreen: Bool, tabID: UUID)+ func browserManagerDevToolsHost(for tabID: UUID) -> NSView?+ /// A DevTools pane appeared or closed; the shell decides whether to show the dock.+ func browserManagerDevToolsChanged()+ func browserManagerHandleKey(_ event: NSEvent) -> Bool+ func browserManagerHandleUnhandledKey(_ event: NSEvent) -> Bool+ func browserManagerFocusedBrowser(_ tabID: UUID)+ func browserManagerOpenInternalURL(_ url: String)+}++/// Creates, shows, hides and tears down CEF browsers inside a container view.+@MainActor+final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {+ let store: SidebarStore+ let favicons: FaviconCache+ let container: NSView+ weak var delegate: BrowserManagerDelegate?+ private(set) var runtimes: [UUID: TabRuntime] = [:]+ private(set) var visibleTabID: UUID?+ private var byBrowser: [ObjectIdentifier: UUID] = [:]++ init(store: SidebarStore, favicons: FaviconCache, container: NSView) {+ self.store = store+ self.favicons = favicons+ self.container = container+ }++ func runtime(for tabID: UUID) -> TabRuntime? { runtimes[tabID] }+ var visibleRuntime: TabRuntime? { visibleTabID.flatMap { runtimes[$0] } }++ @discardableResult+ func ensureRuntime(for tabID: UUID) -> TabRuntime? {+ if let r = runtimes[tabID] { return r }+ guard let item = store.item(tabID), let tab = item.tab else { return nil }+ let browser = CraBrowser(frame: container.bounds, url: tab.url.isEmpty ? "about:blank" : tab.url, delegate: self)+ return register(browser: browser, tabID: tabID)+ }++ /// Popup host: a browser shell CEF will fill with window.open content.+ func makePopupHost(for tabID: UUID) -> CraBrowser {+ let browser = CraBrowser(frame: container.bounds, url: nil, delegate: self)+ register(browser: browser, tabID: tabID)+ return browser+ }++ @discardableResult+ private func register(browser: CraBrowser, tabID: UUID) -> TabRuntime {+ browser.userInfo = tabID.uuidString+ let v = browser.containerView+ v.frame = container.bounds+ v.autoresizingMask = [.width, .height]+ v.isHidden = true+ container.addSubview(v)+ let rt = TabRuntime(tabID: tabID, browser: browser)+ runtimes[tabID] = rt+ byBrowser[ObjectIdentifier(browser)] = tabID+ if let t = store.item(tabID)?.tab, t.muted { browser.setAudioMuted(true) }+ return rt+ }++ func show(_ tabID: UUID?, focus: Bool) {+ if let tabID, let rt = ensureRuntime(for: tabID) {+ for (id, other) in runtimes where id != tabID { other.browser.containerView.isHidden = true }+ rt.browser.containerView.frame = container.bounds+ rt.browser.containerView.isHidden = false+ visibleTabID = tabID+ if focus { rt.browser.setFocused(true) }+ } else {+ for (_, other) in runtimes { other.browser.containerView.isHidden = true }+ visibleTabID = nil+ }+ syncDevToolsVisibility()+ }++ func unload(_ tabID: UUID) {+ guard let rt = runtimes[tabID] else { return }+ if visibleTabID == tabID { visibleTabID = nil }+ rt.browser.containerView.isHidden = true+ rt.browser.close()+ }++ /// Drop runtimes whose tabs no longer exist (archived, deleted).+ func pruneMissingTabs() {+ for id in runtimes.keys where store.item(id)?.isTab != true { unload(id) }+ }++ func closeAll() { for id in Array(runtimes.keys) { unload(id) } }++ func layoutVisible() {+ visibleRuntime?.browser.containerView.frame = container.bounds+ }++ private func tabID(of browser: CraBrowser) -> UUID? { byBrowser[ObjectIdentifier(browser)] }++ // MARK: CraBrowserDelegate++ func browser(_ browser: CraBrowser, didChangeTitle title: String) {+ guard let id = tabID(of: browser) else { return }+ store.updateTab(id, title: title)+ delegate?.browserManagerDidUpdate(id)+ }++ func browser(_ browser: CraBrowser, didChangeURL url: String) {+ guard let id = tabID(of: browser) else { return }+ // Our own error page is a data: URL; keep the real address in the model.+ if url.hasPrefix("data:text/html;base64,") { return }+ store.updateTab(id, url: url)+ delegate?.browserManagerDidUpdate(id)+ }++ func browser(_ browser: CraBrowser, didChangeLoading loading: Bool, canGoBack: Bool, canGoForward: Bool) {+ guard let id = tabID(of: browser) else { return }+ if !loading { runtimes[id]?.progress = 0 }+ delegate?.browserManagerDidUpdate(id)+ }++ func browser(_ browser: CraBrowser, didChangeProgress progress: Double) {+ guard let id = tabID(of: browser) else { return }+ runtimes[id]?.progress = progress+ delegate?.browserManagerDidUpdate(id)+ }++ func browser(_ browser: CraBrowser, didFinishLoadingURL url: String, title: String, statusCode: Int) {+ guard let id = tabID(of: browser) else { return }+ store.recordVisit(url: url, title: title.isEmpty ? (store.item(id)?.tab?.savedTitle ?? "") : title)+ }++ func browser(_ browser: CraBrowser, didLoadFavicon image: NSImage, forURL iconURL: String) {+ guard let id = tabID(of: browser), let tab = store.item(id)?.tab else { return }+ let key = FaviconCache.key(for: tab.url) ?? tab.faviconKey+ guard let key else { return }+ favicons.store(image, forKey: key)+ if tab.faviconKey != key { store.updateTab(id, url: tab.url) }+ }++ func browser(_ browser: CraBrowser, didReportThemeColor hex: String) {+ guard let id = tabID(of: browser) else { return }+ runtimes[id]?.themeColor = hex+ delegate?.browserManagerDidUpdate(id)+ }++ func browser(_ browser: CraBrowser, didChangeStatusMessage message: String) {+ delegate?.browserManager(statusMessage: message)+ }++ func browser(_ browser: CraBrowser, didChangeFullscreen fullscreen: Bool) {+ guard let id = tabID(of: browser) else { return }+ delegate?.browserManager(fullscreen: fullscreen, tabID: id)+ }++ func browser(_ browser: CraBrowser, requestsNewTabWithURL url: String, inBackground background: Bool) {+ if url.hasPrefix("cra://") { delegate?.browserManagerOpenInternalURL(url); return }+ let sourceSpace = tabID(of: browser).flatMap { store.spaceID(ofItem: $0) }+ let parentIndex = tabID(of: browser).flatMap { id -> Int? in+ guard let it = store.item(id), let p = it.parentID, store.rootContainer(of: id) != nil,+ case .today = store.rootContainer(of: id)! else { return nil }+ return (store.item(p)?.children.firstIndex(of: id) ?? -1) + 1+ }+ // Links from a today tab open right below it (Arc); otherwise at the top.+ let tab = store.createTab(url: url, in: sourceSpace, select: !background,+ parent: parentIndex != nil ? store.item(tabID(of: browser)!)?.parentID : nil,+ index: parentIndex)+ if background {+ store.markUnread(tab.id, true)+ ensureRuntime(for: tab.id) // load it so the title and favicon fill in+ }+ }++ func browser(_ browser: CraBrowser, popupHostForURL url: String, inBackground background: Bool) -> CraBrowser? {+ if url.hasPrefix("cra://") { delegate?.browserManagerOpenInternalURL(url); return nil }+ let sourceSpace = tabID(of: browser).flatMap { store.spaceID(ofItem: $0) }+ let tab = store.createTab(url: url, in: sourceSpace, select: !background)+ if background { store.markUnread(tab.id, true) }+ let host = makePopupHost(for: tab.id)+ if !background { show(tab.id, focus: true) }+ return host+ }++ func devToolsHostView(for browser: CraBrowser) -> NSView? {+ guard let id = tabID(of: browser) else { return nil }+ return delegate?.browserManagerDevToolsHost(for: id)+ }++ private(set) var devToolsViews: [UUID: NSView] = [:]+ var visibleTabHasDevTools: Bool { visibleTabID.flatMap { devToolsViews[$0] } != nil }++ func browser(_ browser: CraBrowser, didCreateDevToolsView view: NSView) {+ guard let id = tabID(of: browser) else { return }+ devToolsViews[id] = view+ delegate?.browserManagerDevToolsChanged()+ }++ func browserDidCloseDevTools(_ browser: CraBrowser) {+ guard let id = tabID(of: browser) else { return }+ devToolsViews[id] = nil+ delegate?.browserManagerDevToolsChanged()+ }++ /// CEF's window for the visible tab's DevTools, if any.+ var visibleDevToolsWindow: NSWindow? { visibleTabID.flatMap { devToolsViews[$0]?.window } }++ private func syncDevToolsVisibility() {+ delegate?.browserManagerDevToolsChanged()+ }++ func browser(_ browser: CraBrowser, handleKeyEvent event: NSEvent) -> Bool {+ delegate?.browserManagerHandleKey(event) ?? false+ }++ func browser(_ browser: CraBrowser, handleUnhandledKeyEvent event: NSEvent) -> Bool {+ delegate?.browserManagerHandleUnhandledKey(event) ?? false+ }++ func browser(_ browser: CraBrowser, didUpdateDownload download: CraDownloadInfo) {+ delegate?.browserManager(download: download)+ }++ func browser(_ browser: CraBrowser, requestsPermissionForOrigin origin: String, kinds: UInt, completion: @escaping (Bool) -> Void) {+ // Notification prompts are denied quietly (no modal), like Arc's default.+ if kinds == 8 { completion(false); return }+ var what: [String] = []+ if kinds & 1 != 0 { what.append("camera") }+ if kinds & 2 != 0 { what.append("microphone") }+ if kinds & 4 != 0 { what.append("location") }+ if kinds & 8 != 0 { what.append("notifications") }+ if what.isEmpty { what.append("a browser permission") }+ let alert = NSAlert()+ alert.messageText = "\(origin) wants to use your \(what.joined(separator: " and "))"+ alert.addButton(withTitle: "Allow")+ alert.addButton(withTitle: "Block")+ guard let window = container.window else { completion(false); return }+ alert.beginSheetModal(for: window) { resp in completion(resp == .alertFirstButtonReturn) }+ }++ func browserDidReceiveFocus(_ browser: CraBrowser) {+ guard let id = tabID(of: browser) else { return }+ delegate?.browserManagerFocusedBrowser(id)+ }++ func browserDidClose(_ browser: CraBrowser) {+ guard let id = tabID(of: browser) else { return }+ browser.containerView.removeFromSuperview()+ byBrowser[ObjectIdentifier(browser)] = nil+ if runtimes[id]?.browser === browser { runtimes[id] = nil }+ if visibleTabID == id { visibleTabID = nil }+ delegate?.browserManagerDidUpdate(id)+ }+}diff --git a/Sources/Cra/Services/FaviconCache.swift b/Sources/Cra/Services/FaviconCache.swiftnew file mode 100644index 0000000..9c93f01--- /dev/null+++ b/Sources/Cra/Services/FaviconCache.swift@@ -0,0 +1,81 @@+import AppKit+import Observation++/// Favicons keyed by host. Chromium hands us PNG bytes through the bridge;+/// we keep them in memory and on disk so the sidebar is populated on launch+/// before any tab has loaded (Arc: SidebarItemsFaviconCache).+@MainActor+@Observable+final class FaviconCache {+ private(set) var images: [String: NSImage] = [:]+ private var attemptedDiskLoad: Set<String> = []++ static func key(for urlString: String) -> String? {+ guard let host = URL(string: urlString)?.host, !host.isEmpty else { return nil }+ return host.lowercased()+ }++ func image(forKey key: String?) -> NSImage? {+ guard let key else { return nil }+ if let img = images[key] { return img }+ if !attemptedDiskLoad.contains(key) {+ attemptedDiskLoad.insert(key)+ let file = AppPaths.favicons.appendingPathComponent(Self.fileName(key))+ if let img = NSImage(contentsOf: file) {+ images[key] = img+ return img+ }+ }+ return nil+ }++ func image(for urlString: String) -> NSImage? { image(forKey: Self.key(for: urlString)) }++ private var dominant: [String: String] = [:]++ /// Average colour of the favicon's opaque pixels as "#RRGGBB" (Arc tints+ /// the toolbar with the favicon's dominant colour when a page has no+ /// theme-color).+ func dominantColor(forKey key: String?) -> String? {+ guard let key else { return nil }+ if let c = dominant[key] { return c.isEmpty ? nil : c }+ guard let img = image(forKey: key), let cg = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else { return nil }+ let w = 16, h = 16+ var buf = [UInt8](repeating: 0, count: w * h * 4)+ guard let ctx = CGContext(data: &buf, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4,+ space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }+ ctx.interpolationQuality = .medium+ ctx.draw(cg, in: CGRect(x: 0, y: 0, width: w, height: h))+ var r = 0, g = 0, b = 0, n = 0+ for i in stride(from: 0, to: buf.count, by: 4) where buf[i + 3] > 200 {+ r += Int(buf[i]); g += Int(buf[i + 1]); b += Int(buf[i + 2]); n += 1+ }+ guard n > 40 else { dominant[key] = ""; return nil }+ let hex = String(format: "#%02X%02X%02X", r / n, g / n, b / n)+ dominant[key] = hex+ return hex+ }++ /// Forget in-memory state so files added on disk (imports) are picked up.+ func reset() {+ images = [:]+ attemptedDiskLoad = []+ dominant = [:]+ }++ func store(_ image: NSImage, forKey key: String) {+ images[key] = image+ let file = AppPaths.favicons.appendingPathComponent(Self.fileName(key))+ DispatchQueue.global(qos: .utility).async {+ guard let tiff = image.tiffRepresentation,+ let rep = NSBitmapImageRep(data: tiff),+ let png = rep.representation(using: .png, properties: [:]) else { return }+ try? png.write(to: file, options: .atomic)+ }+ }++ static func fileName(_ key: String) -> String {+ let safe = key.map { $0.isLetter || $0.isNumber || $0 == "." || $0 == "-" ? String($0) : "_" }.joined()+ return safe + ".png"+ }+}diff --git a/Sources/Cra/Services/Import/Importers.swift b/Sources/Cra/Services/Import/Importers.swiftnew file mode 100644index 0000000..ed87fda--- /dev/null+++ b/Sources/Cra/Services/Import/Importers.swift@@ -0,0 +1,454 @@+import AppKit+import CryptoKit+import Foundation++// Importers read Arc's and Dia's on-disk stores (see docs/arc-reverse-engineering.md)+// into a neutral ImportPlan that the store applies.++struct ImportedItem {+ var customTitle: String?+ var pageTitle: String = ""+ var url: String?+ var isFolder = false+ var children: [ImportedItem] = []+ var createdAt = Date()+ /// Cached favicon file in the source browser, if any.+ var faviconPath: String?+}++struct ImportedSpace {+ var title: String+ var emoji: String+ var theme: SpaceTheme?+ var pinned: [ImportedItem] = []+ var today: [ImportedItem] = []+}++struct ImportedArchiveEntry {+ var customTitle: String?+ var pageTitle: String+ var url: String+ var archivedAt: Date+ var reason: ArchiveReason+ var spaceTitle: String?+}++struct ImportedSettings {+ var autoArchive: AutoArchiveThreshold?+ var sidebarWidth: Double?+}++struct ImportPlan {+ var source: String+ var spaces: [ImportedSpace] = []+ 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) }+ }+ 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) }+ }+}++enum ImportError: LocalizedError {+ case notFound(String)+ case unreadable(String)+ var errorDescription: String? {+ switch self {+ case .notFound(let s): return "\(s) data was not found on this Mac."+ case .unreadable(let s): return "Could not read \(s)."+ }+ }+}++private func refDate(_ v: Any?) -> Date {+ if let d = v as? Double { return Date(timeIntervalSinceReferenceDate: d) }+ return Date()+}++/// Arc stores `[id, object, id, object…]` for ordered dictionaries.+private func pairs(_ list: Any?) -> [(String, [String: Any])] {+ guard let arr = list as? [Any] else { return [] }+ var out: [(String, [String: Any])] = []+ var i = 0+ while i + 1 < arr.count {+ if let id = arr[i] as? String, let obj = arr[i + 1] as? [String: Any] { out.append((id, obj)); i += 2 }+ else { i += 1 }+ }+ return out+}++// MARK: - Arc++enum ArcImporter {+ static let supportDir = FileManager.default.homeDirectoryForCurrentUser+ .appendingPathComponent("Library/Application Support/Arc", isDirectory: true)++ static var isAvailable: Bool { FileManager.default.fileExists(atPath: supportDir.appendingPathComponent("StorableSidebar.json").path) }++ static func plan() throws -> ImportPlan {+ let url = supportDir.appendingPathComponent("StorableSidebar.json")+ guard let data = try? Data(contentsOf: url) else { throw ImportError.notFound("Arc") }+ guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let sidebar = root["sidebar"] as? [String: Any],+ let containers = sidebar["containers"] as? [[String: Any]] else { throw ImportError.unreadable("Arc's sidebar") }+ var plan = ImportPlan(source: "Arc")+ guard let main = containers.first(where: { $0["spaces"] != nil }) else { return plan }+ let items = Dictionary(uniqueKeysWithValues: pairs(main["items"]).map { ($0.0, $0.1) })+ var spaceTitleByID: [String: String] = [:]++ func convert(_ id: String) -> ImportedItem? {+ guard let it = items[id], let dataDict = it["data"] as? [String: Any] else { return nil }+ let custom = it["title"] as? String+ let created = refDate(it["createdAt"])+ let childIDs = it["childrenIds"] as? [String] ?? []+ if let tab = dataDict["tab"] as? [String: Any] {+ guard let u = tab["savedURL"] as? String, !u.isEmpty else { return nil }+ return ImportedItem(customTitle: custom, pageTitle: tab["savedTitle"] as? String ?? "", url: u, createdAt: created,+ faviconPath: faviconFile(forItemID: id))+ }+ if dataDict["list"] != nil {+ return ImportedItem(customTitle: custom, pageTitle: custom ?? "Folder", url: nil, isFolder: true,+ children: childIDs.compactMap(convert), createdAt: created)+ }+ if dataDict["splitView"] != nil || dataDict["tabGroup"] != nil {+ // Flatten split views into their tabs.+ let kids = childIDs.compactMap(convert)+ return kids.count == 1 ? kids[0] : ImportedItem(customTitle: custom ?? "Split", pageTitle: "", url: nil, isFolder: true, children: kids, createdAt: created)+ }+ return nil+ }++ // Favorites (topApps) container(s).+ 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) } }+ }++ for (sid, space) in pairs(main["spaces"]) {+ let title = space["title"] as? String ?? "Space"+ spaceTitleByID[sid] = title+ var emoji = "🗂️"+ if let info = space["customInfo"] as? [String: Any], let icon = info["iconType"] as? [String: Any] {+ if let e = icon["emoji_v2"] as? String { emoji = e }+ else if let code = icon["emoji"] as? Int, let scalar = UnicodeScalar(code) { emoji = String(Character(scalar)) }+ }+ var pinnedID: String?, todayID: String?+ if let ids = space["containerIDs"] as? [Any] {+ var i = 0+ while i + 1 < ids.count {+ if let k = ids[i] as? String, let v = ids[i + 1] as? String {+ if k == "pinned" { pinnedID = v } else if k == "unpinned" { todayID = v }+ }+ i += 2+ }+ }+ var sp = ImportedSpace(title: title, emoji: emoji, theme: theme(from: space))+ 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)+ }++ // Archive+ if let adata = try? Data(contentsOf: supportDir.appendingPathComponent("StorableArchiveItems.json")),+ let aroot = try? JSONSerialization.jsonObject(with: adata) as? [String: Any],+ let aitems = aroot["items"] as? [Any] {+ for case let e as [String: Any] in aitems {+ guard let si = e["sidebarItem"] as? [String: Any], let d = si["data"] as? [String: Any],+ let tab = d["tab"] as? [String: Any], let u = tab["savedURL"] as? String, !u.isEmpty else { continue }+ let reason = (e["reason"] as? String) == "auto" ? ArchiveReason.auto : .manual+ var spaceTitle: String?+ if let src = e["source"] as? [String: Any], let sp = src["space"] as? [String: Any], let id = sp["_0"] as? String { spaceTitle = spaceTitleByID[id] }+ plan.archive.append(ImportedArchiveEntry(customTitle: si["title"] as? String, pageTitle: tab["savedTitle"] as? String ?? "",+ url: u, archivedAt: refDate(e["archivedAt"]), reason: reason, spaceTitle: spaceTitle))+ }+ plan.archive.sort { $0.archivedAt > $1.archivedAt }+ if plan.archive.count > 1500 { plan.archive.removeLast(plan.archive.count - 1500) }+ }++ // Settings+ if let wdata = try? Data(contentsOf: supportDir.appendingPathComponent("StorableWindows.json")),+ let wroot = try? JSONSerialization.jsonObject(with: wdata) as? [String: Any],+ let prefs = wroot["sidebarViewPreferences"] as? [String: Any], let w = prefs["sidebarWidth"] as? Double {+ plan.settings.sidebarWidth = w+ }+ if let threshold = UserDefaults(suiteName: "company.thebrowser.Browser")?.string(forKey: "autoArchiveTimeThreshold") {+ plan.settings.autoArchive = AutoArchiveThreshold(rawValue: threshold)+ }+ return plan+ }++ /// Arc caches sidebar favicons as 32x32 PNGs named md5(item id).+ static func faviconFile(forItemID id: String) -> String? {+ let digest = Insecure.MD5.hash(data: Data(id.utf8)).map { String(format: "%02x", $0) }.joined()+ let path = supportDir.appendingPathComponent("SidebarItemsFaviconCache/\(digest)").path+ return FileManager.default.fileExists(atPath: path) ? path : nil+ }++ /// Arc's blendedGradient → SpaceTheme. Prefers the dark variant when one exists.+ private static func theme(from space: [String: Any]) -> SpaceTheme? {+ guard let info = space["customInfo"] as? [String: Any], let wt = info["windowTheme"] as? [String: Any],+ let bg = wt["background"] as? [String: Any] else { return nil }+ var variant: [String: Any]?+ var appearance = "auto"+ if let ab = bg["appearanceBased"] as? [String: Any] {+ variant = (ab["dark"] as? [String: Any]) ?? (ab["light"] as? [String: Any])+ appearance = ab["dark"] != nil ? "dark" : "light"+ } else if let single = bg["single"] as? [String: Any] {+ variant = single["_0"] as? [String: Any]+ }+ guard let v = variant else { return nil }+ if let a = v["contentOverBackgroundAppearance"] as? String { appearance = a }+ let vibrant = v["isVibrant"] as? Bool ?? false+ guard let style = v["style"] as? [String: Any], let color = style["color"] as? [String: Any],+ let c0 = color["_0"] as? [String: Any], let bg2 = c0["blendedGradient"] as? [String: Any],+ let g = bg2["_0"] as? [String: Any], let base = g["baseColors"] as? [[String: Any]], !base.isEmpty else { return nil }+ let overlays = g["overlayColors"] as? [[String: Any]] ?? []+ func comp(_ c: [String: Any], _ k: String) -> Double { max(0, min(1, c[k] as? Double ?? 0)) }+ // Arc blends an overlay gradient onto the base gradient and the wheel+ // mixes the two base colours; bake both into our two stops (fitted to+ // Arc's rendering: top stop leans toward the second base colour).+ func hex(_ i: Int) -> String {+ let b = base[min(i, base.count - 1)]+ let other = base[min(i == 0 ? 1 : 0, base.count - 1)]+ var r = comp(b, "red"), gg = comp(b, "green"), bl = comp(b, "blue")+ if i == 0 {+ r += (comp(other, "red") - r) * 0.1; gg += (comp(other, "green") - gg) * 0.1; bl += (comp(other, "blue") - bl) * 0.1+ }+ if i < overlays.count {+ let o = overlays[i]+ let a = comp(o, "alpha") * 0.85+ r += (comp(o, "red") - r) * a; gg += (comp(o, "green") - gg) * a; bl += (comp(o, "blue") - bl) * a+ }+ return String(format: "#%02X%02X%02X", Int((r * 255).rounded()), Int((gg * 255).rounded()), Int((bl * 255).rounded()))+ }+ var colors = [hex(0), hex(1)]+ let mods = g["modifiers"] as? [String: Any]+ var intensity = mods?["intensityFactor"] as? Double ?? 0.5+ if vibrant && appearance != "dark" {+ // Fitted to Arc over white and black backdrops: the top stop is the+ // first base colour nudged toward the second and 30% toward white;+ // the bottom stop is the base colour pulled 30% toward the overlay's+ // end colour (or the second base colour) and 20% toward white.+ // Opacity ramps 0.45 → 0.59 (see SpacePalette).+ func rgb(_ c: [String: Any]) -> (Double, Double, Double) { (comp(c, "red"), comp(c, "green"), comp(c, "blue")) }+ func mix(_ a: (Double, Double, Double), _ b: (Double, Double, Double), _ t: Double) -> (Double, Double, Double) {+ (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t, a.2 + (b.2 - a.2) * t)+ }+ func hexOf(_ c: (Double, Double, Double)) -> String {+ String(format: "#%02X%02X%02X", Int((c.0 * 255).rounded()), Int((c.1 * 255).rounded()), Int((c.2 * 255).rounded()))+ }+ let b0 = rgb(base[0]), b1 = rgb(base[min(1, base.count - 1)])+ let end = overlays.last(where: { comp($0, "alpha") > 0 }).map(rgb) ?? b1+ let white = (1.0, 1.0, 1.0)+ colors = [hexOf(mix(mix(b0, b1, 0.15), white, 0.30)), hexOf(mix(mix(b0, end, 0.30), white, 0.20))]+ }+ let accent = String(format: "#%02X%02X%02X", Int((comp(base[0], "red") * 255).rounded()),+ Int((comp(base[0], "green") * 255).rounded()), Int((comp(base[0], "blue") * 255).rounded()))+ if appearance == "dark" && !vibrant {+ // Measured from Arc: dark themes show ~27% of the colour over a+ // slightly purple dark grey (#2B2632).+ colors = colors.map { c in+ let k = HexColor.components(c) ?? (0, 0, 0)+ func ch(_ v: Double, _ base: Double) -> Int { Int((v * 255 * 0.27 + base).rounded()) }+ return String(format: "#%02X%02X%02X", ch(k.r, 43), ch(k.g, 38), ch(k.b, 50))+ }+ intensity = 1+ }+ return SpaceTheme(colors: colors, intensity: intensity,+ noise: mods?["noiseFactor"] as? Double ?? 0.15, appearance: appearance, vibrant: vibrant, accent: accent)+ }+}++// MARK: - Dia++enum DiaImporter {+ static let supportDir = FileManager.default.homeDirectoryForCurrentUser+ .appendingPathComponent("Library/Application Support/Dia", isDirectory: true)++ static var isAvailable: Bool { FileManager.default.fileExists(atPath: supportDir.appendingPathComponent("StorableProfileContainers.json").path) }++ static func plan() throws -> ImportPlan {+ guard isAvailable else { throw ImportError.notFound("Dia") }+ var plan = ImportPlan(source: "Dia")++ // Open tabs and the favorites container.+ if let data = try? Data(contentsOf: supportDir.appendingPathComponent("StorableProfileContainers.json")),+ let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let containers = root["containers"] as? [[String: Any]] {+ var openTabs: [ImportedItem] = []+ for c in containers {+ let idInfo = c["id"] as? [String: Any]+ let kind = idInfo?["container"] as? [String: Any]+ let isFavorites = kind?["favorites"] != nil+ for tab in c["tabs"] as? [[String: Any]] ?? [] {+ guard let contents = tab["contents"] as? [[String: Any]] else { continue }+ for content in contents {+ guard let variant = content["variant"] as? [String: Any], let web = variant["webContent"] as? [String: Any],+ let w = web["_0"] as? [String: Any], let url = w["url"] as? String else { continue }+ let item = ImportedItem(pageTitle: w["title"] as? String ?? "", url: url, createdAt: refDate(tab["creationDate"]))+ if isFavorites { plan.favorites.append(item) } else { openTabs.append(item) }+ }+ }+ }+ if !openTabs.isEmpty { plan.spaces.append(ImportedSpace(title: "Dia", emoji: "🌀", theme: nil, today: openTabs)) }+ }++ // Bookmarks: Dia keeps imported Arc spaces as folders on the bookmarks bar.+ let profiles = (try? FileManager.default.contentsOfDirectory(atPath: supportDir.appendingPathComponent("User Data").path)) ?? []+ for prof in profiles where prof == "Default" || prof.hasPrefix("Profile ") {+ let bm = supportDir.appendingPathComponent("User Data/\(prof)/Bookmarks")+ guard let data = try? Data(contentsOf: bm), let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let roots = root["roots"] as? [String: Any], let bar = roots["bookmark_bar"] as? [String: Any] else { continue }+ func convert(_ node: [String: Any]) -> ImportedItem? {+ let name = node["name"] as? String ?? ""+ if node["type"] as? String == "url", let u = node["url"] as? String {+ return ImportedItem(customTitle: name.isEmpty ? nil : name, pageTitle: name, url: u)+ }+ if node["type"] as? String == "folder" {+ let kids = (node["children"] as? [[String: Any]] ?? []).compactMap(convert)+ return ImportedItem(customTitle: name, pageTitle: name, url: nil, isFolder: true, children: kids)+ }+ return nil+ }+ for child in bar["children"] as? [[String: Any]] ?? [] {+ guard let item = convert(child) else { continue }+ if item.isFolder {+ if item.pageTitle.lowercased() == "favorites" { plan.favorites.append(contentsOf: item.children.filter { !$0.isFolder }) }+ else if !item.children.isEmpty {+ if let i = plan.spaces.firstIndex(where: { $0.title == item.pageTitle }) { plan.spaces[i].pinned.append(contentsOf: item.children) }+ else { plan.spaces.append(ImportedSpace(title: item.pageTitle, emoji: "📁", theme: nil, pinned: item.children)) }+ }+ } else {+ plan.favorites.append(item)+ }+ }+ if let other = roots["other"] as? [String: Any], let kids = (other["children"] as? [[String: Any]])?.compactMap(convert), !kids.isEmpty {+ plan.spaces.append(ImportedSpace(title: "Other Bookmarks", emoji: "🔖", theme: nil, pinned: kids))+ }+ }++ // Auto-archive store (best effort; shape varies between Dia versions).+ if let data = try? Data(contentsOf: supportDir.appendingPathComponent("StorableAutoArchive.json")),+ let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let containers = root["containers"] as? [[String: Any]] {+ for c in containers {+ for t in c["archivedTabs"] as? [[String: Any]] ?? [] {+ if let (url, title) = firstURL(in: t) {+ plan.archive.append(ImportedArchiveEntry(customTitle: nil, pageTitle: title, url: url,+ archivedAt: refDate(t["archivedAt"] ?? t["archiveDate"] ?? t["date"]), reason: .auto, spaceTitle: "Dia"))+ }+ }+ }+ }+ return plan+ }++ private static func firstURL(in obj: Any) -> (String, String)? {+ if let d = obj as? [String: Any] {+ if let u = d["url"] as? String, u.hasPrefix("http") { return (u, d["title"] as? String ?? "") }+ for v in d.values { if let r = firstURL(in: v) { return r } }+ } else if let a = obj as? [Any] {+ for v in a { if let r = firstURL(in: v) { return r } }+ }+ return nil+ }+}++// MARK: - Applying++extension SidebarStore {+ struct ImportResult { var spaces = 0; var tabs = 0; var folders = 0; var archived = 0 }++ /// Merge a plan into the sidebar. Spaces with the same title merge; favorites+ /// and pinned tabs skip URLs that already exist in that section.+ @discardableResult+ func apply(_ plan: ImportPlan, includeArchive: Bool, includeSettings: Bool) -> ImportResult {+ var result = ImportResult()++ // A pinned tab that has navigated still counts as present via its home URL.+ func existingURLs(under container: UUID) -> Set<String> {+ Set(tabs(under: container).flatMap { [$0.tab?.url, $0.tab?.savedURL].compactMap { $0 } })+ }++ // Favicons first, for every item (also ones skipped as duplicates).+ func copyFavicons(_ items: [ImportedItem]) {+ for it in items {+ if it.isFolder { copyFavicons(it.children); continue }+ guard let src = it.faviconPath, let url = it.url, let key = FaviconCache.key(for: url) else { continue }+ let dst = AppPaths.favicons.appendingPathComponent(FaviconCache.fileName(key))+ if !FileManager.default.fileExists(atPath: dst.path) {+ try? FileManager.default.copyItem(atPath: src, toPath: dst.path)+ }+ }+ }+ copyFavicons(plan.favorites)+ for sp in plan.spaces { copyFavicons(sp.pinned); copyFavicons(sp.today) }++ func insert(_ items: [ImportedItem], into parent: UUID, skip: Set<String>, pinned: Bool) {+ var skip = skip+ for it in items {+ if it.isFolder {+ let name = it.customTitle ?? it.pageTitle+ // Re-importing must not duplicate folders: reuse one with the same name.+ let folder: SidebarItem+ if let existing = children(of: parent).first(where: { $0.isFolder && ($0.title ?? "") == name }) {+ folder = existing+ } else {+ folder = createFolder(named: name, in: parent)+ setExpanded(folder.id, false)+ result.folders += 1+ }+ insert(it.children, into: folder.id, skip: existingURLs(under: folder.id), pinned: pinned)+ } else if let url = it.url, !skip.contains(url) {+ skip.insert(url)+ var tab = SidebarItem.tab(url, title: it.pageTitle, parent: parent)+ tab.title = it.customTitle+ tab.createdAt = it.createdAt+ if var t = tab.tab { t.timeLastActiveAt = it.createdAt; tab.data = .tab(t) }+ insertItem(tab, into: parent, at: nil)+ result.tabs += 1+ }+ }+ }++ insert(plan.favorites, into: favoritesContainerID, skip: existingURLs(under: favoritesContainerID), pinned: true)++ for sp in plan.spaces {+ let space: Space+ if var existing = orderedSpaces.first(where: { $0.title.caseInsensitiveCompare(sp.title) == .orderedSame }) {+ if let t = sp.theme, existing.theme != t { existing.theme = t; updateSpace(existing) }+ space = existing+ } else {+ space = createSpace(title: sp.title, emoji: sp.emoji, theme: sp.theme, focus: false)+ result.spaces += 1+ }+ 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)+ }++ if includeArchive {+ let known = Set(archive.compactMap { $0.item.tab?.url })+ for e in plan.archive where !known.contains(e.url) {+ var item = SidebarItem.tab(e.url, title: e.pageTitle, parent: nil)+ item.title = e.customTitle+ let sid = orderedSpaces.first { $0.title == e.spaceTitle }?.id+ appendArchived(ArchivedItem(archivedAt: e.archivedAt, reason: e.reason, sourceSpaceID: sid, wasPinned: false, item: item))+ result.archived += 1+ }+ }++ if includeSettings {+ if let a = plan.settings.autoArchive { settings.autoArchive = a }+ if let w = plan.settings.sidebarWidth { prefs.sidebarWidth = min(max(w, 220), 520) }+ }+ touchAfterImport()+ return result+ }+}diff --git a/Sources/Cra/Services/Persistence.swift b/Sources/Cra/Services/Persistence.swiftnew file mode 100644index 0000000..5175761--- /dev/null+++ b/Sources/Cra/Services/Persistence.swift@@ -0,0 +1,67 @@+import Foundation++enum AppPaths {+ static let supportDir: URL = {+ let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ .appendingPathComponent("Cra", isDirectory: true)+ try? FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)+ return base+ }()+ static var chromiumCache: URL { supportDir.appendingPathComponent("Chromium", isDirectory: true) }+ static var favicons: URL {+ let u = supportDir.appendingPathComponent("Favicons", isDirectory: true)+ try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true)+ return u+ }+ static var log: URL { supportDir.appendingPathComponent("chromium.log") }+ static func file(_ name: String) -> URL { supportDir.appendingPathComponent(name) }+}++/// One JSON file, loaded once, saved with a short debounce. Writes are atomic+/// and the previous version is kept as `<name>.bak`, which is what Arc does+/// with its timestamped Storable*.json copies, minus the pile-up.+final class JSONStore<T: Codable> {+ let url: URL+ private var pending: DispatchWorkItem?+ private let encoder: JSONEncoder = {+ let e = JSONEncoder()+ e.outputFormatting = [.prettyPrinted, .sortedKeys]+ e.dateEncodingStrategy = .iso8601+ return e+ }()+ private let decoder: JSONDecoder = {+ let d = JSONDecoder()+ d.dateDecodingStrategy = .iso8601+ return d+ }()++ init(_ name: String) { url = AppPaths.file(name) }++ func load(or fallback: () -> T) -> T {+ guard let data = try? Data(contentsOf: url) else { return fallback() }+ if let v = try? decoder.decode(T.self, from: data) { return v }+ // Corrupt file: keep it aside for forensics and start fresh.+ try? FileManager.default.moveItem(at: url, to: url.appendingPathExtension("corrupt"))+ return fallback()+ }++ func save(_ value: T, delay: TimeInterval = 0.4) {+ pending?.cancel()+ let item = DispatchWorkItem { [weak self] in self?.saveNow(value) }+ pending = item+ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: item)+ }++ func saveNow(_ value: T) {+ pending?.cancel()+ pending = nil+ guard let data = try? encoder.encode(value) else { return }+ let fm = FileManager.default+ let bak = url.appendingPathExtension("bak")+ if fm.fileExists(atPath: url.path) {+ try? fm.removeItem(at: bak)+ try? fm.copyItem(at: url, to: bak)+ }+ try? data.write(to: url, options: .atomic)+ }+}diff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swiftnew file mode 100644index 0000000..85e13eb--- /dev/null+++ b/Sources/Cra/Services/SidebarStore.swift@@ -0,0 +1,637 @@+import Foundation+import Observation++/// The single source of truth for spaces, tabs, folders, favorites, the+/// archive and window preferences. Mutations here are what Arc's+/// SidebarDataStore mutations do; persistence mirrors its Storable*.json files.+@MainActor+@Observable+final class SidebarStore {+ // MARK: State++ 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) } }+ private(set) var history: [String: HistoryEntry] = [:]+ private(set) var ranking = RankingData()+ /// Bumped on every structural change; cheap way for AppKit code to observe.+ private(set) var revision = 0++ // MARK: Persistence++ private let sidebarFile = JSONStore<SidebarDocument>("sidebar.json")+ private let archiveFile = JSONStore<[ArchivedItem]>("archive.json")+ private let prefsStore = JSONStore<WindowPrefs>("windows.json")+ private let settingsStore = JSONStore<AppSettings>("settings.json")+ private let historyFile = JSONStore<[HistoryEntry]>("history.json")+ private let rankingFile = JSONStore<RankingData>("commandbar.json")++ 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) }+ for it in doc.items { items[it.id] = it }+ archive = archiveFile.load(or: { [] })+ prefs = prefsStore.load(or: { WindowPrefs() })+ settings = settingsStore.load(or: { AppSettings() })+ for h in historyFile.load(or: { [] }) { history[h.url] = h }+ ranking = rankingFile.load(or: { RankingData() })+ repair()+ if prefs.focusedSpaceID == nil || spaces[prefs.focusedSpaceID!] == nil {+ prefs.focusedSpaceID = spaceOrder.first+ }+ }++ /// Make sure every space has its containers, favorites exist, 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.pinnedContainerID] == nil {+ let c = SidebarItem.container(.pinned(spaceID: id), id: space.pinnedContainerID)+ items[c.id] = c+ }+ if items[space.todayContainerID] == nil {+ let c = SidebarItem.container(.today(spaceID: id), id: space.todayContainerID)+ items[c.id] = c+ }+ spaces[id] = space+ _ = space+ }+ if spaces.isEmpty {+ 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 }+ }+ // Drop children references that do not resolve and orphans.+ for (id, var it) in items {+ it.children = it.children.filter { items[$0] != nil && items[$0]?.parentID == id }+ items[id] = it+ }+ for (id, it) in items where it.container == nil {+ if let p = it.parentID, let parent = items[p], parent.children.contains(id) { continue }+ // Orphan: put it in the first space's today list rather than losing it.+ if let space = spaceOrder.first.flatMap({ spaces[$0] }) {+ var fixed = it+ fixed.parentID = space.todayContainerID+ items[id] = fixed+ items[space.todayContainerID]?.children.append(id)+ }+ }+ }++ func save() {+ let doc = SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: spaceOrder.compactMap { spaces[$0] },+ favoritesContainerID: favoritesContainerID, 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))+ sidebarFile.saveNow(doc)+ archiveFile.saveNow(archive)+ prefsStore.saveNow(prefs)+ settingsStore.saveNow(settings)+ historyFile.saveNow(Array(history.values))+ rankingFile.saveNow(ranking)+ }++ private func touch() {+ revision &+= 1+ save()+ }++ // MARK: Lookup++ var orderedSpaces: [Space] { spaceOrder.compactMap { spaces[$0] } }+ var focusedSpaceID: UUID { prefs.focusedSpaceID ?? spaceOrder.first! }+ var focusedSpace: Space { spaces[focusedSpaceID] ?? orderedSpaces.first! }++ func item(_ id: UUID) -> SidebarItem? { items[id] }+ func space(_ id: UUID) -> Space? { spaces[id] }++ func children(of id: UUID) -> [SidebarItem] {+ (items[id]?.children ?? []).compactMap { items[$0] }+ }++ /// Depth-first list of every tab under a container or folder.+ func tabs(under id: UUID) -> [SidebarItem] {+ var out: [SidebarItem] = []+ func walk(_ id: UUID) {+ for c in children(of: id) {+ if c.isTab { out.append(c) } else if c.isFolder { walk(c.id) }+ }+ }+ walk(id)+ return out+ }++ func allTabs() -> [SidebarItem] { items.values.filter { $0.isTab } }++ /// Favorites + pinned + today for a space, in sidebar order. This is what+ /// ⌘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)+ }++ /// Which container an item ultimately lives in.+ func rootContainer(of id: UUID) -> ContainerKind? {+ var cur = items[id]+ var hops = 0+ while let c = cur, hops < 64 {+ if let kind = c.container { return kind }+ guard let p = c.parentID else { return nil }+ cur = items[p]+ hops += 1+ }+ 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 isPinned(_ id: UUID) -> Bool {+ switch rootContainer(of: id) {+ case .pinned, .favorites: return true+ default: return false+ }+ }++ func isFavorite(_ id: UUID) -> Bool { rootContainer(of: id) == .favorites }++ func selectedTabID(in spaceID: UUID) -> UUID? {+ guard let id = prefs.selectedTabPerSpace[spaceID], items[id]?.isTab == true else { return nil }+ return id+ }+ var selectedTabID: UUID? { selectedTabID(in: focusedSpaceID) }+ var selectedTab: SidebarItem? { selectedTabID.flatMap { items[$0] } }++ // MARK: Tabs++ @discardableResult+ func createTab(url: String, title: String = "", in spaceID: UUID? = nil, pinned: Bool = false,+ select: Bool = true, parent: UUID? = nil, index: Int? = nil) -> SidebarItem {+ let sid = spaceID ?? focusedSpaceID+ let space = spaces[sid] ?? focusedSpace+ let parentID = parent ?? (pinned ? space.pinnedContainerID : space.todayContainerID)+ var tab = SidebarItem.tab(url, title: title, parent: parentID)+ tab.data = .tab({ var t = TabData(url: url, title: title); t.activeTabBeforeCreationID = selectedTabID(in: sid); return t }())+ tab.isUnread = !select+ items[tab.id] = tab+ var p = items[parentID]!+ let at = index ?? (settings.newTabsAtTop && !pinned ? 0 : p.children.count)+ p.children.insert(tab.id, at: min(max(0, at), p.children.count))+ items[parentID] = p+ if select { selectTab(tab.id) } else { touch() }+ return tab+ }++ func selectTab(_ id: UUID?) {+ guard let id, let it = items[id], it.isTab else {+ prefs.selectedTabPerSpace[focusedSpaceID] = nil+ touch()+ return+ }+ let sid = spaceID(ofItem: id) ?? focusedSpaceID+ if sid != focusedSpaceID { prefs.focusedSpaceID = sid }+ prefs.selectedTabPerSpace[sid] = id+ var updated = it+ updated.isUnread = false+ if var t = updated.tab { t.timeLastActiveAt = Date(); updated.data = .tab(t) }+ items[id] = updated+ var dates = ranking.recentlySwitchedToTabs[id] ?? []+ dates.append(Date())+ if dates.count > 10 { dates.removeFirst(dates.count - 10) }+ ranking.recentlySwitchedToTabs[id] = dates+ rankingFile.save(ranking)+ touch()+ }++ func updateTab(_ id: UUID, url: String? = nil, title: String? = nil) {+ guard var it = items[id], var t = it.tab else { return }+ if let url, !url.isEmpty, url != "about:blank" {+ t.url = url+ if !isPinned(id) { t.savedURL = url }+ if let key = FaviconCache.key(for: url) { t.faviconKey = key }+ }+ if let title { t.savedTitle = title }+ it.data = .tab(t)+ items[id] = it+ revision &+= 1+ sidebarFile.save(SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: orderedSpaces,+ favoritesContainerID: favoritesContainerID, items: Array(items.values)), delay: 2)+ }++ func markUnread(_ id: UUID, _ unread: Bool = true) {+ guard var it = items[id] else { return }+ it.isUnread = unread+ items[id] = it+ revision &+= 1+ }++ func setMuted(_ id: UUID, _ muted: Bool) {+ guard var it = items[id], var t = it.tab else { return }+ t.muted = muted+ it.data = .tab(t)+ items[id] = it+ touch()+ }++ func rename(_ id: UUID, to title: String?) {+ guard var it = items[id] else { return }+ let trimmed = title?.trimmingCharacters(in: .whitespacesAndNewlines)+ it.title = (trimmed?.isEmpty ?? true) ? nil : trimmed+ items[id] = it+ touch()+ }++ /// Pinned tabs have a home URL. Reset returns there (Arc: resetTab).+ func resetPinnedTab(_ id: UUID) -> String? {+ guard var it = items[id], var t = it.tab, isPinned(id) else { return nil }+ t.url = t.savedURL+ it.data = .tab(t)+ items[id] = it+ touch()+ return t.savedURL+ }++ /// Make the current page the pinned home (Arc: replacePinnedTab).+ func setPinnedHomeToCurrent(_ id: UUID) {+ guard var it = items[id], var t = it.tab else { return }+ t.savedURL = t.url+ it.data = .tab(t)+ items[id] = it+ touch()+ }++ func duplicateTab(_ id: UUID) -> SidebarItem? {+ guard let it = items[id], let t = it.tab, let parent = it.parentID else { return nil }+ let idx = (items[parent]?.children.firstIndex(of: id) ?? 0) + 1+ return createTab(url: t.url, title: t.savedTitle, in: spaceID(ofItem: id), pinned: false,+ select: true, parent: parent, index: idx)+ }++ // MARK: Import helpers++ func insertItem(_ item: SidebarItem, into parent: UUID, at index: Int?) {+ var it = item+ it.parentID = parent+ items[it.id] = it+ guard var p = items[parent] else { return }+ p.children.insert(it.id, at: min(index ?? p.children.count, p.children.count))+ items[parent] = p+ }++ func appendArchived(_ entry: ArchivedItem) {+ archive.append(entry)+ archive.sort { $0.archivedAt > $1.archivedAt }+ }++ func touchAfterImport() { touch() }++ /// Replace the whole sidebar with a backup (cloud restore).+ func replaceDocument(_ doc: SidebarDocument) {+ spaces = [:]+ for s in doc.spaces { spaces[s.id] = s }+ spaceOrder = doc.spaceOrder.filter { spaces[$0] != nil }+ items = [:]+ for it in doc.items { items[it.id] = it }+ favoritesContainerID = doc.favoritesContainerID+ repair()+ prefs.focusedSpaceID = spaceOrder.first+ prefs.selectedTabPerSpace = [:]+ touch()+ }++ var document: SidebarDocument {+ SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: orderedSpaces, favoritesContainerID: favoritesContainerID, items: Array(items.values))+ }++ /// Most recently used tab other than the current one (⌃Tab).+ func mostRecentOtherTab() -> UUID? {+ let current = selectedTabID+ return ranking.recentlySwitchedToTabs+ .filter { $0.key != current && items[$0.key]?.isTab == true }+ .max { ($0.value.last ?? .distantPast) < ($1.value.last ?? .distantPast) }?.key+ }++ // MARK: Tree moves++ /// Detach an item from its parent without deleting it.+ private func detach(_ id: UUID) {+ guard let it = items[id], let p = it.parentID, var parent = items[p] else { return }+ parent.children.removeAll { $0 == id }+ items[p] = parent+ }++ private func isDescendant(_ candidate: UUID, of ancestor: UUID) -> Bool {+ var cur = items[candidate]?.parentID+ var hops = 0+ while let c = cur, hops < 64 {+ if c == ancestor { return true }+ cur = items[c]?.parentID+ hops += 1+ }+ return false+ }++ /// Move an item (tab or folder) under `newParent` at `index`. Folders may+ /// only live in pinned sections or favorites; dropping a folder into the+ /// today list unpacks it.+ func moveItem(_ id: UUID, to newParent: UUID, index: Int?) {+ guard var it = items[id], items[newParent] != nil, id != newParent, !isDescendant(newParent, of: id) else { return }+ let fromParent = it.parentID+ let oldIndex = fromParent.flatMap { items[$0]?.children.firstIndex(of: id) }+ if it.isFolder, case .today = rootContainerKind(newParent) ?? .favorites {+ // Unpack: move the folder's tabs instead.+ let kids = it.children+ detach(id)+ items[id] = nil+ var at = index ?? 0+ for k in kids {+ moveItem(k, to: newParent, index: at)+ at += 1+ }+ touch()+ return+ }+ detach(id)+ var parent = items[newParent]!+ var at = index ?? parent.children.count+ if fromParent == newParent, let old = oldIndex, old < at { at -= 1 }+ at = min(max(0, at), parent.children.count)+ parent.children.insert(id, at: at)+ items[newParent] = parent+ it.parentID = newParent+ if var t = it.tab {+ // Moving into a pinned section makes the current page the home.+ let kind = rootContainerKind(newParent)+ switch kind {+ case .pinned, .favorites: t.savedURL = t.url+ default: break+ }+ it.data = .tab(t)+ }+ items[id] = it+ touch()+ }++ private func rootContainerKind(_ id: UUID) -> ContainerKind? { rootContainer(of: id) }++ func pinTab(_ id: UUID) {+ guard let sid = spaceID(ofItem: id), let space = spaces[sid] else { return }+ if isFavorite(id) {+ moveItem(id, to: space.pinnedContainerID, index: nil)+ } else {+ moveItem(id, to: space.pinnedContainerID, index: nil)+ }+ }++ func unpinTab(_ id: UUID) {+ guard let sid = spaceID(ofItem: id), let space = spaces[sid] else { return }+ moveItem(id, to: space.todayContainerID, index: 0)+ }++ func togglePinned(_ id: UUID) {+ if isPinned(id) { unpinTab(id) } else { pinTab(id) }+ }++ func addToFavorites(_ id: UUID) { moveItem(id, to: favoritesContainerID, index: nil) }++ func removeFromFavorites(_ id: UUID) {+ moveItem(id, to: focusedSpace.pinnedContainerID, index: nil)+ }++ func moveTab(_ id: UUID, toSpace sid: UUID) {+ guard let space = spaces[sid] else { return }+ let pinned = isPinned(id)+ moveItem(id, to: pinned ? space.pinnedContainerID : space.todayContainerID, index: pinned ? nil : 0)+ }++ // MARK: Folders++ @discardableResult+ func createFolder(named name: String, in parent: UUID, index: Int? = nil) -> SidebarItem {+ var folder = SidebarItem.folder(name, parent: parent)+ folder.parentID = parent+ items[folder.id] = folder+ var p = items[parent]!+ p.children.insert(folder.id, at: min(index ?? p.children.count, p.children.count))+ items[parent] = p+ prefs.expandedFolders.insert(folder.id)+ touch()+ return folder+ }++ func deleteFolder(_ id: UUID) {+ guard let f = items[id], f.isFolder else { return }+ for t in tabs(under: id) { archiveTab(t.id, reason: .manual) }+ // Nested folders left behind (now empty) go too.+ for c in children(of: id) where c.isFolder { deleteFolder(c.id) }+ detach(id)+ items[id] = nil+ touch()+ }++ func isExpanded(_ id: UUID) -> Bool { prefs.expandedFolders.contains(id) }+ func setExpanded(_ id: UUID, _ expanded: Bool) {+ if expanded { prefs.expandedFolders.insert(id) } else { prefs.expandedFolders.remove(id) }+ }++ // MARK: Archive++ func archiveTab(_ id: UUID, reason: ArchiveReason) {+ guard let it = items[id], it.isTab else { return }+ let sid = spaceID(ofItem: id)+ let wasSelected = sid.flatMap { selectedTabID(in: $0) } == id+ let pinned = isPinned(id)+ detach(id)+ items[id] = nil+ archive.insert(ArchivedItem(archivedAt: Date(), reason: reason, sourceSpaceID: sid, wasPinned: pinned, item: it), at: 0)+ if archive.count > 2000 { archive.removeLast(archive.count - 2000) }+ if wasSelected, let sid {+ prefs.selectedTabPerSpace[sid] = nextSelection(after: it, in: sid)+ }+ touch()+ }++ /// Arc goes back to the tab you came from (activeTabBeforeCreationID) and+ /// otherwise to the neighbour in the list.+ private func nextSelection(after closed: SidebarItem, in sid: UUID) -> UUID? {+ if let back = closed.tab?.activeTabBeforeCreationID, items[back]?.isTab == true, spaceID(ofItem: back) == sid {+ return back+ }+ let list = visibleTabs(in: sid)+ guard !list.isEmpty else { return nil }+ if let p = closed.parentID, let siblings = items[p]?.children {+ // Prefer the sibling that took the closed tab's slot (the one below it).+ let today = tabs(under: p)+ if let first = today.first { _ = first }+ _ = siblings+ }+ // Fall back to the top-most today tab, then the first visible tab.+ if let space = spaces[sid], let first = tabs(under: space.todayContainerID).first { return first.id }+ return list.first?.id+ }++ @discardableResult+ func restoreArchived(_ id: UUID, select: Bool = true) -> SidebarItem? {+ guard let idx = archive.firstIndex(where: { $0.id == id }) else { return nil }+ let entry = archive.remove(at: idx)+ var it = entry.item+ let sid = entry.sourceSpaceID.flatMap { spaces[$0] != nil ? $0 : nil } ?? focusedSpaceID+ let space = spaces[sid]!+ let parent = entry.wasPinned ? space.pinnedContainerID : space.todayContainerID+ it.parentID = parent+ it.children = []+ it.isUnread = false+ items[it.id] = it+ var p = items[parent]!+ p.children.insert(it.id, at: entry.wasPinned ? p.children.count : 0)+ items[parent] = p+ if select { selectTab(it.id) } else { touch() }+ return it+ }++ @discardableResult+ func reopenLastArchived() -> SidebarItem? {+ guard let last = archive.first else { return nil }+ return restoreArchived(last.id)+ }++ func removeFromArchive(_ id: UUID) {+ archive.removeAll { $0.id == id }+ touch()+ }++ func clearArchive() {+ archive.removeAll()+ touch()+ }++ func clearToday(_ sid: UUID? = nil) {+ guard let space = spaces[sid ?? focusedSpaceID] else { return }+ for t in tabs(under: space.todayContainerID) { archiveTab(t.id, reason: .clear) }+ }++ /// Today tabs idle longer than the threshold are archived (Arc:+ /// ArchiveState+AutoArchive, autoArchiveTimeThreshold).+ func runAutoArchive() {+ let cutoff = Date().addingTimeInterval(-settings.autoArchive.seconds)+ for space in orderedSpaces {+ let selected = selectedTabID(in: space.id)+ for t in tabs(under: space.todayContainerID) where t.id != selected {+ let last = t.tab?.timeLastActiveAt ?? t.createdAt+ if last < cutoff { archiveTab(t.id, reason: .auto) }+ }+ }+ }++ // MARK: Spaces++ @discardableResult+ func createSpace(title: String, emoji: String, theme: SpaceTheme? = nil, focus: Bool = true) -> Space {+ let id = UUID()+ let pinned = SidebarItem.container(.pinned(spaceID: id))+ let today = SidebarItem.container(.today(spaceID: id))+ 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())+ spaces[id] = space+ spaceOrder.append(id)+ if focus { prefs.focusedSpaceID = id }+ touch()+ return space+ }++ func updateSpace(_ space: Space) {+ guard spaces[space.id] != nil else { return }+ spaces[space.id] = space+ touch()+ }++ 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) {+ archiveTab(t.id, reason: .spaceDeleted)+ }+ for c in children(of: space.pinnedContainerID) where c.isFolder { deleteFolder(c.id) }+ items[space.pinnedContainerID] = nil+ items[space.todayContainerID] = nil+ spaces[id] = nil+ spaceOrder.removeAll { $0 == id }+ prefs.selectedTabPerSpace[id] = nil+ if prefs.focusedSpaceID == id { prefs.focusedSpaceID = spaceOrder.first }+ touch()+ }++ func moveSpace(_ id: UUID, to index: Int) {+ guard let from = spaceOrder.firstIndex(of: id) else { return }+ spaceOrder.remove(at: from)+ spaceOrder.insert(id, at: min(max(0, index), spaceOrder.count))+ touch()+ }++ func focusSpace(_ id: UUID) {+ guard spaces[id] != nil, id != focusedSpaceID else { return }+ prefs.focusedSpaceID = id+ revision &+= 1+ }++ func focusSpace(offset: Int) {+ guard let idx = spaceOrder.firstIndex(of: focusedSpaceID), spaceOrder.count > 1 else { return }+ let n = spaceOrder.count+ focusSpace(spaceOrder[((idx + offset) % n + n) % n])+ }++ // MARK: History and ranking signals++ func recordVisit(url: String, title: String) {+ guard url.hasPrefix("http") else { return }+ var e = history[url] ?? HistoryEntry(url: url, title: title, lastVisit: Date(), visitCount: 0)+ e.visitCount += 1+ e.lastVisit = Date()+ if !title.isEmpty { e.title = title }+ history[url] = e+ if history.count > 5000 {+ let drop = history.values.sorted { $0.lastVisit < $1.lastVisit }.prefix(history.count - 5000)+ for d in drop { history[d.url] = nil }+ }+ historyFile.save(Array(history.values), delay: 5)+ }++ func recordQuerySelection(query: String, url: String) {+ let q = query.lowercased().trimmingCharacters(in: .whitespaces)+ guard !q.isEmpty else { return }+ ranking.queriesToSelected[q] = url+ if ranking.queriesToSelected.count > 500 {+ if let k = ranking.queriesToSelected.keys.first { ranking.queriesToSelected[k] = nil }+ }+ rankingFile.save(ranking)+ }++ func recordCommandUse(_ id: String) {+ ranking.commandUsage[id, default: 0] += 1+ rankingFile.save(ranking)+ }+}diff --git a/Sources/Cra/Services/SuggestionEngine.swift b/Sources/Cra/Services/SuggestionEngine.swiftnew file mode 100644index 0000000..a57a6d5--- /dev/null+++ b/Sources/Cra/Services/SuggestionEngine.swift@@ -0,0 +1,380 @@+import Foundation++enum CommandBarMode: Equatable {+ /// ⌘T: commit creates a new tab in the current space.+ case newTab+ /// ⌘L: commit navigates the current tab.+ case editURL+}++enum SuggestionKind: Equatable {+ case switchToTab(UUID)+ case archived(UUID)+ case history+ case navigate+ case search+ case topDomain+ case command(String)+ case switchSpace(UUID)+ case moveToSpace(UUID)+ case moveToFolder(UUID)+}++struct Suggestion: Identifiable, Equatable {+ let id: String+ let kind: SuggestionKind+ let title: String+ let subtitle: String+ let url: String?+ let faviconKey: String?+ let symbol: String?+ let trailing: String?+ var score: Double+ var spaceID: UUID? = nil+ var tabID: UUID? {+ if case .switchToTab(let id) = kind { return id }+ return nil+ }+}++struct SuggestionResult {+ var items: [Suggestion] = []+ /// Host (or more) to complete the typed text to, e.g. "github.com".+ var inlineCompletion: String?+ var query: String = ""+}++/// What makes ⌘T feel like Arc: open tabs, archived tabs, history, the+/// typed URL or search, popular domains and commands, ranked with+/// recency/frequency/learned signals (Arc: CommandBarRanking*).+@MainActor+final class SuggestionEngine {+ unowned let store: SidebarStore+ unowned let bindings: KeyBindingRegistry++ init(store: SidebarStore, bindings: KeyBindingRegistry) {+ self.store = store+ self.bindings = bindings+ }++ // MARK: Entry++ func suggestions(for rawQuery: String, mode: CommandBarMode, currentTabID: UUID?) -> SuggestionResult {+ let query = rawQuery.trimmingCharacters(in: .whitespaces)+ let q = query.lowercased()+ var result = SuggestionResult(query: query)+ if q.isEmpty {+ result.items = recentSuggestions(excluding: currentTabID)+ return result+ }++ var items: [Suggestion] = []+ let typed = typedRow(query: query)+ items.append(contentsOf: tabSuggestions(q, excluding: currentTabID))+ items.append(contentsOf: archiveSuggestions(q))+ items.append(contentsOf: historySuggestions(q, openURLs: Set(store.allTabs().compactMap { $0.tab?.url })))+ items.append(contentsOf: topDomainSuggestions(q))+ items.append(contentsOf: commandSuggestions(q, currentTabID: currentTabID))++ // Learned: the user picked this URL for this query before.+ if let learned = store.ranking.queriesToSelected[q] {+ for i in items.indices where items[i].url == learned { items[i].score += 150 }+ }++ items = dedupe(items)+ items.sort { $0.score > $1.score }++ // Arc's order: the row that supplies the inline completion comes first,+ // then what you typed, then everything else.+ let completion = inlineCompletion(q, candidates: items)+ if let completion, let idx = items.firstIndex(where: { $0.id == completion.candidateID }) {+ let c = items.remove(at: idx)+ items.insert(c, at: 0)+ items.insert(typed, at: 1)+ } else {+ items.insert(typed, at: 0)+ }+ result.items = Array(items.prefix(8))+ result.inlineCompletion = completion?.text+ return result+ }++ // MARK: Typed text++ static func looksLikeURL(_ s: String) -> Bool {+ let t = s.trimmingCharacters(in: .whitespaces)+ if t.isEmpty || t.contains(" ") { return false }+ if t.range(of: #"^[a-zA-Z][a-zA-Z0-9+.\-]*://"#, options: .regularExpression) != nil { return true }+ if t.hasPrefix("localhost") || t.hasPrefix("about:") || t.hasPrefix("view-source:") || t.hasPrefix("data:") || t.hasPrefix("file:") { return true }+ if t.range(of: #"^(\d{1,3}\.){3}\d{1,3}(:\d+)?(/.*)?$"#, options: .regularExpression) != nil { return true }+ // host.tld[:port][/path]+ return t.range(of: #"^[\w\-]+(\.[\w\-]+)+(:\d+)?(/\S*)?$"#, options: .regularExpression) != nil+ }++ static func urlFromInput(_ s: String) -> String {+ let t = s.trimmingCharacters(in: .whitespaces)+ if t.range(of: #"^[a-zA-Z][a-zA-Z0-9+.\-]*:"#, options: .regularExpression) != nil { return t }+ if t.hasPrefix("localhost") || t.range(of: #"^(\d{1,3}\.){3}\d{1,3}"#, options: .regularExpression) != nil {+ return "http://" + t+ }+ return "https://" + t+ }++ private func typedRow(query: String) -> Suggestion {+ if Self.looksLikeURL(query) {+ let url = Self.urlFromInput(query)+ return Suggestion(id: "typed", kind: .navigate, title: query, subtitle: "Open URL", url: url,+ faviconKey: FaviconCache.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)",+ url: engine.searchURL(query), faviconKey: nil, symbol: "magnifyingglass", trailing: nil, score: 1000)+ }++ // MARK: Sources++ private func tabSuggestions(_ q: String, excluding current: UUID?) -> [Suggestion] {+ var out: [Suggestion] = []+ for tab in store.allTabs() where tab.id != current {+ guard let t = tab.tab else { continue }+ var score = textScore(q, title: tab.displayTitle, url: t.url)+ if let custom = tab.title?.lowercased(), custom.hasPrefix(q) { score += 40 }+ if score < 30 { continue }+ score += recencyBoost(t.timeLastActiveAt)+ let switches = store.ranking.recentlySwitchedToTabs[tab.id]?.filter { $0 > Date().addingTimeInterval(-7 * 86400) }.count ?? 0+ score += Double(min(switches, 10)) * 3+ let sid = store.spaceID(ofItem: tab.id)+ let spaceName = sid.flatMap { store.space($0)?.title } ?? ""+ let pinned = store.isPinned(tab.id)+ out.append(Suggestion(id: "tab:\(tab.id)", kind: .switchToTab(tab.id), title: tab.displayTitle,+ subtitle: [spaceName, pinned ? "Pinned" : "", Self.humanURL(t.url)].filter { !$0.isEmpty }.joined(separator: " · "),+ url: t.url, faviconKey: t.faviconKey, symbol: nil, trailing: "Switch to Tab", score: score, spaceID: sid))+ }+ return out+ }++ private func archiveSuggestions(_ q: String) -> [Suggestion] {+ var out: [Suggestion] = []+ for entry in store.archive.prefix(400) {+ guard let t = entry.item.tab else { continue }+ var score = textScore(q, title: entry.item.displayTitle, url: t.url) * 0.85+ if score < 30 { continue }+ score += recencyBoost(entry.archivedAt) * 0.5+ let spaceName = entry.sourceSpaceID.flatMap { store.space($0)?.title } ?? ""+ out.append(Suggestion(id: "arch:\(entry.id)", kind: .archived(entry.id), title: entry.item.displayTitle,+ subtitle: ["Archived \(Self.relative(entry.archivedAt))", spaceName, Self.humanURL(t.url)].filter { !$0.isEmpty }.joined(separator: " · "),+ url: t.url, faviconKey: t.faviconKey, symbol: nil, trailing: "Restore", score: score))+ }+ return out+ }++ private func historySuggestions(_ q: String, openURLs: Set<String>) -> [Suggestion] {+ var out: [Suggestion] = []+ for h in store.history.values where !openURLs.contains(h.url) {+ var score = textScore(q, title: h.title, url: h.url) * 0.8+ if score < 30 { continue }+ score += min(Double(h.visitCount), 20) * 1.5 + recencyBoost(h.lastVisit) * 0.6+ out.append(Suggestion(id: "hist:\(h.url)", kind: .history, title: h.title.isEmpty ? Self.humanURL(h.url) : h.title,+ subtitle: Self.humanURL(h.url), url: h.url, faviconKey: FaviconCache.key(for: h.url),+ symbol: "clock", trailing: nil, score: score))+ }+ return out+ }++ private func topDomainSuggestions(_ q: String) -> [Suggestion] {+ guard !q.contains(" ") else { return [] }+ var out: [Suggestion] = []+ for (i, d) in PopularDomains.list.enumerated() {+ let bare = d.hasPrefix("www.") ? String(d.dropFirst(4)) : d+ guard bare.hasPrefix(q) || d.hasPrefix(q) else { continue }+ let url = "https://\(d)/"+ out.append(Suggestion(id: "top:\(d)", kind: .topDomain, title: bare, subtitle: "Open URL", url: url,+ faviconKey: FaviconCache.key(for: url), symbol: "globe", trailing: nil,+ score: 72 - Double(i) * 0.1))+ }+ return out+ }++ private func commandSuggestions(_ q: String, currentTabID: UUID?) -> [Suggestion] {+ guard q.count >= 2 else { return [] }+ var out: [Suggestion] = []+ func nameScore(_ name: String, triggers: [String]) -> Double {+ let n = name.lowercased()+ if n.hasPrefix(q) { return 80 }+ if n.split(separator: " ").contains(where: { $0.hasPrefix(q) }) { return 68 }+ if triggers.contains(where: { $0.hasPrefix(q) }) { return 70 }+ if n.contains(q) { return 50 }+ return 0+ }+ for a in bindings.actions where a.inCommandBar {+ var s = nameScore(a.name, triggers: a.triggers)+ guard s > 0 else { continue }+ s += Double(min(store.ranking.commandUsage[a.id] ?? 0, 10)) * 2+ out.append(Suggestion(id: "cmd:\(a.id)", kind: .command(a.id), title: a.name, subtitle: "Command",+ url: nil, faviconKey: nil, symbol: "command", trailing: a.primary?.display, score: s))+ }+ for space in store.orderedSpaces {+ let s = nameScore("Switch to \(space.title)", triggers: [space.title.lowercased()])+ if s > 0 && space.id != store.focusedSpaceID {+ out.append(Suggestion(id: "space:\(space.id)", kind: .switchSpace(space.id), title: "Switch to \(space.title)",+ subtitle: "Space", url: nil, faviconKey: nil, symbol: nil, trailing: space.emoji, score: s))+ }+ if currentTabID != nil, space.id != store.focusedSpaceID {+ let m = nameScore("Move Tab to \(space.title)", triggers: ["move"])+ if m > 0 {+ out.append(Suggestion(id: "move:\(space.id)", kind: .moveToSpace(space.id), title: "Move Tab to \(space.title)",+ subtitle: "Space", url: nil, faviconKey: nil, symbol: "arrow.right.square", trailing: space.emoji, score: m - 5))+ }+ }+ }+ if currentTabID != nil {+ for f in store.children(of: store.focusedSpace.pinnedContainerID) where f.isFolder {+ let name = f.title ?? "Folder"+ let m = nameScore("Move Tab to Folder \(name)", triggers: [name.lowercased()])+ if m > 0 {+ out.append(Suggestion(id: "folder:\(f.id)", kind: .moveToFolder(f.id), title: "Move Tab to \(name)",+ subtitle: "Folder", url: nil, faviconKey: nil, symbol: "folder", trailing: nil, score: m - 5))+ }+ }+ }+ return out+ }++ private func recentSuggestions(excluding current: UUID?) -> [Suggestion] {+ let tabs = store.allTabs().filter { $0.id != current }+ .sorted { ($0.tab?.timeLastActiveAt ?? .distantPast) > ($1.tab?.timeLastActiveAt ?? .distantPast) }+ .prefix(7)+ var out: [Suggestion] = tabs.map { tab in+ let sid = store.spaceID(ofItem: tab.id)+ return Suggestion(id: "tab:\(tab.id)", kind: .switchToTab(tab.id), title: tab.displayTitle,+ subtitle: [sid.flatMap { store.space($0)?.title } ?? "", Self.humanURL(tab.tab?.url ?? "")].filter { !$0.isEmpty }.joined(separator: " · "),+ url: tab.tab?.url, faviconKey: tab.tab?.faviconKey, symbol: nil, trailing: "Switch to Tab", score: 0, spaceID: sid)+ }+ for entry in store.archive.prefix(2) {+ guard let t = entry.item.tab else { continue }+ out.append(Suggestion(id: "arch:\(entry.id)", kind: .archived(entry.id), title: entry.item.displayTitle,+ subtitle: "Archived \(Self.relative(entry.archivedAt))", url: t.url, faviconKey: t.faviconKey,+ symbol: nil, trailing: "Restore", score: 0))+ }+ return out+ }++ // MARK: Scoring++ /// 0...100 from how well the query matches a title and a URL.+ func textScore(_ q: String, title: String, url: String) -> Double {+ let t = title.lowercased()+ let u = Self.humanURL(url).lowercased()+ let host = (URL(string: url)?.host ?? "").lowercased()+ let bareHost = host.hasPrefix("www.") ? String(host.dropFirst(4)) : host+ var score = 0.0+ let tokens = q.split(separator: " ").map(String.init)+ if tokens.count > 1 {+ let hay = t + " " + u+ let hits = tokens.filter { hay.contains($0) }.count+ if hits == tokens.count { score = 75 } else if hits > 0 { score = 30 * Double(hits) / Double(tokens.count) }+ if t.hasPrefix(q) { score = 95 }+ return score+ }+ if t.hasPrefix(q) { score = 100 }+ else if t.split(whereSeparator: { !$0.isLetter && !$0.isNumber }).contains(where: { $0.hasPrefix(q) }) { score = 85 }+ else if t.contains(q) { score = 65 }+ else if let f = fuzzy(q, in: t) { score = 25 + 25 * f }+ if bareHost.hasPrefix(q) || host.hasPrefix(q) { score = max(score, 95) }+ else if bareHost.contains(q) { score = max(score, 70) }+ else if u.contains(q) { score = max(score, 55) }+ return score+ }++ /// Subsequence match quality (0...1) or nil when not a subsequence.+ private func fuzzy(_ q: String, in text: String) -> Double? {+ guard q.count >= 3 else { return nil }+ var it = text.makeIterator()+ var matched = 0+ var gaps = 0+ var inGap = false+ for c in q {+ var found = false+ while let x = it.next() {+ if x == c { found = true; break }+ inGap = true+ }+ if !found { return nil }+ if inGap { gaps += 1; inGap = false }+ matched += 1+ }+ return max(0, 1 - Double(gaps) / Double(q.count))+ }++ private func recencyBoost(_ date: Date?) -> Double {+ guard let date else { return 0 }+ let age = Date().timeIntervalSince(date)+ if age < 600 { return 30 }+ if age < 3600 { return 22 }+ if age < 86400 { return 14 }+ if age < 7 * 86400 { return 7 }+ return 0+ }++ /// Arc dedups by title+host for sites whose tabs share titles+ /// (command_bar_behavior.json: dedupByTitleAndHostList).+ private static let dedupHosts: Set<String> = ["figma.com", "www.figma.com", "notion.so", "www.notion.so", "github.com",+ "zoom.us", "maps.google.com", "console.cloud.google.com", "app.slack.com",+ "linear.app", "www.youtube.com", "docs.google.com", "mail.google.com"]++ private func dedupe(_ items: [Suggestion]) -> [Suggestion] {+ var seen: Set<String> = []+ var out: [Suggestion] = []+ for s in items.sorted(by: { $0.score > $1.score }) {+ var key = s.id+ if let url = s.url, let host = URL(string: url)?.host?.lowercased() {+ key = Self.dedupHosts.contains(host) ? "\(host)|\(s.title.lowercased())" : url+ if case .command = s.kind { key = s.id }+ }+ if seen.insert(key).inserted { out.append(s) }+ }+ return out+ }++ private func inlineCompletion(_ q: String, candidates: [Suggestion]) -> (text: String, candidateID: String)? {+ guard !q.contains(" "), q.count >= 2, !Self.looksLikeURL(q) || !q.contains("/") else { return nil }+ for c in candidates {+ guard let url = c.url, c.score >= 90 || c.kind == .topDomain, let host = URL(string: url)?.host?.lowercased() else { continue }+ let bare = host.hasPrefix("www.") ? String(host.dropFirst(4)) : host+ if bare.hasPrefix(q) && bare != q { return (bare, c.id) }+ if host.hasPrefix(q) && host != q { return (host, c.id) }+ }+ return nil+ }++ // MARK: Formatting++ static func humanURL(_ url: String) -> String {+ var s = url+ for p in ["https://www.", "http://www.", "https://", "http://"] where s.hasPrefix(p) { s = String(s.dropFirst(p.count)); break }+ if s.hasSuffix("/") { s.removeLast() }+ if s.count > 70 { s = String(s.prefix(67)) + "…" }+ return s+ }++ static func relative(_ date: Date) -> String {+ let f = RelativeDateTimeFormatter()+ f.unitsStyle = .short+ return f.localizedString(for: date, relativeTo: Date())+ }+}++enum PopularDomains {+ static let list: [String] = [+ "google.com", "youtube.com", "github.com", "gmail.com", "mail.google.com", "docs.google.com", "drive.google.com",+ "calendar.google.com", "maps.google.com", "chatgpt.com", "claude.ai", "x.com", "twitter.com", "reddit.com",+ "wikipedia.org", "en.wikipedia.org", "amazon.com", "apple.com", "developer.apple.com", "netflix.com", "linkedin.com",+ "facebook.com", "instagram.com", "notion.so", "figma.com", "slack.com", "app.slack.com", "discord.com", "zoom.us",+ "vercel.com", "stackoverflow.com", "npmjs.com", "medium.com", "nytimes.com", "bbc.com", "spotify.com",+ "open.spotify.com", "dr.dk", "tv2.dk", "jysk.com", "jysk.dk", "stripe.com", "dashboard.stripe.com", "cloudflare.com",+ "aws.amazon.com", "console.cloud.google.com", "linear.app", "trello.com", "asana.com", "dropbox.com",+ "icloud.com", "twitch.tv", "pinterest.com", "ebay.com", "booking.com", "airbnb.com", "paypal.com",+ "convex.dev", "supabase.com", "openai.com", "platform.openai.com", "anthropic.com", "huggingface.co",+ "producthunt.com", "news.ycombinator.com", "arc.net", "tryspook.com", "kildahl.dk", "localhost:3000",+ ]+}diff --git a/Sources/Cra/UI/BrandMark.swift b/Sources/Cra/UI/BrandMark.swiftnew file mode 100644index 0000000..3548097--- /dev/null+++ b/Sources/Cra/UI/BrandMark.swift@@ -0,0 +1,26 @@+import SwiftUI++/// The Cra "segments" mark from brand/cra-segments.svg, rendered at build time+/// into resources/brand (WebKit, so the multiply blends survive).+struct BrandMark: View {+ var size: CGFloat = 48+ var mono = false++ private static let colour: NSImage? = load("cra-mark@2x")+ private static let monoImage: NSImage? = load("cra-mark-mono")++ private static func load(_ name: String) -> NSImage? {+ guard let url = Bundle.main.url(forResource: name, withExtension: "png", subdirectory: "brand") else { return nil }+ return NSImage(contentsOf: url)+ }++ var body: some View {+ if let img = mono ? BrandMark.monoImage : BrandMark.colour {+ Image(nsImage: img)+ .resizable()+ .interpolation(.high)+ .frame(width: size, height: size)+ .accessibilityLabel("Cra")+ }+ }+}diff --git a/Sources/Cra/UI/CommandBar/CommandBarController.swift b/Sources/Cra/UI/CommandBar/CommandBarController.swiftnew file mode 100644index 0000000..9732c0a--- /dev/null+++ b/Sources/Cra/UI/CommandBar/CommandBarController.swift@@ -0,0 +1,124 @@+import AppKit+import Observation+import SwiftUI++/// State + behaviour of the ⌘T / ⌘L bar. The panel and SwiftUI view read+/// from here; MainWindowController owns commits.+@MainActor+@Observable+final class CommandBarController {+ var isOpen = false+ var mode: CommandBarMode = .newTab+ var query = ""+ var result = SuggestionResult()+ var selectedIndex = 0+ /// Text pushed into the field from outside (prefill); bump version to apply.+ var fieldText = ""+ var fieldTextVersion = 0+ var allowCompletion = true+ /// Layout hints set by the window controller before opening.+ var panelWidth: CGFloat = CraMetrics.commandBarWidth+ var attached = false+ var highlight: Color = .accentColor.opacity(0.4)+ var focusedSpaceID: UUID?+ var spaceName: (UUID) -> String = { _ in "" }++ unowned let engine: SuggestionEngine+ unowned let store: SidebarStore+ var onCommit: (Suggestion?, String, CommandBarMode, Bool) -> Void = { _, _, _, _ in }+ var onClose: () -> Void = {}++ init(engine: SuggestionEngine, store: SidebarStore) {+ self.engine = engine+ self.store = store+ }++ var placeholder: String {+ switch mode {+ case .newTab: return "Search or enter URL…"+ case .editURL: return "Edit URL or search…"+ }+ }++ func open(mode: CommandBarMode, prefill: String?) {+ self.mode = mode+ query = prefill ?? ""+ fieldText = query+ fieldTextVersion += 1+ allowCompletion = false+ selectedIndex = 0+ result = engine.suggestions(for: query, mode: mode, currentTabID: store.selectedTabID)+ isOpen = true+ }++ /// Replace the typed text (scripting / tests).+ func setQuery(_ text: String) {+ fieldText = text+ fieldTextVersion += 1+ update(query: text, allowCompletion: true)+ }++ func update(query newQuery: String, allowCompletion: Bool) {+ query = newQuery+ self.allowCompletion = allowCompletion+ result = engine.suggestions(for: newQuery, mode: mode, currentTabID: store.selectedTabID)+ if !allowCompletion { result.inlineCompletion = nil }+ selectedIndex = 0+ }++ func moveSelection(by delta: Int) {+ guard !result.items.isEmpty else { return }+ let n = result.items.count+ selectedIndex = ((selectedIndex + delta) % n + n) % n+ }++ /// Accept the inline completion (Tab / →).+ func acceptCompletion() -> Bool {+ guard let c = result.inlineCompletion else { return false }+ fieldText = c+ fieldTextVersion += 1+ update(query: c, allowCompletion: false)+ return true+ }++ func commit(forceNewTab: Bool) {+ let selected = result.items.indices.contains(selectedIndex) ? result.items[selectedIndex] : nil+ var typed = query+ // Enter on the typed row with an inline completion goes to the completion.+ if selectedIndex == 0, let c = result.inlineCompletion, selected?.id == "typed" { typed = c }+ close()+ onCommit(selected, typed, mode, forceNewTab)+ }++ func commit(_ suggestion: Suggestion) {+ close()+ onCommit(suggestion, query, mode, false)+ }++ func close() {+ guard isOpen else { return }+ isOpen = false+ onClose()+ }+}++/// Borderless floating panel that can take keyboard focus.+final class CommandBarPanel: NSPanel {+ override var canBecomeKey: Bool { true }+ override var canBecomeMain: Bool { false }++ init() {+ super.init(contentRect: NSRect(x: 0, y: 0, width: 680, height: 60),+ styleMask: [.borderless, .nonactivatingPanel, .fullSizeContentView],+ backing: .buffered, defer: false)+ isFloatingPanel = true+ level = .floating+ backgroundColor = .clear+ isOpaque = false+ hasShadow = true+ hidesOnDeactivate = false+ isMovableByWindowBackground = false+ animationBehavior = .utilityWindow+ collectionBehavior = [.fullScreenAuxiliary, .moveToActiveSpace]+ }+}diff --git a/Sources/Cra/UI/CommandBar/CommandBarView.swift b/Sources/Cra/UI/CommandBar/CommandBarView.swiftnew file mode 100644index 0000000..bdb015f--- /dev/null+++ b/Sources/Cra/UI/CommandBar/CommandBarView.swift@@ -0,0 +1,150 @@+import SwiftUI++/// Arc's command bar: a wide translucent panel, input row with the top+/// match's favicon, single-line rows "Title — url", the selected row tinted+/// with the space color, "Switch to Tab" + arrow for open tabs.+struct CommandBarView: View {+ let controller: CommandBarController+ @Environment(FaviconCache.self) private var favicons+ @Environment(\.colorScheme) private var scheme++ static let rowHeight: CGFloat = 50+ static let fieldHeight: CGFloat = 60+ static func height(forRows n: Int) -> CGFloat { fieldHeight + (n == 0 ? 0 : CGFloat(n) * rowHeight + CGFloat(n - 1) * 2 + 20) }++ private var dark: Bool { scheme == .dark }+ @State private var shown = false++ /// Arc pops the bar in with a short fade and a hint of scale; driven by the+ /// controller's open state so it replays on every open.+ var body: some View {+ content+ .opacity(shown ? 1 : 0)+ .scaleEffect(shown ? 1 : 0.985, anchor: .top)+ .onChange(of: controller.isOpen, initial: true) { _, open in+ withAnimation(open ? .easeOut(duration: 0.12) : .easeIn(duration: 0.08)) { shown = open }+ }+ }++ private var content: some View {+ let items = controller.result.items+ return VStack(spacing: 0) {+ HStack(spacing: 14) {+ leadingIcon.frame(width: 22, height: 22)+ CommandTextField(controller: controller)+ .frame(height: 30)+ if controller.query.isEmpty {+ Image(systemName: "info.circle")+ .font(.system(size: 16, weight: .regular))+ .foregroundStyle(.secondary)+ }+ }+ .padding(.horizontal, 22)+ .frame(height: Self.fieldHeight)++ if !items.isEmpty {+ Rectangle().fill(Color.primary.opacity(0.08)).frame(height: 1).padding(.horizontal, 16)+ VStack(spacing: 2) {+ ForEach(Array(items.enumerated()), id: \.element.id) { idx, s in+ SuggestionRow(suggestion: s, selected: idx == controller.selectedIndex,+ highlight: controller.highlight, focusedSpaceID: controller.focusedSpaceID,+ spaceName: controller.spaceName, queryEmpty: controller.query.isEmpty, dark: dark)+ .onHover { if $0 { controller.selectedIndex = idx } }+ .onTapGesture { controller.commit(s) }+ }+ }+ .padding(10)+ }+ }+ .frame(width: controller.panelWidth)+ .background(dark ? AnyShapeStyle(Color.black.opacity(0.74)) : AnyShapeStyle(Color.white.opacity(0.7)))+ .background(.ultraThinMaterial)+ .clipShape(UnevenRoundedRectangle(topLeadingRadius: controller.attached ? 10 : 14, bottomLeadingRadius: 14,+ bottomTrailingRadius: 14, topTrailingRadius: controller.attached ? 10 : 14, style: .continuous))+ .overlay(UnevenRoundedRectangle(topLeadingRadius: controller.attached ? 10 : 14, bottomLeadingRadius: 14,+ bottomTrailingRadius: 14, topTrailingRadius: controller.attached ? 10 : 14, style: .continuous)+ .strokeBorder(Color.primary.opacity(dark ? 0.12 : 0.08)))+ }++ @ViewBuilder private var leadingIcon: some View {+ if let s = controller.result.items.first, let key = s.faviconKey, s.id != "typed", let img = favicons.image(forKey: key),+ controller.result.inlineCompletion != nil || controller.mode == .editURL {+ Image(nsImage: img).resizable().interpolation(.high).aspectRatio(contentMode: .fit)+ .frame(width: 20, height: 20).clipShape(RoundedRectangle(cornerRadius: 5, style: .continuous))+ } else {+ Image(systemName: controller.mode == .editURL ? "info.circle" : "magnifyingglass")+ .font(.system(size: 17, weight: .medium))+ .foregroundStyle(.secondary)+ }+ }+}++struct SuggestionRow: View {+ let suggestion: Suggestion+ let selected: Bool+ let highlight: Color+ let focusedSpaceID: UUID?+ let spaceName: (UUID) -> String+ let queryEmpty: Bool+ let dark: Bool+ @Environment(FaviconCache.self) private var favicons++ private var isTab: Bool { suggestion.tabID != nil }+ private var otherSpace: String? {+ guard isTab, let sid = suggestion.spaceID, sid != focusedSpaceID else { return nil }+ return spaceName(sid)+ }++ var body: some View {+ HStack(spacing: 14) {+ icon.frame(width: 26, height: 26)+ (Text(suggestion.title).font(.system(size: 15, weight: .semibold)).foregroundStyle(.primary)+ + Text(detailText).font(.system(size: 15)).foregroundStyle(.secondary))+ .lineLimit(1)+ .truncationMode(.middle)+ Spacer(minLength: 8)+ if isTab {+ Text(otherSpace ?? (queryEmpty ? "" : "Switch to Tab"))+ .font(.system(size: 14, weight: .medium))+ .foregroundStyle(.secondary)+ Image(systemName: "arrow.right")+ .font(.system(size: 12, weight: .bold))+ .foregroundStyle(.primary.opacity(0.8))+ .frame(width: 22, height: 22)+ .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(Color.primary.opacity(0.1)))+ } else if let t = suggestion.trailing {+ Text(t).font(.system(size: 13, weight: .medium)).foregroundStyle(.secondary)+ }+ }+ .padding(.horizontal, 14)+ .frame(height: CommandBarView.rowHeight)+ .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(selected ? highlight : .clear))+ .contentShape(Rectangle())+ }++ private var detailText: String {+ switch suggestion.kind {+ case .switchToTab, .search, .command, .switchSpace, .moveToSpace, .moveToFolder: return ""+ case .archived: return suggestion.subtitle.isEmpty ? "" : " — \(suggestion.subtitle)"+ default:+ guard let url = suggestion.url else { return "" }+ let human = SuggestionEngine.humanURL(url)+ return human.lowercased() == suggestion.title.lowercased() ? "" : " — \(human)"+ }+ }++ @ViewBuilder private var icon: some View {+ if let key = suggestion.faviconKey, let img = favicons.image(forKey: key) {+ Image(nsImage: img).resizable().interpolation(.high).aspectRatio(contentMode: .fit)+ .frame(width: 18, height: 18)+ .padding(4)+ .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(dark ? Color.white.opacity(0.14) : Color.black.opacity(0.06)))+ } else if case .switchSpace = suggestion.kind, let t = suggestion.trailing {+ Text(t).font(.system(size: 16))+ } else {+ Image(systemName: suggestion.symbol ?? "globe")+ .font(.system(size: 15, weight: .medium))+ .foregroundStyle(.secondary)+ }+ }+}diff --git a/Sources/Cra/UI/CommandBar/CommandTextField.swift b/Sources/Cra/UI/CommandBar/CommandTextField.swiftnew file mode 100644index 0000000..d531af5--- /dev/null+++ b/Sources/Cra/UI/CommandBar/CommandTextField.swift@@ -0,0 +1,131 @@+import AppKit+import SwiftUI++/// NSTextField wrapper with Chrome/Arc-style inline completion: the+/// completed suffix is inserted selected, so typing replaces it and+/// Backspace removes it without re-completing.+struct CommandTextField: NSViewRepresentable {+ let controller: CommandBarController++ func makeNSView(context: Context) -> NSTextField {+ let field = NSTextField(string: controller.fieldText)+ field.isBordered = false+ field.isBezeled = false+ field.drawsBackground = false+ field.focusRingType = .none+ field.font = .systemFont(ofSize: 20, weight: .regular)+ field.placeholderString = controller.placeholder+ field.delegate = context.coordinator+ field.lineBreakMode = .byTruncatingTail+ field.cell?.usesSingleLineMode = true+ field.cell?.wraps = false+ field.cell?.isScrollable = true+ context.coordinator.field = field+ DispatchQueue.main.async {+ field.window?.makeFirstResponder(field)+ field.currentEditor()?.selectAll(nil)+ }+ return field+ }++ func updateNSView(_ field: NSTextField, context: Context) {+ field.placeholderString = controller.placeholder+ let coord = context.coordinator+ if coord.appliedVersion != controller.fieldTextVersion {+ coord.appliedVersion = controller.fieldTextVersion+ coord.suppressChange = true+ field.stringValue = controller.fieldText+ coord.lastTyped = controller.fieldText+ coord.suppressChange = false+ DispatchQueue.main.async {+ field.window?.makeFirstResponder(field)+ field.currentEditor()?.selectAll(nil)+ }+ }+ if let c = controller.result.inlineCompletion, controller.allowCompletion, coord.pendingCompletion != c {+ coord.applyCompletion(c)+ } else if controller.result.inlineCompletion == nil {+ coord.pendingCompletion = nil+ }+ }++ func makeCoordinator() -> Coordinator { Coordinator(controller: controller) }++ @MainActor+ final class Coordinator: NSObject, NSTextFieldDelegate {+ let controller: CommandBarController+ weak var field: NSTextField?+ var appliedVersion = 0+ var lastTyped = ""+ var suppressChange = false+ var pendingCompletion: String?++ init(controller: CommandBarController) { self.controller = controller }++ func applyCompletion(_ completion: String) {+ guard let field, let editor = field.currentEditor() else { return }+ let typed = lastTyped+ guard completion.lowercased().hasPrefix(typed.lowercased()), completion.count > typed.count else { return }+ let remainder = String(completion.dropFirst(typed.count))+ pendingCompletion = completion+ suppressChange = true+ field.stringValue = typed + remainder+ editor.selectedRange = NSRange(location: (typed as NSString).length, length: (remainder as NSString).length)+ suppressChange = false+ }++ func controlTextDidChange(_ obj: Notification) {+ guard !suppressChange, let field else { return }+ let text = field.stringValue+ let deleting = text.count < lastTyped.count || (pendingCompletion != nil && text == lastTyped)+ lastTyped = text+ pendingCompletion = nil+ controller.update(query: text, allowCompletion: !deleting)+ }++ func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {+ switch selector {+ case #selector(NSResponder.moveDown(_:)):+ controller.moveSelection(by: 1); return true+ case #selector(NSResponder.moveUp(_:)):+ controller.moveSelection(by: -1); return true+ case #selector(NSResponder.insertNewline(_:)):+ let cmd = NSApp.currentEvent?.modifierFlags.contains(.command) ?? false+ // If a completion suffix is selected, Enter means "go there".+ if pendingCompletion != nil, textView.selectedRange.length > 0 {+ lastTyped = textView.string+ controller.update(query: textView.string, allowCompletion: false)+ }+ controller.commit(forceNewTab: cmd)+ return true+ case #selector(NSResponder.cancelOperation(_:)):+ controller.close(); return true+ case #selector(NSResponder.insertTab(_:)), #selector(NSResponder.moveRight(_:)), #selector(NSResponder.moveToEndOfLine(_:)):+ if pendingCompletion != nil, textView.selectedRange.length > 0 {+ let text = textView.string+ textView.setSelectedRange(NSRange(location: (text as NSString).length, length: 0))+ lastTyped = text+ pendingCompletion = nil+ controller.update(query: text, allowCompletion: false)+ return true+ }+ return selector == #selector(NSResponder.insertTab(_:))+ case #selector(NSResponder.deleteBackward(_:)):+ if pendingCompletion != nil, textView.selectedRange.length > 0 {+ // Remove the suggestion, keep what was typed.+ let typed = lastTyped+ pendingCompletion = nil+ suppressChange = true+ textView.string = typed+ textView.setSelectedRange(NSRange(location: (typed as NSString).length, length: 0))+ suppressChange = false+ controller.update(query: typed, allowCompletion: false)+ return true+ }+ return false+ default:+ return false+ }+ }+ }+}diff --git a/Sources/Cra/UI/ContentToolbarView.swift b/Sources/Cra/UI/ContentToolbarView.swiftnew file mode 100644index 0000000..1621965--- /dev/null+++ b/Sources/Cra/UI/ContentToolbarView.swift@@ -0,0 +1,156 @@+import SwiftUI++/// Arc's toolbar above the page: lock + URL (monospaced), copy link, DevTools,+/// sidebar toggle. With no tab it carries the nav buttons and a centered+/// "Search or Enter URL…" placeholder instead.+struct ContentToolbarView: View {+ let palette: SpacePalette+ @Environment(SidebarStore.self) private var store+ @Environment(SidebarUIState.self) private var ui+ @Environment(\.sidebarActions) private var actions+ @State private var hoverURL = false++ private var onCard: Bool { store.selectedTab != nil }+ @Environment(FaviconCache.self) private var favicons++ /// Arc's toolbar colour: the page's theme-color when it declares one+ /// (Messenger's white included), else a dark favicon colour, else the+ /// space tint.+ private var cardHex: String? {+ let theme = ui.pageThemeColor+ if theme != "none", !theme.isEmpty, HexColor.components(theme) != nil { return theme }+ return nil+ }+ private var cardFill: Color { cardHex.map { Color(hex: $0) } ?? palette.toolbarFill }+ private var cardIsLight: Bool { (cardHex.flatMap(HexColor.luminance) ?? 0) > 0.6 }+ private var fg: Color { onCard ? (cardIsLight ? Color.black.opacity(0.8) : Color(hex: "#E4E0D4")) : palette.textSecondary }+ private var fgDim: Color { onCard ? (cardIsLight ? Color.black.opacity(0.6) : Color(hex: "#F0E6CC").opacity(0.9)) : palette.textTertiary }++ private var developerMode: Bool { store.selectedTab?.tab.map { store.settings.isDeveloperMode(url: $0.url) } ?? false }++ /// Arc's default bar: nav buttons at the left, the friendly URL centred+ /// (host bright, path dimmer) behind a link glyph.+ @ViewBuilder private func defaultBar(_ t: TabData) -> some View {+ let human = SuggestionEngine.humanURL(t.url)+ let host = AppSettings.siteKey(for: t.url) ?? human+ let path = human.hasPrefix(host) ? String(human.dropFirst(host.count)) : ""+ HStack(spacing: 0) {+ ToolbarIcon(symbol: "arrow.left", fg: fgDim, help: "Go Back (⌘[)", enabled: ui.canGoBack, width: 37, iconSize: 15) { actions.goBack() }+ ToolbarIcon(symbol: "arrow.right", fg: fgDim, help: "Go Forward (⌘])", enabled: ui.canGoForward, width: 37, iconSize: 15) { actions.goForward() }+ ToolbarIcon(symbol: ui.isLoading ? "xmark" : "arrow.clockwise", fg: fgDim, help: "Refresh (⌘R)", width: 37, iconSize: 15) { actions.reload() }+ }+ .padding(.leading, 1)+ Spacer(minLength: 8)+ Button { actions.openCommandBar(.editURL) } label: {+ HStack(spacing: 7) {+ Image(systemName: "link").font(.system(size: 12, weight: .medium)).foregroundStyle(fgDim)+ (Text(host).foregroundStyle(fg) + Text(path).foregroundStyle(fgDim))+ .font(.system(size: 13))+ .lineLimit(1)+ .truncationMode(.tail)+ }+ .padding(.horizontal, 10)+ .frame(height: 28)+ .background(RoundedRectangle(cornerRadius: 7).fill(hoverURL ? Color.white.opacity(0.08) : .clear))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .onHover { hoverURL = $0 }+ .help(t.url)+ Spacer(minLength: 8)+ }++ var body: some View {+ let tab = store.selectedTab+ HStack(spacing: 6) {+ if let tab, let t = tab.tab, !developerMode {+ defaultBar(t)+ } else if let tab, let t = tab.tab {+ Button { actions.openCommandBar(.editURL) } label: {+ HStack(spacing: 12) {+ Image(systemName: t.url.hasPrefix("https://") ? "lock.fill" : "globe")+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(fgDim)+ .frame(width: 14)+ Text(t.url)+ .font(.system(size: 12, design: .monospaced))+ .foregroundStyle(fg)+ .lineLimit(1)+ .truncationMode(.tail)+ Spacer(minLength: 0)+ }+ .padding(.horizontal, 6)+ .frame(height: 28)+ .background(RoundedRectangle(cornerRadius: 6).fill(hoverURL ? Color.white.opacity(0.08) : .clear))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .onHover { hoverURL = $0 }+ .padding(.leading, 8)+ } else {+ HStack(spacing: 0) {+ ToolbarIcon(symbol: "arrow.left", fg: fgDim, enabled: false, width: 37, iconSize: 15) {}+ ToolbarIcon(symbol: "arrow.right", fg: fgDim, enabled: false, width: 37, iconSize: 15) {}+ ToolbarIcon(symbol: "arrow.clockwise", fg: fgDim, enabled: false, width: 37, iconSize: 15) {}+ }+ .padding(.leading, 1)+ Spacer()+ Button { actions.openCommandBar(.newTab) } label: {+ Text("Search or Enter URL…")+ .font(.system(size: 13))+ .foregroundStyle(palette.textTertiary)+ }+ .buttonStyle(.plain)+ Spacer()+ }+ if tab != nil && developerMode {+ Spacer(minLength: 8)+ ToolbarIcon(symbol: "link", fg: fgDim, help: "Copy URL (⇧⌘C)") { actions.performAction("copyURL") }+ toolbarDivider+ ToolbarIcon(symbol: "camera", fg: fgDim, help: "Capture page") { actions.performAction("capturePage") }+ toolbarDivider+ ToolbarIcon(symbol: "terminal", fg: fgDim, help: "Developer Tools (⌥⌘I)") { actions.performAction("devTools") }+ ToolbarIcon(symbol: "globe", fg: fgDim, help: "View Source (⌥⌘U)") { actions.performAction("viewSource") }+ toolbarDivider+ }+ ToolbarIcon(symbol: "sidebar.right", fg: fgDim, help: "Toggle Sidebar (⌘S)") { actions.toggleSidebar() }+ .padding(.trailing, 6)+ }+ .frame(height: CraMetrics.toolbarHeight)+ .background(onCard ? cardFill : (palette.isDark ? Color.white.opacity(0.025) : Color.black.opacity(0.03)))+ .overlay(alignment: .bottom) {+ if !onCard { Rectangle().fill(palette.isDark ? Color.white.opacity(0.07) : Color.black.opacity(0.07)).frame(height: 1) }+ }+ .ignoresSafeArea()+ }+}++private extension ContentToolbarView {+ var toolbarDivider: some View {+ Rectangle().fill(cardIsLight ? Color.black.opacity(0.15) : Color.white.opacity(0.22)).frame(width: 1, height: 14).padding(.horizontal, 5)+ }+}++struct ToolbarIcon: View {+ let symbol: String+ let fg: Color+ var help: String = ""+ var enabled: Bool = true+ var width: CGFloat = 26+ var iconSize: CGFloat = 13+ let action: () -> Void+ @State private var hover = false+ var body: some View {+ Button(action: action) {+ Image(systemName: symbol)+ .font(.system(size: iconSize, weight: .regular))+ .foregroundStyle(enabled ? fg : fg.opacity(0.4))+ .frame(width: width, height: 26)+ .background(RoundedRectangle(cornerRadius: 7).fill(hover && enabled ? Color.white.opacity(0.1) : .clear))+ }+ .buttonStyle(.plain)+ .disabled(!enabled)+ .onHover { hover = $0 }+ .help(help)+ }+}diff --git a/Sources/Cra/UI/Overlays.swift b/Sources/Cra/UI/Overlays.swiftnew file mode 100644index 0000000..30c1537--- /dev/null+++ b/Sources/Cra/UI/Overlays.swift@@ -0,0 +1,115 @@+import AppKit+import Observation+import SwiftUI++struct DownloadToast: Identifiable, Equatable {+ let id: UInt32+ var name: String+ var percent: Int+ var state: Int+ var path: String+}++/// Overlay state shown on top of the web content: link status, find bar,+/// download toasts.+@MainActor+@Observable+final class OverlayState {+ var status = ""+ var findVisible = false+ var findQuery = ""+ var findFocusToken = 0+ var toasts: [DownloadToast] = []+}++struct StatusBubble: View {+ let overlay: OverlayState+ var body: some View {+ if !overlay.status.isEmpty {+ Text(overlay.status)+ .font(.system(size: 11))+ .lineLimit(1)+ .truncationMode(.middle)+ .padding(.horizontal, 8)+ .padding(.vertical, 4)+ .background(.thinMaterial, in: RoundedRectangle(cornerRadius: 6, style: .continuous))+ .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(Color.primary.opacity(0.1)))+ .padding(6)+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)+ }+ }+}++struct FindBar: View {+ let overlay: OverlayState+ let onFind: (String, Bool, Bool) -> Void // query, forward, isNext+ let onClose: () -> Void+ @FocusState private var focused: Bool++ var body: some View {+ if overlay.findVisible {+ @Bindable var overlay = overlay+ HStack(spacing: 6) {+ Image(systemName: "magnifyingglass").foregroundStyle(.secondary)+ TextField("Find in page", text: $overlay.findQuery)+ .textFieldStyle(.plain)+ .frame(width: 180)+ .focused($focused)+ .onSubmit { onFind(overlay.findQuery, !(NSApp.currentEvent?.modifierFlags.contains(.shift) ?? false), true) }+ .onChange(of: overlay.findQuery) { _, q in onFind(q, true, false) }+ .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)+ Button { onClose() } label: { Image(systemName: "xmark") }.buttonStyle(.plain)+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 7)+ .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 }+ }+ }+}++struct ToastStack: View {+ let overlay: OverlayState+ var body: some View {+ VStack(alignment: .trailing, spacing: 6) {+ ForEach(overlay.toasts) { t in+ HStack(spacing: 10) {+ Image(systemName: t.state == 1 ? "checkmark.circle.fill" : (t.state == 0 ? "arrow.down.circle" : "exclamationmark.circle"))+ .foregroundStyle(t.state == 1 ? .green : .secondary)+ VStack(alignment: .leading, spacing: 2) {+ Text(t.name).font(.system(size: 12, weight: .medium)).lineLimit(1)+ if t.state == 0 {+ ProgressView(value: Double(max(0, t.percent)), total: 100).controlSize(.small)+ } else {+ Text(t.state == 1 ? "Downloaded" : (t.state == 2 ? "Cancelled" : "Failed")).font(.system(size: 11)).foregroundStyle(.secondary)+ }+ }+ if t.state == 1 {+ Button("Show") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: t.path)]) }+ .controlSize(.small)+ }+ }+ .padding(10)+ .frame(width: 300)+ .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: .bottomTrailing)+ }+}++/// Arc shows a faint, slightly lighter card over the gradient when no tab is selected.+struct EmptyContentView: View {+ let space: Space+ var body: some View {+ (space.theme.palette.isDark ? Color.white.opacity(0.04) : Color.black.opacity(0.03))+ }+}diff --git a/Sources/Cra/UI/ShellView.swift b/Sources/Cra/UI/ShellView.swiftnew file mode 100644index 0000000..3d46fe5--- /dev/null+++ b/Sources/Cra/UI/ShellView.swift@@ -0,0 +1,307 @@+import AppKit+import SwiftUI++/// The window's content view: gradient background, sidebar (anchored,+/// hidden, or floating over the content on hover), a resize handle, and the+/// content card: Arc's toolbar strip on top, the Chromium view below. With no+/// tab selected there is no card, just the toolbar on the gradient.+final class ShellView: NSView {+ /// Behind-window blur for vibrant (Arc-style) themes.+ let vibrancy = NSVisualEffectView()+ /// Lifts the dark blur toward Arc's mid-grey base before the gradient goes on.+ let vibrancyLift = NSView()+ let backgroundHost: NSHostingView<SpaceBackground>+ let sidebarHost: NSHostingView<AnyView>+ let resizeHandle = ResizeHandleView()+ /// The rounded card. Holds the toolbar and the web container.+ let contentContainer = NSView()+ let toolbarHost: NSHostingView<AnyView>+ /// Where Chromium views live (card minus toolbar, minus the DevTools pane).+ let webContainer = NSView()+ /// DevTools dock on the right of the page, like Chrome's default.+ let devToolsHost = NSView()+ let devToolsDivider = NSView()+ let devToolsHandle = DevToolsResizeHandle()+ var devToolsVisible = false { didSet { needsLayout = true } }+ var devToolsWidth: CGFloat = 460 { didSet { needsLayout = true } }+ /// Reports the dock area (window coordinates) so the DevTools child window follows it.+ var onDevToolsFrame: ((NSRect) -> Void)?+ /// Set while the sidebar/card frames are being animated; layout() then leaves them alone.+ private var animatingFrames = false+ /// While the sidebar animates, Chromium views are kept at their final size+ /// (Arc reflows the page once, not every frame).+ private var frozenWebBounds: NSRect?+ let placeholderHost: NSHostingView<AnyView>+ let statusHost: NSHostingView<AnyView>+ let toastHost: NSHostingView<AnyView>+ let findHost: NSHostingView<AnyView>++ var sidebarWidth: CGFloat = CraMetrics.sidebarDefaultWidth { didSet { needsLayout = true } }+ var sidebarVisible = true { didSet { needsLayout = true } }+ var floatingSidebar = false { didSet { needsLayout = true } }+ var contentFullscreen = false { didSet { needsLayout = true } }+ var showToolbar = true { didSet { needsLayout = true } }+ var hasTab = false { didSet { needsLayout = true } }+ var onEdgeHover: ((Bool) -> Void)?+ var windowActive = true {+ didSet { refreshLift() }+ }++ /// Dark vibrant themes keep the earlier calibration (underWindowBackground + 15% lift).+ var vibrantDark = false { didSet { refreshLift() } }++ func refreshLift() {+ let t = CraTuning.shared+ let lift = vibrantDark ? (windowActive ? 0.15 : 0.93) : (windowActive ? t.liftActive : t.liftInactive)+ vibrancyLift.layer?.backgroundColor = NSColor(white: 1, alpha: lift).cgColor+ vibrancy.material = vibrantDark ? .underWindowBackground : t.material+ vibrancy.state = (t.forceActiveBlur || windowActive) ? .active : .inactive+ vibrancy.appearance = NSAppearance(named: t.darkBlur ? .darkAqua : .aqua)+ }+ var statusVisible = false+ var findVisible = false+ var toastCount = 0+ private var trackingArea: NSTrackingArea?++ init(frame: NSRect, background: SpaceBackground, sidebar: AnyView, toolbar: AnyView, placeholder: AnyView, status: AnyView, toasts: AnyView, find: AnyView) {+ backgroundHost = NSHostingView(rootView: background)+ sidebarHost = NSHostingView(rootView: sidebar)+ toolbarHost = NSHostingView(rootView: toolbar)+ placeholderHost = NSHostingView(rootView: placeholder)+ statusHost = NSHostingView(rootView: status)+ toastHost = NSHostingView(rootView: toasts)+ findHost = NSHostingView(rootView: find)+ super.init(frame: frame)+ wantsLayer = true++ vibrancy.blendingMode = .behindWindow+ vibrancy.material = .underWindowBackground+ vibrancy.state = .active+ vibrancy.isHidden = true+ addSubview(vibrancy)+ vibrancyLift.wantsLayer = true+ vibrancyLift.layer?.backgroundColor = NSColor(white: 1, alpha: 0.15).cgColor+ vibrancyLift.isHidden = true+ addSubview(vibrancyLift)+ addSubview(backgroundHost)+ contentContainer.wantsLayer = true+ contentContainer.layer?.cornerRadius = CraMetrics.contentCornerRadius+ contentContainer.layer?.cornerCurve = .continuous+ contentContainer.layer?.masksToBounds = true+ contentContainer.layer?.backgroundColor = NSColor.clear.cgColor+ addSubview(contentContainer)+ toolbarHost.sizingOptions = []+ contentContainer.addSubview(toolbarHost)+ webContainer.wantsLayer = true+ webContainer.autoresizesSubviews = false+ contentContainer.addSubview(webContainer)+ devToolsHost.wantsLayer = true+ devToolsHost.layer?.backgroundColor = NSColor.white.cgColor+ devToolsHost.isHidden = true+ contentContainer.addSubview(devToolsHost)+ devToolsDivider.wantsLayer = true+ devToolsDivider.layer?.backgroundColor = NSColor.black.withAlphaComponent(0.12).cgColor+ devToolsDivider.isHidden = true+ contentContainer.addSubview(devToolsDivider)+ devToolsHandle.isHidden = true+ devToolsHandle.onDrag = { [weak self] dx in+ guard let self else { return }+ self.devToolsWidth = min(max(320, self.devToolsWidth - dx), self.contentContainer.bounds.width * 0.7)+ self.layoutSubtreeIfNeeded()+ }+ contentContainer.addSubview(devToolsHandle)+ webContainer.addSubview(placeholderHost)+ for h in [statusHost, toastHost, findHost] {+ h.sizingOptions = []+ h.isHidden = true+ webContainer.addSubview(h)+ }+ sidebarHost.sizingOptions = []+ sidebarHost.wantsLayer = true+ sidebarHost.layer?.cornerCurve = .continuous+ addSubview(sidebarHost)+ addSubview(resizeHandle)+ }++ required init?(coder: NSCoder) { fatalError() }++ override var isFlipped: Bool { false }++ override func updateTrackingAreas() {+ super.updateTrackingAreas()+ if let t = trackingArea { removeTrackingArea(t) }+ let t = NSTrackingArea(rect: bounds, options: [.mouseMoved, .mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect], owner: self, userInfo: nil)+ addTrackingArea(t)+ trackingArea = t+ }++ override func mouseMoved(with event: NSEvent) {+ super.mouseMoved(with: event)+ let p = convert(event.locationInWindow, from: nil)+ let overTitleRow = (sidebarVisible || floatingSidebar) && !contentFullscreen+ && p.x < sidebarWidth && p.y > bounds.height - CraMetrics.titleAreaHeight+ (window as? CraWindow)?.trafficLightsRevealed = overTitleRow+ guard !sidebarVisible, !contentFullscreen else { return }+ if !floatingSidebar, p.x <= 2 {+ onEdgeHover?(true)+ } else if floatingSidebar, p.x > sidebarWidth + 24 {+ onEdgeHover?(false)+ }+ }++ override func mouseExited(with event: NSEvent) {+ super.mouseExited(with: event)+ (window as? CraWindow)?.trafficLightsRevealed = false+ if floatingSidebar { onEdgeHover?(false) }+ }++ struct Frames {+ var sidebar: NSRect+ var handle: NSRect+ var content: NSRect+ var cornerRadius: CGFloat+ var sidebarCorner: CGFloat+ }++ func frames(sidebarVisible: Bool, floating: Bool, fullscreen: Bool, width: CGFloat) -> Frames {+ let b = bounds+ if fullscreen {+ return Frames(sidebar: NSRect(x: -width, y: 0, width: width, height: b.height),+ handle: .zero, content: b, cornerRadius: 0, sidebarCorner: 0)+ }+ if sidebarVisible {+ let inset = CraMetrics.contentInset+ let content = NSRect(x: width, y: inset, width: max(0, b.width - width - inset), height: max(0, b.height - 2 * inset))+ return Frames(sidebar: NSRect(x: 0, y: 0, width: width, height: b.height),+ handle: NSRect(x: width - 4, y: 0, width: 8, height: b.height),+ content: content, cornerRadius: CraMetrics.contentCornerRadius, sidebarCorner: 0)+ }+ if floating {+ let m: CGFloat = 8+ return Frames(sidebar: NSRect(x: m, y: m, width: width, height: b.height - 2 * m),+ handle: .zero, content: NSRect(x: 0, y: 0, width: b.width, height: b.height), cornerRadius: 0, sidebarCorner: 12)+ }+ return Frames(sidebar: NSRect(x: -width - 20, y: 0, width: width, height: b.height),+ handle: .zero, content: b, cornerRadius: 0, sidebarCorner: 0)+ }++ override func layout() {+ super.layout()+ vibrancy.frame = bounds+ vibrancyLift.frame = bounds+ backgroundHost.frame = bounds+ if animatingFrames { layoutContentChildren(); return }+ let f = frames(sidebarVisible: sidebarVisible, floating: floatingSidebar, fullscreen: contentFullscreen, width: sidebarWidth)+ apply(f)+ }++ func apply(_ f: Frames) {+ sidebarHost.frame = f.sidebar+ resizeHandle.frame = f.handle+ resizeHandle.isHidden = f.handle.isEmpty+ contentContainer.frame = f.content+ contentContainer.layer?.cornerRadius = f.cornerRadius+ sidebarHost.layer?.cornerRadius = f.sidebarCorner+ if f.sidebarCorner > 0 {+ sidebarHost.shadow = NSShadow()+ sidebarHost.shadow?.shadowBlurRadius = 24+ sidebarHost.shadow?.shadowOffset = NSSize(width: 0, height: -6)+ sidebarHost.shadow?.shadowColor = NSColor.black.withAlphaComponent(0.3)+ } else {+ sidebarHost.shadow = nil+ }+ layoutContentChildren()+ }++ func layoutContentChildren() {+ let cb = contentContainer.bounds+ let toolbarH: CGFloat = (showToolbar && !contentFullscreen) ? CraMetrics.toolbarHeight : 0+ toolbarHost.isHidden = toolbarH == 0+ toolbarHost.frame = NSRect(x: 0, y: cb.height - toolbarH, width: cb.width, height: toolbarH)+ let bodyH = max(0, cb.height - toolbarH)+ let showDev = devToolsVisible && cb.width > 640+ let devW: CGFloat = showDev ? min(max(320, devToolsWidth), cb.width * 0.7) : 0+ webContainer.frame = NSRect(x: 0, y: 0, width: cb.width - devW, height: bodyH)+ devToolsHost.isHidden = !showDev+ devToolsDivider.isHidden = !showDev+ devToolsHandle.isHidden = !showDev+ devToolsHost.frame = NSRect(x: cb.width - devW, y: 0, width: devW, height: bodyH)+ devToolsDivider.frame = NSRect(x: cb.width - devW, y: 0, width: 1, height: bodyH)+ devToolsHandle.frame = NSRect(x: cb.width - devW - 3, y: 0, width: 7, height: bodyH)+ for sub in devToolsHost.subviews { sub.frame = devToolsHost.bounds }+ if showDev { onDevToolsFrame?(contentContainer.convert(devToolsHost.frame, to: nil)) }+ // The white page card only exists while a tab is showing.+ contentContainer.layer?.backgroundColor = NSColor.clear.cgColor+ webContainer.layer?.backgroundColor = (hasTab ? NSColor.white : NSColor.clear).cgColor+ let wb = webContainer.bounds+ // Chromium views are added after the overlays; keep overlays on top.+ for h in [statusHost, toastHost, findHost] where webContainer.subviews.last !== h {+ webContainer.addSubview(h, positioned: .above, relativeTo: nil)+ }+ placeholderHost.frame = wb+ let chromiumBounds = frozenWebBounds ?? wb+ for sub in webContainer.subviews where sub !== placeholderHost && sub !== statusHost && sub !== toastHost && sub !== findHost {+ if sub.frame != chromiumBounds { sub.frame = chromiumBounds }+ }+ statusHost.isHidden = !statusVisible+ statusHost.frame = NSRect(x: 0, y: 0, width: min(540, wb.width), height: 34)+ toastHost.isHidden = toastCount == 0+ toastHost.frame = NSRect(x: wb.width - 330, y: 0, width: 330, height: CGFloat(toastCount) * 76 + 20)+ findHost.isHidden = !findVisible+ findHost.frame = NSRect(x: wb.width - 360, y: wb.height - 60, width: 360, height: 60)+ }++ /// Animate between sidebar states by interpolating frames.+ func animateSidebar(visible: Bool, floating: Bool, fullscreen: Bool, width: CGFloat, duration: TimeInterval = 0.22) {+ let target = frames(sidebarVisible: visible, floating: floating, fullscreen: fullscreen, width: width)+ // Size the page for its destination once, up front; the card then just slides over it.+ let toolbarH: CGFloat = (showToolbar && !fullscreen) ? CraMetrics.toolbarHeight : 0+ let devW: CGFloat = devToolsVisible && target.content.width > 640 ? min(max(320, devToolsWidth), target.content.width * 0.7) : 0+ frozenWebBounds = NSRect(x: 0, y: 0, width: target.content.width - devW, height: max(0, target.content.height - toolbarH))+ layoutContentChildren()+ animatingFrames = true+ NSAnimationContext.runAnimationGroup { ctx in+ ctx.duration = duration+ // Fast start, soft landing: feels immediate without a visible snap.+ ctx.timingFunction = CAMediaTimingFunction(controlPoints: 0.2, 0.85, 0.25, 1)+ ctx.allowsImplicitAnimation = true+ sidebarHost.animator().frame = target.sidebar+ contentContainer.animator().frame = target.content+ contentContainer.layer?.cornerRadius = target.cornerRadius+ } completionHandler: { [weak self] in+ guard let self else { return }+ self.animatingFrames = false+ self.frozenWebBounds = nil+ self.sidebarVisible = visible+ self.floatingSidebar = floating+ self.contentFullscreen = fullscreen+ self.needsLayout = true+ self.layoutSubtreeIfNeeded()+ }+ }+}++/// Thin vertical strip between sidebar and content that drags the width.+final class ResizeHandleView: NSView {+ var onDrag: ((CGFloat) -> Void)?+ var onEnd: (() -> Void)?+ private var lastX: CGFloat = 0++ override func resetCursorRects() { addCursorRect(bounds, cursor: .resizeLeftRight) }+ override func mouseDown(with event: NSEvent) { lastX = event.locationInWindow.x }+ override func mouseDragged(with event: NSEvent) {+ let x = event.locationInWindow.x+ onDrag?(x - lastX)+ lastX = x+ }+ override func mouseUp(with event: NSEvent) { onEnd?() }+}+++/// Thin vertical grab area on the DevTools divider.+final class DevToolsResizeHandle: NSView {+ var onDrag: ((CGFloat) -> Void)?+ override func resetCursorRects() { addCursorRect(bounds, cursor: .resizeLeftRight) }+ override func mouseDragged(with event: NSEvent) { onDrag?(event.deltaX) }+ override func hitTest(_ point: NSPoint) -> NSView? { bounds.contains(convert(point, from: superview)) ? self : nil }+}diff --git a/Sources/Cra/UI/Sidebar/FavoritesGrid.swift b/Sources/Cra/UI/Sidebar/FavoritesGrid.swiftnew file mode 100644index 0000000..19605a1--- /dev/null+++ b/Sources/Cra/UI/Sidebar/FavoritesGrid.swift@@ -0,0 +1,102 @@+import SwiftUI++/// Arc's "top apps": a 4-wide grid of favorite tiles shared by every space.+struct FavoritesGrid: View {+ let palette: SpacePalette+ @Environment(SidebarStore.self) private var store+ @Environment(SidebarUIState.self) private var ui+ @Environment(\.sidebarActions) private var actions+ @State private var targeted = false++ private let columns = Array(repeating: GridItem(.flexible(), spacing: 8), count: 4)++ var body: some View {+ let favorites = store.tabs(under: store.favoritesContainerID)+ VStack(spacing: 0) {+ if !favorites.isEmpty {+ LazyVGrid(columns: columns, spacing: 8) {+ ForEach(favorites) { item in FavoriteCell(item: item, palette: palette) }+ }+ }+ RoundedRectangle(cornerRadius: 10, style: .continuous)+ .strokeBorder(palette.textTertiary.opacity(targeted ? 0.6 : 0), style: StrokeStyle(lineWidth: 1, dash: [4, 3]))+ .background(RoundedRectangle(cornerRadius: 10).fill(targeted ? palette.hoverFill : .clear))+ .frame(height: targeted ? 36 : (favorites.isEmpty ? 8 : 6))+ .overlay {+ if targeted { Text("Add to Favorites").font(.system(size: 11, weight: .medium)).foregroundStyle(palette.textSecondary) }+ }+ .padding(.top, favorites.isEmpty ? 0 : 4)+ .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)+ return true+ } isTargeted: { targeted = $0 }+ }+ }+}++/// Arc's keyboard-focus ring: 2pt systemYellow with black 6/6 dashes, inside the edge.+struct FocusRing: View {+ let radius: CGFloat+ var body: some View {+ ZStack {+ RoundedRectangle(cornerRadius: radius, style: .continuous)+ .strokeBorder(Color(red: 1, green: 0.8, blue: 0), lineWidth: 2)+ RoundedRectangle(cornerRadius: radius, style: .continuous)+ .strokeBorder(Color.black.opacity(0.92), style: StrokeStyle(lineWidth: 2, dash: [6, 6]))+ }+ .allowsHitTesting(false)+ }+}++struct FavoriteCell: View {+ let item: SidebarItem+ let palette: SpacePalette+ @Environment(SidebarStore.self) private var store+ @Environment(SidebarUIState.self) private var ui+ @Environment(\.sidebarActions) private var actions+ @State private var hover = false+ @State private var targeted = false++ private var selected: Bool { store.selectedTabID == item.id }++ var body: some View {+ ZStack {+ RoundedRectangle(cornerRadius: 10, style: .continuous)+ .fill(selected ? palette.selectedFill : (hover || targeted ? palette.hoverFill : palette.pillFill))+ if ui.keyboardFocusID == item.id { FocusRing(radius: 10) }+ FaviconView(key: item.tab?.faviconKey, palette: palette, size: 20)+ if item.isUnread && !selected {+ Circle().fill(palette.textPrimary.opacity(0.6)).frame(width: 6, height: 6)+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing)+ .padding(5)+ }+ }+ .frame(height: 47)+ .contentShape(RoundedRectangle(cornerRadius: 10))+ .onHover { hover = $0 }+ .onTapGesture { ui.keyboardFocusID = nil; store.selectTab(item.id) }+ .help(item.displayTitle)+ .draggable(SidebarDragItem(id: item.id))+ .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))+ return true+ } isTargeted: { targeted = $0 }+ .contextMenu {+ Button("Remove from Favorites") { store.removeFromFavorites(item.id) }+ Button("Rename…") { ui.renamingID = item.id }+ Button("Copy Link") {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(item.tab?.url ?? "", forType: .string)+ }+ if let t = item.tab, t.url != t.savedURL { Button("Back to Pinned Page") { actions.resetPinnedTab(item.id) } }+ Button("Make This the Pinned Page") { store.setPinnedHomeToCurrent(item.id) }+ Divider()+ Button("Close") { actions.closeTab(item.id) }+ Button("Archive") { store.archiveTab(item.id, reason: .manual) }+ }+ }+}diff --git a/Sources/Cra/UI/Sidebar/SidebarItemView.swift b/Sources/Cra/UI/Sidebar/SidebarItemView.swiftnew file mode 100644index 0000000..b0c3be6--- /dev/null+++ b/Sources/Cra/UI/Sidebar/SidebarItemView.swift@@ -0,0 +1,298 @@+import SwiftUI++enum SidebarSection { case favorites, pinned, today }++/// A tab or a folder (with its children when expanded).+struct SidebarItemView: View {+ let item: SidebarItem+ let depth: Int+ let palette: SpacePalette+ let section: SidebarSection+ @Environment(SidebarStore.self) private var store++ var body: some View {+ if item.isFolder {+ FolderRow(item: item, depth: depth, palette: palette)+ if store.isExpanded(item.id) {+ ForEach(store.children(of: item.id)) { child in+ SidebarItemView(item: child, depth: depth + 1, palette: palette, section: section)+ .transition(.asymmetric(insertion: .opacity.combined(with: .offset(y: -6)), removal: .opacity))+ }+ }+ } else if item.isTab {+ TabRow(item: item, depth: depth, palette: palette, section: section)+ }+ }+}++struct FaviconView: View {+ let key: String?+ let palette: SpacePalette+ var size: CGFloat = CraMetrics.favicon+ @Environment(FaviconCache.self) private var favicons++ var body: some View {+ if let img = favicons.image(forKey: key) {+ Image(nsImage: img)+ .resizable()+ .interpolation(.high)+ .aspectRatio(contentMode: .fit)+ .frame(width: size, height: size)+ .clipShape(RoundedRectangle(cornerRadius: size * 0.22, style: .continuous))+ } else {+ Image(systemName: "globe")+ .font(.system(size: size * 0.8, weight: .regular))+ .foregroundStyle(palette.textTertiary)+ .frame(width: size, height: size)+ }+ }+}++struct TabRow: View {+ let item: SidebarItem+ let depth: Int+ let palette: SpacePalette+ let section: SidebarSection+ @Environment(SidebarStore.self) private var store+ @Environment(SidebarUIState.self) private var ui+ @Environment(\.sidebarActions) private var actions+ @State private var hover = false+ @State private var draft = ""+ @State private var dropAfter: Bool?+ @FocusState private var renameFocused: Bool++ private var tab: TabData { item.tab! }+ private var selected: Bool { store.selectedTabID == item.id }+ private var editing: Bool { ui.renamingID == item.id }+ private var loaded: Bool { ui.loadedTabIDs.contains(item.id) }+ private var pinned: Bool { section != .today }+ private var navigatedAway: Bool { pinned && tab.url != tab.savedURL && !tab.savedURL.isEmpty }+ /// Arc shows the host under a pinned tab only when it has left the pinned+ /// site (navigating within the same host shows nothing).+ private var subtitle: String? {+ guard navigatedAway, let host = URL(string: tab.url)?.host, let saved = URL(string: tab.savedURL)?.host,+ host.replacingOccurrences(of: "www.", with: "") != saved.replacingOccurrences(of: "www.", with: "") else { return nil }+ return host.replacingOccurrences(of: "www.", with: "")+ }++ var body: some View {+ HStack(spacing: 11) {+ FaviconView(key: tab.faviconKey, palette: palette)+ .frame(width: CraMetrics.favicon)+ if editing {+ TextField("", text: $draft)+ .textFieldStyle(.plain)+ .font(.system(size: 14))+ .focused($renameFocused)+ .onSubmit { commitRename() }+ .onExitCommand { ui.renamingID = nil }+ .onAppear { draft = item.title ?? item.displayTitle; renameFocused = true }+ .onChange(of: renameFocused) { _, f in if !f && editing { commitRename() } }+ } else {+ VStack(alignment: .leading, spacing: 1) {+ Text(item.displayTitle)+ .font(.system(size: 14))+ .foregroundStyle(palette.textPrimary)+ .lineLimit(1)+ .truncationMode(.tail)+ if let subtitle {+ Text(subtitle).font(.system(size: 11)).foregroundStyle(palette.textTertiary).lineLimit(1)+ }+ }+ }+ Spacer(minLength: 4)+ if tab.muted {+ Image(systemName: "speaker.slash.fill").font(.system(size: 10)).foregroundStyle(palette.textTertiary)+ }+ if item.isUnread && !selected && !hover {+ Circle().fill(palette.textPrimary.opacity(0.55)).frame(width: 6, height: 6)+ }+ if hover && !editing {+ if navigatedAway {+ SidebarIconButton(symbol: "arrow.uturn.backward", palette: palette, help: "Back to pinned page", size: 22) {+ actions.resetPinnedTab(item.id)+ }+ }+ SidebarIconButton(symbol: "xmark", palette: palette, help: pinned ? "Close (keeps the pinned tab)" : "Archive (⌘W)", size: 22) {+ actions.closeTab(item.id)+ }+ }+ }+ .padding(.leading, 8 + CGFloat(depth) * CraMetrics.indent)+ .padding(.trailing, 6)+ .frame(height: CraMetrics.rowHeight)+ .background(+ RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous)+ .fill(selected ? palette.selectedFill : (hover ? palette.hoverFill : .clear))+ .shadow(color: selected && !palette.isDark ? .black.opacity(0.06) : .clear, radius: 3, y: 1)+ )+ .overlay { if ui.keyboardFocusID == item.id { FocusRing(radius: CraMetrics.rowCorner) } }+ .overlay(alignment: .top) { if dropAfter == false { dropLine } }+ .overlay(alignment: .bottom) { if dropAfter == true { dropLine } }+ .contentShape(Rectangle())+ .onHover { hover = $0 }+ .onTapGesture(count: 2) { ui.renamingID = item.id }+ .onTapGesture { if !editing { ui.keyboardFocusID = nil; store.selectTab(item.id) } }+ .draggable(SidebarDragItem(id: item.id)) {+ HStack(spacing: 8) {+ FaviconView(key: tab.faviconKey, palette: palette)+ Text(item.displayTitle).font(.system(size: 14)).lineLimit(1)+ }+ .padding(8)+ .background(RoundedRectangle(cornerRadius: 8).fill(.regularMaterial))+ }+ .dropDestination(for: SidebarDragItem.self) { items, location in+ guard let d = items.first, d.id != item.id, let parent = item.parentID,+ let idx = store.item(parent)?.children.firstIndex(of: item.id) else { return false }+ let after = location.y > CraMetrics.rowHeight / 2+ store.moveItem(d.id, to: parent, index: idx + (after ? 1 : 0))+ return true+ } isTargeted: { targeted in dropAfter = targeted ? true : nil }+ .contextMenu { contextMenu }+ .help(tab.url)+ }++ private var dropLine: some View {+ Rectangle().fill(palette.textPrimary.opacity(0.5)).frame(height: 2).padding(.horizontal, 6)+ }++ private func commitRename() {+ guard editing else { return }+ store.rename(item.id, to: draft)+ ui.renamingID = nil+ }++ @ViewBuilder+ private var contextMenu: some View {+ if pinned {+ Button("Unpin Tab") { store.unpinTab(item.id) }+ } else {+ Button("Pin Tab") { store.pinTab(item.id) }+ }+ if store.isFavorite(item.id) {+ Button("Remove from Favorites") { store.removeFromFavorites(item.id) }+ } else {+ Button("Add to Favorites") { store.addToFavorites(item.id) }+ }+ Divider()+ Button("Rename…") { ui.renamingID = item.id }+ if item.title != nil { Button("Use Page Title") { store.rename(item.id, to: nil) } }+ Button("Duplicate") { store.duplicateTab(item.id) }+ Button("Copy Link") {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(tab.url, forType: .string)+ }+ Button(tab.muted ? "Unmute" : "Mute") { store.setMuted(item.id, !tab.muted); actions.performAction("muteTab:\(item.id)") }+ if pinned {+ Divider()+ if navigatedAway { Button("Back to Pinned Page") { actions.resetPinnedTab(item.id) } }+ Button("Make This the Pinned Page") { store.setPinnedHomeToCurrent(item.id) }+ }+ Divider()+ Menu("Move to Space") {+ ForEach(store.orderedSpaces) { s in+ Button("\(s.emoji) \(s.title)") { store.moveTab(item.id, toSpace: s.id) }+ .disabled(s.id == store.spaceID(ofItem: item.id))+ }+ }+ let folders = store.children(of: store.focusedSpace.pinnedContainerID).filter { $0.isFolder }+ if !folders.isEmpty {+ Menu("Move to Folder") {+ ForEach(folders) { f in+ Button(f.title ?? "Folder") { store.moveItem(item.id, to: f.id, index: nil) }+ .disabled(f.id == item.parentID)+ }+ }+ }+ Button("New Folder with Tab") {+ let f = store.createFolder(named: "New Folder", in: store.focusedSpace.pinnedContainerID, index: 0)+ store.moveItem(item.id, to: f.id, index: nil)+ ui.renamingID = f.id+ }+ Divider()+ Button(pinned ? "Close" : "Archive") { actions.closeTab(item.id) }+ if pinned { Button("Unpin and Archive") { store.archiveTab(item.id, reason: .manual) } }+ }+}++struct FolderRow: View {+ let item: SidebarItem+ let depth: Int+ let palette: SpacePalette+ @Environment(SidebarStore.self) private var store+ @Environment(SidebarUIState.self) private var ui+ @State private var hover = false+ @State private var draft = ""+ @State private var targeted = false+ @FocusState private var renameFocused: Bool++ private var expanded: Bool { store.isExpanded(item.id) }+ private var editing: Bool { ui.renamingID == item.id }++ var body: some View {+ HStack(spacing: 11) {+ Image(systemName: expanded ? "folder" : "folder.fill")+ .font(.system(size: 15, weight: .regular))+ .foregroundStyle(palette.folderTint)+ .frame(width: CraMetrics.favicon)+ if editing {+ TextField("", text: $draft)+ .textFieldStyle(.plain)+ .font(.system(size: 14, weight: .medium))+ .focused($renameFocused)+ .onSubmit { commitRename() }+ .onExitCommand { ui.renamingID = nil }+ .onAppear { draft = item.title ?? ""; renameFocused = true }+ .onChange(of: renameFocused) { _, f in if !f && editing { commitRename() } }+ } else {+ Text(item.title ?? "Folder")+ .font(.system(size: 14, weight: .medium))+ .lineLimit(1)+ }+ Spacer()+ if hover && !expanded {+ Text("\(store.tabs(under: item.id).count)")+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(palette.textTertiary)+ .padding(.trailing, 8)+ }+ }+ .padding(.leading, 8 + CGFloat(depth) * CraMetrics.indent)+ .frame(height: CraMetrics.rowHeight)+ .background(RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous).fill(targeted ? palette.selectedFill : (hover ? palette.hoverFill : .clear)))+ .contentShape(Rectangle())+ .onHover { hover = $0 }+ .onTapGesture(count: 2) { ui.renamingID = item.id }+ .onTapGesture { if !editing { withAnimation(.snappy(duration: 0.22, extraBounce: 0)) { store.setExpanded(item.id, !expanded) } } }+ .draggable(SidebarDragItem(id: item.id))+ .dropDestination(for: SidebarDragItem.self) { items, location in+ guard let d = items.first, d.id != item.id else { return false }+ let h = CraMetrics.rowHeight+ if location.y < h * 0.25, let parent = item.parentID, let idx = store.item(parent)?.children.firstIndex(of: item.id) {+ store.moveItem(d.id, to: parent, index: idx)+ } else if location.y > h * 0.75, let parent = item.parentID, let idx = store.item(parent)?.children.firstIndex(of: item.id) {+ store.moveItem(d.id, to: parent, index: idx + 1)+ } else {+ store.moveItem(d.id, to: item.id, index: nil)+ store.setExpanded(item.id, true)+ }+ return true+ } isTargeted: { targeted = $0 }+ .contextMenu {+ Button("Rename…") { ui.renamingID = item.id }+ Button("New Folder Inside") {+ let f = store.createFolder(named: "New Folder", in: item.id, index: 0)+ store.setExpanded(item.id, true)+ ui.renamingID = f.id+ }+ Divider()+ Button("Delete Folder (archives tabs)") { store.deleteFolder(item.id) }+ }+ }++ private func commitRename() {+ guard editing else { return }+ store.rename(item.id, to: draft.isEmpty ? "Folder" : draft)+ ui.renamingID = nil+ }+}diff --git a/Sources/Cra/UI/Sidebar/SidebarRootView.swift b/Sources/Cra/UI/Sidebar/SidebarRootView.swiftnew file mode 100644index 0000000..63673ad--- /dev/null+++ b/Sources/Cra/UI/Sidebar/SidebarRootView.swift@@ -0,0 +1,290 @@+import SwiftUI++/// The whole left column, laid out like Arc: traffic lights + sidebar toggle,+/// nav buttons at the right of the top row, favorites, muted space header,+/// pinned, divider, today, new tab, and the dock at the bottom.+struct SidebarRootView: View {+ @Environment(SidebarStore.self) private var store+ @Environment(SidebarUIState.self) private var ui+ @Environment(\.sidebarActions) private var actions+ @State private var switchDirection: Edge = .trailing+ @State private var lastSpaceIndex = 0++ var body: some View {+ let space = store.focusedSpace+ let palette = space.theme.palette+ VStack(spacing: 0) {+ SidebarTopBar(palette: palette)+ ScrollView(.vertical, showsIndicators: false) {+ VStack(alignment: .leading, spacing: 0) {+ FavoritesGrid(palette: palette)+ .padding(.horizontal, 8)+ SpaceSectionView(space: space, palette: palette)+ .id(space.id)+ .transition(.asymmetric(insertion: .move(edge: switchDirection).combined(with: .opacity),+ removal: .move(edge: switchDirection == .trailing ? .leading : .trailing).combined(with: .opacity)))+ }+ .padding(.bottom, 12)+ }+ .clipped()+ SpaceDock(palette: palette)+ .padding(.horizontal, 10)+ .padding(.bottom, 6)+ }+ .foregroundStyle(palette.textPrimary)+ .ignoresSafeArea()+ .onChange(of: store.focusedSpaceID) { _, new in+ let idx = store.spaceOrder.firstIndex(of: new) ?? 0+ switchDirection = idx >= lastSpaceIndex ? .trailing : .leading+ lastSpaceIndex = idx+ }+ .animation(.snappy(duration: 0.24, extraBounce: 0), value: store.focusedSpaceID)+ .onAppear { lastSpaceIndex = store.spaceOrder.firstIndex(of: store.focusedSpaceID) ?? 0 }+ }+}++/// Row 1: traffic lights, the sidebar toggle right after them, nav buttons+/// right-aligned (Arc puts them here when the toolbar shows the URL). When the+/// toolbar is hidden the URL pill moves into the sidebar on a second row.+struct SidebarTopBar: View {+ let palette: SpacePalette+ @Environment(SidebarStore.self) private var store+ @Environment(SidebarUIState.self) private var ui+ @Environment(\.sidebarActions) private var actions+ @State private var hoverPill = false++ var body: some View {+ VStack(spacing: 4) {+ HStack(spacing: 2) {+ Spacer().frame(width: 72)+ SidebarIconButton(symbol: "sidebar.left", palette: palette, help: "Hide Sidebar (⌘S)", iconSize: 15.5) { actions.toggleSidebar() }+ Spacer()+ if store.settings.showToolbar, let t = store.selectedTab?.tab, store.settings.isDeveloperMode(url: t.url) {+ navButtons+ }+ }+ .frame(height: 28)+ .padding(.top, CraMetrics.titleRowCenter - 14)+ .padding(.bottom, CraMetrics.titleAreaHeight - CraMetrics.titleRowCenter - 14)+ .padding(.horizontal, 6)+ if !store.settings.showToolbar {+ HStack(spacing: 2) {+ navButtons+ urlPill+ }+ .padding(.horizontal, 8)+ .padding(.bottom, 4)+ }+ }+ }++ private var navButtons: some View {+ HStack(spacing: 0) {+ SidebarIconButton(symbol: "arrow.left", palette: palette, help: "Go Back (⌘[)", enabled: ui.canGoBack, size: 34, iconSize: 15, weight: .regular) { actions.goBack() }+ SidebarIconButton(symbol: "arrow.right", palette: palette, help: "Go Forward (⌘])", enabled: ui.canGoForward, size: 34, iconSize: 15, weight: .regular) { actions.goForward() }+ SidebarIconButton(symbol: ui.isLoading ? "xmark" : "arrow.clockwise", palette: palette, help: "Refresh (⌘R)", size: 24, iconSize: 15, weight: .regular) { actions.reload() }+ Menu {+ Button("Refresh the Page") { actions.performAction("reload") }+ Button("Force Refresh the Page") { actions.performAction("hardReload") }+ Divider()+ Button("View Source") { actions.performAction("viewSource") }+ Button("Developer Tools") { actions.performAction("devTools") }+ } label: {+ Image(systemName: "chevron.down")+ .font(.system(size: 8, weight: .bold))+ .foregroundStyle(palette.textTertiary)+ .frame(width: 12, height: 28)+ .contentShape(Rectangle())+ }+ .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden)+ .frame(width: 12)+ }+ }++ private var urlPill: some View {+ let tab = store.selectedTab+ let url = tab?.tab?.url ?? ""+ let host = URL(string: url)?.host ?? ""+ let secure = url.hasPrefix("https://")+ return Button {+ actions.openCommandBar(tab == nil ? .newTab : .editURL)+ } label: {+ HStack(spacing: 6) {+ if tab != nil {+ Image(systemName: secure ? "lock.fill" : "globe").font(.system(size: 10, weight: .semibold)).foregroundStyle(palette.textSecondary)+ }+ Text(tab == nil ? "Search or Enter URL…" : (host.isEmpty ? SuggestionEngine.humanURL(url) : host.replacingOccurrences(of: "www.", with: "")))+ .font(.system(size: 12.5, weight: .medium))+ .foregroundStyle(tab == nil ? palette.textTertiary : palette.textPrimary)+ .lineLimit(1).truncationMode(.middle)+ Spacer(minLength: 0)+ }+ .padding(.horizontal, 10)+ .frame(height: 30)+ .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(hoverPill ? palette.selectedFill : palette.pillFill))+ }+ .buttonStyle(.plain)+ .onHover { hoverPill = $0 }+ .help(url)+ }+}++struct SidebarIconButton: View {+ let symbol: String+ let palette: SpacePalette+ var help: String = ""+ var enabled: Bool = true+ var size: CGFloat = 28+ var iconSize: CGFloat = 13+ var weight: Font.Weight = .medium+ let action: () -> Void+ @State private var hover = false++ var body: some View {+ Button(action: action) {+ Image(systemName: symbol)+ .font(.system(size: iconSize, weight: weight))+ .foregroundStyle(enabled ? palette.textSecondary : palette.textTertiary.opacity(0.55))+ .frame(width: size, height: min(size, 28))+ .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(hover && enabled ? palette.hoverFill : .clear))+ }+ .buttonStyle(.plain)+ .disabled(!enabled)+ .onHover { hover = $0 }+ .help(help)+ }+}++/// Space header, pinned (folders allowed), divider, today, new-tab row.+struct SpaceSectionView: View {+ let space: Space+ let palette: SpacePalette+ @Environment(SidebarStore.self) private var store+ @Environment(SidebarUIState.self) private var ui+ @Environment(\.sidebarActions) private var actions+ @State private var hoverDivider = false+ @State private var dropOnPinned = false+ @State private var dropOnToday = false++ var body: some View {+ let todayItems = store.children(of: space.todayContainerID)+ VStack(alignment: .leading, spacing: 0) {+ SpaceHeader(space: space, palette: palette)+ .padding(.horizontal, 10)+ Rectangle().fill(palette.separator.opacity(0.35)).frame(height: 1).padding(.bottom, 5)++ VStack(spacing: CraMetrics.rowSpacing) {+ ForEach(store.children(of: space.pinnedContainerID)) { item in+ SidebarItemView(item: item, depth: 0, palette: palette, section: .pinned)+ }+ }+ .padding(.horizontal, 10)+ .frame(minHeight: 8)+ .background(RoundedRectangle(cornerRadius: 10).fill(dropOnPinned ? palette.hoverFill : .clear).padding(.horizontal, 8))+ .dropDestination(for: SidebarDragItem.self) { items, _ in+ guard let d = items.first else { return false }+ store.moveItem(d.id, to: space.pinnedContainerID, index: nil)+ return true+ } isTargeted: { dropOnPinned = $0 }++ // Divider between pinned and today; "Clear" shows on hover.+ HStack {+ Rectangle().fill(palette.separator).frame(height: 1)+ .opacity(todayItems.isEmpty ? 0 : 1)+ if hoverDivider && !todayItems.isEmpty {+ Button("Clear") { store.clearToday(space.id) }+ .buttonStyle(.plain)+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(palette.textSecondary)+ .transition(.opacity)+ }+ }+ .frame(height: 18)+ .padding(.horizontal, 20)+ .contentShape(Rectangle())+ .onHover { hoverDivider = $0 }+ .animation(.easeOut(duration: 0.15), value: hoverDivider)++ VStack(spacing: CraMetrics.rowSpacing) {+ ForEach(todayItems) { item in+ SidebarItemView(item: item, depth: 0, palette: palette, section: .today)+ }+ NewTabRow(palette: palette)+ }+ .padding(.horizontal, 10)+ .background(RoundedRectangle(cornerRadius: 10).fill(dropOnToday ? palette.hoverFill : .clear).padding(.horizontal, 8))+ .dropDestination(for: SidebarDragItem.self) { items, _ in+ guard let d = items.first else { return false }+ store.moveItem(d.id, to: space.todayContainerID, index: nil)+ return true+ } isTargeted: { dropOnToday = $0 }+ }+ }+}++struct SpaceHeader: View {+ let space: Space+ let palette: SpacePalette+ @Environment(SidebarStore.self) private var store+ @Environment(\.sidebarActions) private var actions+ @State private var hover = false++ var body: some View {+ Menu {+ Button("Edit Space…") { actions.editSpace(space) }+ Button("New Folder") { actions.performAction("newFolder") }+ Divider()+ Button("Clear Today") { store.clearToday(space.id) }+ Divider()+ Button("New Space…") { actions.editSpace(nil) }+ Button("Delete Space…") { actions.performAction("deleteSpace") }+ } label: {+ HStack(spacing: 8) {+ Text(space.emoji).font(.system(size: 12))+ Text(space.title)+ .font(.system(size: 14, weight: .medium))+ .foregroundStyle(palette.textSecondary)+ .lineLimit(1)+ Image(systemName: "chevron.down")+ .font(.system(size: 8, weight: .bold))+ .foregroundStyle(palette.textTertiary)+ .opacity(hover ? 1 : 0)+ Spacer()+ }+ .padding(.horizontal, 7)+ .frame(height: 31)+ .background(RoundedRectangle(cornerRadius: 8).fill(hover ? palette.hoverFill : .clear))+ .contentShape(Rectangle())+ }+ .menuStyle(.button)+ .buttonStyle(.plain)+ .menuIndicator(.hidden)+ .onHover { hover = $0 }+ }+}++struct NewTabRow: View {+ let palette: SpacePalette+ @Environment(\.sidebarActions) private var actions+ @State private var hover = false+ var body: some View {+ Button { actions.openCommandBar(.newTab) } label: {+ HStack(spacing: 9) {+ Image(systemName: "plus")+ .font(.system(size: 13, weight: .medium))+ .frame(width: CraMetrics.favicon)+ Text("New Tab")+ .font(.system(size: 14))+ Spacer()+ }+ .foregroundStyle(hover ? palette.textPrimary : palette.textSecondary)+ .padding(.leading, 8)+ .padding(.trailing, 10)+ .frame(height: CraMetrics.rowHeight)+ .background(RoundedRectangle(cornerRadius: CraMetrics.rowCorner, style: .continuous).fill(hover ? palette.selectedFill : .clear))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .onHover { hover = $0 }+ }+}diff --git a/Sources/Cra/UI/Sidebar/SpaceDock.swift b/Sources/Cra/UI/Sidebar/SpaceDock.swiftnew file mode 100644index 0000000..b0f1d3f--- /dev/null+++ b/Sources/Cra/UI/Sidebar/SpaceDock.swift@@ -0,0 +1,60 @@+import SwiftUI++/// Bottom row like Arc's: library/archive at the left, tiny space icons in+/// the middle (inactive ones dimmed), "+" at the right.+struct SpaceDock: View {+ let palette: SpacePalette+ @Environment(SidebarStore.self) private var store+ @Environment(\.sidebarActions) private var actions++ var body: some View {+ HStack(spacing: 0) {+ SidebarIconButton(symbol: "archivebox", palette: palette, help: "Library (⇧⌘L)") { actions.showArchive() }+ Spacer(minLength: 0)+ HStack(spacing: 6) {+ ForEach(store.orderedSpaces) { space in+ SpaceDockButton(space: space, palette: palette, selected: space.id == store.focusedSpaceID)+ }+ }+ Spacer(minLength: 0)+ SidebarIconButton(symbol: "plus", palette: palette, help: "New Space") { actions.editSpace(nil) }+ }+ .frame(height: 36)+ }+}++struct SpaceDockButton: View {+ let space: Space+ let palette: SpacePalette+ let selected: Bool+ @Environment(SidebarStore.self) private var store+ @Environment(\.sidebarActions) private var actions+ @State private var hover = false+ @State private var targeted = false++ var body: some View {+ Text(space.emoji)+ .font(.system(size: 13))+ .frame(width: 26, height: 26)+ .opacity(selected || hover ? 1 : 0.45)+ .saturation(selected || hover ? 1 : 0.2)+ .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(targeted ? palette.hoverFill : .clear))+ .contentShape(Rectangle())+ .onHover { hover = $0 }+ .onTapGesture { store.focusSpace(space.id) }+ .help(space.title)+ .dropDestination(for: SidebarDragItem.self) { items, _ in+ guard let d = items.first else { return false }+ store.moveTab(d.id, toSpace: space.id)+ return true+ } isTargeted: { targeted = $0 }+ .contextMenu {+ Button("Edit Space…") { actions.editSpace(space) }+ Divider()+ Button("Move Left") { if let i = store.spaceOrder.firstIndex(of: space.id) { store.moveSpace(space.id, to: max(0, i - 1)) } }+ Button("Move Right") { if let i = store.spaceOrder.firstIndex(of: space.id) { store.moveSpace(space.id, to: i + 1) } }+ Divider()+ Button("Delete Space…") { store.focusSpace(space.id); actions.performAction("deleteSpace") }+ }+ }+}diff --git a/Sources/Cra/UI/SidebarUIState.swift b/Sources/Cra/UI/SidebarUIState.swiftnew file mode 100644index 0000000..45f841e--- /dev/null+++ b/Sources/Cra/UI/SidebarUIState.swift@@ -0,0 +1,63 @@+import AppKit+import Observation+import SwiftUI+import UniformTypeIdentifiers++/// Transient sidebar UI state shared between AppKit and SwiftUI.+@MainActor+@Observable+final class SidebarUIState {+ var renamingID: UUID?+ var draggingID: UUID?+ var hoveredTabID: UUID?+ /// Loading progress per tab (0...1), fed by the browser manager.+ var progress: [UUID: Double] = [:]+ var loadedTabIDs: Set<UUID> = []+ var canGoBack = false+ var canGoForward = false+ var isLoading = false+ var isCompact = false+ /// Page theme colour of the visible tab ("#RRGGBB" or "").+ var pageThemeColor = ""+ /// Tab chosen from the keyboard; Arc draws its yellow/black dashed ring+ /// around it until the mouse picks another tab.+ var keyboardFocusID: UUID?+}++/// Things the sidebar needs AppKit to do.+@MainActor+final class SidebarActions {+ var openCommandBar: (CommandBarMode) -> Void = { _ in }+ var closeTab: (UUID) -> Void = { _ in }+ var goBack: () -> Void = {}+ var goForward: () -> Void = {}+ var reload: () -> Void = {}+ var editSpace: (Space?) -> Void = { _ in }+ var toggleSidebar: () -> Void = {}+ var showArchive: () -> Void = {}+ var resetPinnedTab: (UUID) -> Void = { _ in }+ var openURL: (String) -> Void = { _ in }+ var performAction: (String) -> Void = { _ in }+}++private struct SidebarActionsKey: EnvironmentKey {+ @MainActor static var defaultValue: SidebarActions { SidebarActions() }+}++extension EnvironmentValues {+ var sidebarActions: SidebarActions {+ get { self[SidebarActionsKey.self] }+ set { self[SidebarActionsKey.self] = newValue }+ }+}++extension UTType {+ static let craSidebarItem = UTType(exportedAs: "dk.kildahl.cra.sidebar-item")+}++struct SidebarDragItem: Codable, Transferable {+ let id: UUID+ static var transferRepresentation: some TransferRepresentation {+ CodableRepresentation(contentType: .craSidebarItem)+ }+}diff --git a/Sources/Cra/UI/Theme.swift b/Sources/Cra/UI/Theme.swiftnew file mode 100644index 0000000..424e0f6--- /dev/null+++ b/Sources/Cra/UI/Theme.swift@@ -0,0 +1,208 @@+import AppKit+import AppKit+import SwiftUI++extension Color {+ init(hex: String) {+ let c = HexColor.components(hex) ?? (0.5, 0.5, 0.5)+ self.init(.sRGB, red: c.r, green: c.g, blue: c.b, opacity: 1)+ }+}++extension NSColor {+ convenience init(hex: String) {+ let c = HexColor.components(hex) ?? (0.5, 0.5, 0.5)+ self.init(srgbRed: c.r, green: c.g, blue: c.b, alpha: 1)+ }+}++/// Colors derived from a space theme, the way Arc derives a+/// semanticColorPalette from the window theme.+struct SpacePalette {+ let isDark: Bool+ let gradientColors: [Color]+ let textPrimary: Color+ let textSecondary: Color+ let textTertiary: Color+ let hoverFill: Color+ let selectedFill: Color+ let separator: Color+ let pillFill: Color+ let toolbarFill: Color+ let folderTint: Color+ /// Selected row in the command bar (Arc tints it with the space color).+ let commandHighlight: Color+ let noise: Double+ /// Opacity of the gradient over the blurred desktop at the top and bottom+ /// stops (1 when not vibrant). Arc's light themes get more opaque downwards.+ let gradientAlpha: Double+ let gradientAlphaBottom: Double+ let vibrant: Bool++ var gradient: LinearGradient {+ LinearGradient(colors: gradientColors, startPoint: .top, endPoint: .bottom)+ }+}++extension SpaceTheme {+ private static func mix(_ hex: String, towardWhite: Bool, amount: Double) -> Color {+ let c = HexColor.components(hex) ?? (0.5, 0.5, 0.5)+ let target = towardWhite ? 1.0 : 0.0+ let a = max(0, min(1, amount))+ return Color(.sRGB, red: c.r + (target - c.r) * a, green: c.g + (target - c.g) * a, blue: c.b + (target - c.b) * a, opacity: 1)+ }++ /// Arc's toolbar band: the first theme colour pushed to a dark, fully+ /// saturated shade on light themes (Victor: #72601D) and a muted,+ /// slightly darker one on dark themes (JYSK: #0E0B16).+ static func hsb(_ r: Double, _ g: Double, _ b: Double) -> (h: Double, s: Double, v: Double) {+ let mx = max(r, g, b), mn = min(r, g, b), d = mx - mn+ var h = 0.0+ if d > 0.00001 {+ if mx == r { h = ((g - b) / d).truncatingRemainder(dividingBy: 6) }+ else if mx == g { h = (b - r) / d + 2 }+ else { h = (r - g) / d + 4 }+ h /= 6+ if h < 0 { h += 1 }+ }+ return (h, mx > 0 ? d / mx : 0, mx)+ }++ static func rgb(h: Double, s: Double, v: Double) -> (Double, Double, Double) {+ let i = floor(h * 6), f = h * 6 - i+ let p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s)+ switch Int(i) % 6 {+ case 0: return (v, t, p)+ case 1: return (q, v, p)+ case 2: return (p, v, t)+ case 3: return (p, q, v)+ case 4: return (t, p, v)+ default: return (v, p, q)+ }+ }++ /// Light: 46% brightness, saturation +0.10 (Victor #F8D558 → #725F1D, Arc #72601D).+ /// Dark: 60% saturation, 80% brightness (JYSK #010220 → #0A0B19, Arc #0E0B16).+ static func toolbarColor(_ hex: String, dark: Bool) -> Color {+ let c = HexColor.components(hex) ?? (0.5, 0.5, 0.5)+ var (h, s, v) = hsb(c.r, c.g, c.b)+ if dark { s *= 0.6; v *= 0.8 } else { s = min(1, s + 0.10); v *= 0.46 }+ let o = rgb(h: h, s: s, v: v)+ return Color(.sRGB, red: o.0, green: o.1, blue: o.2, opacity: 1)+ }++ var palette: SpacePalette {+ let dark = isDark+ let base = colors.isEmpty ? ["#DDDDDD"] : colors+ // Vibrant (Arc): raw colors at `intensity` opacity over the blur.+ // Opaque: intensity 1 = the raw colors; lower pulls toward white/black.+ let pull = vibrant ? 0 : (1 - intensity) * (dark ? 0.35 : 0.6)+ var stops = base.map { SpaceTheme.mix($0, towardWhite: !dark, amount: pull) }+ if stops.count == 1 { stops.append(SpaceTheme.mix(base[0], towardWhite: !dark, amount: pull + 0.15)) }+ let accent = SpaceTheme.mix(base[0], towardWhite: dark, amount: dark ? 0.25 : -0.0)+ return SpacePalette(+ isDark: dark,+ gradientColors: stops,+ textPrimary: dark ? .white.opacity(0.92) : .black.opacity(0.9),+ textSecondary: dark ? .white.opacity(0.6) : .black.opacity(0.58),+ textTertiary: dark ? .white.opacity(0.38) : .black.opacity(0.38),+ hoverFill: dark ? .white.opacity(0.07) : .white.opacity(0.38),+ selectedFill: dark ? .white.opacity(0.13) : .white.opacity(0.74),+ separator: dark ? .white.opacity(0.12) : .black.opacity(0.09),+ pillFill: dark ? .white.opacity(0.08) : .black.opacity(0.07),+ // Arc: the toolbar is the first theme color at ~46% (dark) / lightened a touch (dark themes).+ toolbarFill: SpaceTheme.toolbarColor(self.accent ?? base[0], dark: dark),+ folderTint: dark ? Color(hex: "#6B9CFF") : Color(hex: "#3B7CF6"),+ commandHighlight: dark ? accent.opacity(0.55) : SpaceTheme.mix(base[0], towardWhite: false, amount: 0.45).opacity(0.75),+ noise: noise,+ // Calibrated against Arc's rendering of a 0.25-intensity vibrant theme.+ // Fitted to Arc's Victor theme (intensity 0.25) over white and black+ // backdrops: light vibrant themes run 0.45 → 0.59 over a HUD blur+ // (which passes ~55% of the backdrop and adds ~30/255 grey).+ gradientAlpha: vibrant ? (dark ? max(0.35, min(0.9, intensity * 2.2)) : min(0.95, intensity * 1.8)) : 1,+ gradientAlphaBottom: vibrant ? (dark ? max(0.35, min(0.9, intensity * 2.2)) : min(0.95, intensity * 2.33)) : 1,+ vibrant: vibrant+ )+ }+}++extension Color {+ /// Mix toward another color in sRGB (amount 0...1).+ func blendedToward(_ other: Color, _ amount: Double) -> Color {+ guard amount > 0 else { return self }+ let a = NSColor(self).usingColorSpace(.sRGB) ?? .gray+ let b = NSColor(other).usingColorSpace(.sRGB) ?? .gray+ let t = max(0, min(1, amount))+ return Color(.sRGB, red: Double(a.redComponent + (b.redComponent - a.redComponent) * t),+ green: Double(a.greenComponent + (b.greenComponent - a.greenComponent) * t),+ blue: Double(a.blueComponent + (b.blueComponent - a.blueComponent) * t), opacity: 1)+ }+}++/// A tiny tiled grain texture, like Arc's "grain" overlay modifier.+enum NoiseTexture {+ static let image: NSImage = {+ let size = 96+ let img = NSImage(size: NSSize(width: size, height: size))+ img.lockFocus()+ var rng = SystemRandomNumberGenerator()+ for y in 0..<size {+ for x in 0..<size {+ let v = Double.random(in: 0...1, using: &rng)+ NSColor(white: v, alpha: 1).setFill()+ NSRect(x: x, y: y, width: 1, height: 1).fill()+ }+ }+ img.unlockFocus()+ return img+ }()+}++struct NoiseOverlay: View {+ let amount: Double+ let isDark: Bool+ var body: some View {+ Image(nsImage: NoiseTexture.image)+ .resizable(resizingMode: .tile)+ .opacity(amount * (isDark ? 0.1 : 0.09))+ .blendMode(isDark ? .screen : .multiply)+ .allowsHitTesting(false)+ }+}++struct SpaceBackground: View {+ let palette: SpacePalette+ var body: some View {+ let scale = palette.vibrant ? CraTuning.shared.gradientAlphaScale : 1+ let n = palette.gradientColors.count+ let stops = palette.gradientColors.enumerated().map { i, c -> Gradient.Stop in+ let t = n > 1 ? Double(i) / Double(n - 1) : 0+ let a = (palette.gradientAlpha + (palette.gradientAlphaBottom - palette.gradientAlpha) * t) * scale+ return Gradient.Stop(color: c.opacity(min(1, a)), location: t)+ }+ ZStack {+ LinearGradient(stops: stops, startPoint: .top, endPoint: .bottom)+ NoiseOverlay(amount: palette.noise, isDark: palette.isDark)+ }+ .ignoresSafeArea()+ }+}++/// Layout constants measured from Arc 1.168 at 2x (see docs).+enum CraMetrics {+ static let sidebarMinWidth: CGFloat = 220+ static let sidebarMaxWidth: CGFloat = 520+ static let sidebarDefaultWidth: CGFloat = 328+ static let rowHeight: CGFloat = 40+ static let rowSpacing: CGFloat = 1+ static let rowCorner: CGFloat = 10+ static let favicon: CGFloat = 16+ static let indent: CGFloat = 18+ static let contentInset: CGFloat = 9+ static let contentCornerRadius: CGFloat = 10+ static let toolbarHeight: CGFloat = 40+ /// Traffic lights, sidebar toggle and nav buttons share this centre line.+ static let titleRowCenter: CGFloat = 24+ static let titleAreaHeight: CGFloat = 44+ static let commandBarWidth: CGFloat = 766+}diff --git a/Sources/Cra/UI/Tuning.swift b/Sources/Cra/UI/Tuning.swiftnew file mode 100644index 0000000..a64d9a5--- /dev/null+++ b/Sources/Cra/UI/Tuning.swift@@ -0,0 +1,30 @@+import AppKit+import Observation++/// Rendering constants calibrated against Arc. They can be changed at run time+/// for calibration with `cra://debug?lift=0.15&liftInactive=0.93&alpha=1&toolbar=0.4&material=21`.+@MainActor @Observable+final class CraTuning {+ static let shared = CraTuning()++ /// White layer over the behind-window blur (active / inactive window).+ var liftActive: Double = 0.0+ var liftInactive: Double = 0.75+ /// Multiplier on the theme's gradient opacity (vibrant themes only).+ var gradientAlphaScale: Double = 1+ /// Black overlay that makes the toolbar band out of the space background.+ var toolbarAlpha: Double = 0.40+ var material: NSVisualEffectView.Material = .hudWindow+ var forceActiveBlur = false+ var darkBlur = true++ func apply(_ q: [String: String]) {+ if let v = q["lift"].flatMap(Double.init) { liftActive = v }+ if let v = q["liftInactive"].flatMap(Double.init) { liftInactive = v }+ if let v = q["alpha"].flatMap(Double.init) { gradientAlphaScale = v }+ if let v = q["toolbar"].flatMap(Double.init) { toolbarAlpha = v }+ if let v = q["material"].flatMap(Int.init), let m = NSVisualEffectView.Material(rawValue: v) { material = m }+ if let v = q["state"] { forceActiveBlur = v == "active" }+ if let v = q["appearance"] { darkBlur = v != "light" }+ }+}diff --git a/Sources/Cra/UI/Windows/AccountView.swift b/Sources/Cra/UI/Windows/AccountView.swiftnew file mode 100644index 0000000..2364dc9--- /dev/null+++ b/Sources/Cra/UI/Windows/AccountView.swift@@ -0,0 +1,117 @@+import SwiftUI++/// Sign in / create account / Google, and the signed-in card with backups.+struct AccountView: View {+ @Environment(AccountStore.self) private var account+ @Environment(SidebarStore.self) private var store+ let onGoogle: () -> Void+ let onRestore: (SidebarDocument) -> Void+ @State private var email = ""+ @State private var password = ""+ @State private var name = ""+ @State private var creating = false+ @State private var restoreCandidate: String?++ var body: some View {+ VStack(alignment: .leading, spacing: 14) {+ if let user = account.user {+ HStack(spacing: 12) {+ avatar(user)+ VStack(alignment: .leading, spacing: 2) {+ Text(user.name ?? user.email).font(.system(size: 15, weight: .semibold))+ Text(user.email).font(.system(size: 12)).foregroundStyle(.secondary)+ Text(user.authProvider == "google" ? "Google account" : "Email account").font(.system(size: 11)).foregroundStyle(.tertiary)+ }+ Spacer()+ Button("Sign Out") { Task { await account.signOut() } }+ }+ Divider()+ HStack {+ Text("Sidebar backups").font(.system(size: 13, weight: .semibold))+ Spacer()+ Button("Back Up Now") {+ Task { await account.backupSidebar(store.document, tabCount: store.allTabs().count) }+ }+ }+ if account.backups.isEmpty {+ Text("No backups yet. Settings sync automatically; the sidebar is backed up every 10 minutes while signed in.")+ .font(.system(size: 12)).foregroundStyle(.secondary)+ } else {+ ForEach(account.backups, id: \.device) { b in+ HStack {+ VStack(alignment: .leading, spacing: 1) {+ Text(b.device + (b.device == AccountStore.deviceID ? " (this Mac)" : "")).font(.system(size: 13))+ Text("\(b.tabCount) tabs · \(b.updatedAt.formatted(date: .abbreviated, time: .shortened))").font(.system(size: 11)).foregroundStyle(.secondary)+ }+ Spacer()+ Button("Restore…") { restoreCandidate = b.device }+ }+ }+ }+ } else {+ HStack(spacing: 10) {+ BrandMark(size: 32)+ Text(creating ? "Create your Cra account" : "Sign in to Cra").font(.system(size: 15, weight: .semibold))+ }+ Text("Syncs your settings and keeps a backup of your sidebar.").font(.system(size: 12)).foregroundStyle(.secondary)+ if creating {+ TextField("Name", text: $name).textFieldStyle(.roundedBorder)+ }+ TextField("Email", text: $email).textFieldStyle(.roundedBorder).textContentType(.username)+ SecureField("Password", text: $password).textFieldStyle(.roundedBorder).textContentType(.password)+ .onSubmit { submit() }+ if let err = account.lastError { Text(err).font(.system(size: 12)).foregroundStyle(.red) }+ HStack {+ Button(creating ? "Already have an account" : "Create an account") { creating.toggle(); account.lastError = nil }+ .buttonStyle(.link).font(.system(size: 12))+ Spacer()+ if account.isBusy { ProgressView().controlSize(.small) }+ Button(creating ? "Create Account" : "Sign In") { submit() }+ .keyboardShortcut(.defaultAction)+ .disabled(email.isEmpty || password.isEmpty || account.isBusy)+ }+ if account.googleConfigured {+ Divider()+ Button { onGoogle() } label: {+ HStack { Image(systemName: "g.circle.fill"); Text("Continue with Google") }.frame(maxWidth: .infinity)+ }+ }+ }+ }+ .padding(20)+ .frame(width: 420)+ .task { await account.refreshBackups(); await account.refreshGoogleConfig() }+ .alert("Replace your sidebar?", isPresented: Binding(get: { restoreCandidate != nil }, set: { if !$0 { restoreCandidate = nil } })) {+ Button("Restore", role: .destructive) {+ guard let device = restoreCandidate else { return }+ Task {+ if let doc = await account.fetchBackup(device: device) { onRestore(doc) }+ restoreCandidate = nil+ }+ }+ Button("Cancel", role: .cancel) { restoreCandidate = nil }+ } message: {+ Text("Spaces, pinned tabs and folders on this Mac will be replaced by the backup. The archive is kept.")+ }+ }++ private func submit() {+ Task {+ if creating { await account.signUp(email: email, password: password, name: name) }+ else { await account.signIn(email: email, password: password) }+ }+ }++ @ViewBuilder private func avatar(_ user: AccountUser) -> some View {+ if let s = user.profileImageUrl, let url = URL(string: s) {+ AsyncImage(url: url) { img in img.resizable() } placeholder: { Color.secondary.opacity(0.2) }+ .frame(width: 40, height: 40).clipShape(Circle())+ } else {+ Text(String((user.name ?? user.email).prefix(1)).uppercased())+ .font(.system(size: 16, weight: .semibold))+ .frame(width: 40, height: 40)+ .background(Circle().fill(Color(hex: "#6944AE")))+ .foregroundStyle(.white)+ }+ }+}diff --git a/Sources/Cra/UI/Windows/ArchiveView.swift b/Sources/Cra/UI/Windows/ArchiveView.swiftnew file mode 100644index 0000000..4dbaf6a--- /dev/null+++ b/Sources/Cra/UI/Windows/ArchiveView.swift@@ -0,0 +1,98 @@+import SwiftUI++/// Searchable list of archived tabs grouped by day (Arc: Archive / ⌘Y).+struct ArchiveView: View {+ let onRestore: (UUID) -> Void+ @Environment(SidebarStore.self) private var store+ @Environment(FaviconCache.self) private var favicons+ @State private var query = ""++ private var filtered: [ArchivedItem] {+ let q = query.lowercased().trimmingCharacters(in: .whitespaces)+ if q.isEmpty { return store.archive }+ return store.archive.filter {+ $0.item.displayTitle.lowercased().contains(q) || ($0.item.tab?.url.lowercased().contains(q) ?? false)+ }+ }++ private var grouped: [(String, [ArchivedItem])] {+ let cal = Calendar.current+ let df = DateFormatter()+ df.dateStyle = .medium+ var order: [String] = []+ var groups: [String: [ArchivedItem]] = [:]+ for e in filtered {+ let label = cal.isDateInToday(e.archivedAt) ? "Today" : (cal.isDateInYesterday(e.archivedAt) ? "Yesterday" : df.string(from: e.archivedAt))+ if groups[label] == nil { order.append(label) }+ groups[label, default: []].append(e)+ }+ return order.map { ($0, groups[$0]!) }+ }++ var body: some View {+ VStack(spacing: 0) {+ HStack {+ Image(systemName: "magnifyingglass").foregroundStyle(.secondary)+ TextField("Search archived tabs", text: $query).textFieldStyle(.plain)+ Spacer()+ Text("\(store.archive.count) tabs").foregroundStyle(.secondary).font(.system(size: 12))+ Button("Clear Archive") { store.clearArchive() }.disabled(store.archive.isEmpty)+ }+ .padding(12)+ Divider()+ if filtered.isEmpty {+ Spacer()+ Text(store.archive.isEmpty ? "Tabs you close end up here." : "No matches.").foregroundStyle(.secondary)+ Spacer()+ } else {+ List {+ ForEach(grouped, id: \.0) { label, items in+ Section(label) {+ ForEach(items) { e in+ ArchiveRow(entry: e)+ .contentShape(Rectangle())+ .onTapGesture { onRestore(e.id) }+ .contextMenu {+ Button("Restore") { onRestore(e.id) }+ Button("Copy Link") {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(e.item.tab?.url ?? "", forType: .string)+ }+ Divider()+ Button("Remove from Archive") { store.removeFromArchive(e.id) }+ }+ }+ }+ }+ }+ .listStyle(.inset)+ }+ }+ }+}++private struct ArchiveRow: View {+ let entry: ArchivedItem+ @Environment(SidebarStore.self) private var store+ @Environment(FaviconCache.self) private var favicons+ var body: some View {+ HStack(spacing: 10) {+ if let img = favicons.image(forKey: entry.item.tab?.faviconKey) {+ Image(nsImage: img).resizable().frame(width: 16, height: 16).clipShape(RoundedRectangle(cornerRadius: 3))+ } else {+ Image(systemName: "globe").foregroundStyle(.secondary).frame(width: 16)+ }+ VStack(alignment: .leading, spacing: 1) {+ Text(entry.item.displayTitle).lineLimit(1)+ Text(SuggestionEngine.humanURL(entry.item.tab?.url ?? "")).font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1)+ }+ Spacer()+ if let sid = entry.sourceSpaceID, let s = store.space(sid) {+ Text("\(s.emoji) \(s.title)").font(.system(size: 11)).foregroundStyle(.secondary)+ }+ Text(entry.reason == .auto ? "auto" : "").font(.system(size: 10)).foregroundStyle(.tertiary)+ Text(entry.archivedAt, style: .time).font(.system(size: 11)).foregroundStyle(.tertiary)+ }+ .padding(.vertical, 2)+ }+}diff --git a/Sources/Cra/UI/Windows/ImportView.swift b/Sources/Cra/UI/Windows/ImportView.swiftnew file mode 100644index 0000000..ef1bd3e--- /dev/null+++ b/Sources/Cra/UI/Windows/ImportView.swift@@ -0,0 +1,83 @@+import SwiftUI++/// Import spaces, pinned tabs, folders, favorites, archive and settings from+/// Arc or Dia. Shown from Settings and on first launch when either exists.+struct ImportView: View {+ let onDone: () -> Void+ @Environment(SidebarStore.self) private var store+ @Environment(FaviconCache.self) private var favicons+ @State private var source = ArcImporter.isAvailable ? "Arc" : "Dia"+ @State private var plan: ImportPlan?+ @State private var error: String?+ @State private var includeArchive = true+ @State private var includeSettings = true+ @State private var result: SidebarStore.ImportResult?+ @State private var working = false++ var body: some View {+ VStack(alignment: .leading, spacing: 16) {+ Text("Import").font(.system(size: 17, weight: .semibold))+ Picker("From", selection: $source) {+ if ArcImporter.isAvailable { Text("Arc").tag("Arc") }+ if DiaImporter.isAvailable { Text("Dia").tag("Dia") }+ }+ .pickerStyle(.segmented)+ .onChange(of: source) { _, _ in load() }++ if let plan {+ VStack(alignment: .leading, spacing: 6) {+ Label("\(plan.spaces.count) spaces: \(plan.spaces.map { "\($0.emoji) \($0.title)" }.joined(separator: ", "))", systemImage: "square.grid.2x2")+ Label("\(plan.tabCount) tabs, \(plan.folderCount) folders, \(plan.favorites.count) favorites", systemImage: "pin")+ Label("\(plan.archive.count) archived tabs", systemImage: "archivebox")+ if plan.settings.autoArchive != nil || plan.settings.sidebarWidth != nil {+ Label("Settings: auto-archive \(plan.settings.autoArchive?.label ?? "–"), sidebar width \(Int(plan.settings.sidebarWidth ?? 0))", systemImage: "gear")+ }+ }+ .font(.system(size: 13))+ Toggle("Include archived tabs", isOn: $includeArchive)+ Toggle("Include settings", isOn: $includeSettings)+ Text("Spaces with the same name are merged. Tabs already in a section are skipped.")+ .font(.system(size: 11)).foregroundStyle(.secondary)+ } else if let error {+ Text(error).foregroundStyle(.red)+ } else {+ ProgressView().controlSize(.small)+ }++ if let result {+ Text("Imported \(result.spaces) new spaces, \(result.tabs) tabs, \(result.folders) folders and \(result.archived) archived tabs.")+ .font(.system(size: 13, weight: .medium)).foregroundStyle(.green)+ }++ HStack {+ Button(result == nil ? "Not Now" : "Done") { onDone() }.keyboardShortcut(.cancelAction)+ Spacer()+ if result == nil {+ Button("Import") {+ guard let plan else { return }+ working = true+ result = store.apply(plan, includeArchive: includeArchive, includeSettings: includeSettings)+ favicons.reset()+ working = false+ }+ .keyboardShortcut(.defaultAction)+ .disabled(plan == nil || working)+ }+ }+ }+ .padding(20)+ .frame(width: 460)+ .onAppear { load() }+ }++ private func load() {+ plan = nil+ error = nil+ result = nil+ do {+ plan = try (source == "Arc" ? ArcImporter.plan() : DiaImporter.plan())+ } catch {+ self.error = error.localizedDescription+ }+ }+}diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swiftnew file mode 100644index 0000000..a34cc64--- /dev/null+++ b/Sources/Cra/UI/Windows/MainWindowController.swift@@ -0,0 +1,701 @@+import AppKit+import CraCEF+import SwiftUI++@MainActor+final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserManagerDelegate {+ unowned let app: AppDelegate+ var store: SidebarStore { app.store }+ let sidebarUI = SidebarUIState()+ let sidebarActions = SidebarActions()+ let overlay = OverlayState()+ let commandBar: CommandBarController+ private(set) var browsers: BrowserManager!+ private(set) var shell: ShellView!+ private var commandPanel: CommandBarPanel!+ private var commandHost: NSHostingView<AnyView>!+ private var spaceEditor: NSWindow?+ private var importPanel: NSWindow?+ private var scrollMonitor: Any?+ private var swipeX: CGFloat = 0+ private var swipeY: CGFloat = 0+ private var swipeFired = false+ private var enteredFullscreenForContent = false+ private var lastSidebarVisible = true+ private var lastSidebarWidth: CGFloat = 0+ private var commandBarOpenedAt = Date.distantPast+ private var commandObserving = false++ var currentBrowser: CraBrowser? { browsers.visibleRuntime?.browser }++ init(app: AppDelegate) {+ self.app = app+ commandBar = CommandBarController(engine: app.engine, store: app.store)+ let frame = app.store.prefs.windowFrame.map { NSRectFromString($0) } ?? NSRect(x: 0, y: 0, width: 1400, height: 880)+ let window = CraWindow(contentRect: frame,+ styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],+ backing: .buffered, defer: false)+ super.init(window: window)+ window.delegate = self+ window.titlebarAppearsTransparent = true+ window.titleVisibility = .hidden+ window.isMovableByWindowBackground = true+ window.minSize = NSSize(width: 640, height: 420)+ window.isReleasedWhenClosed = false+ window.tabbingMode = .disallowed+ window.title = "Cra"+ if app.store.prefs.windowFrame == nil { window.center() }++ let store = app.store+ let palette = store.focusedSpace.theme.palette+ let env: (AnyView) -> AnyView = { v in+ AnyView(v.environment(store).environment(self.sidebarUI).environment(app.favicons).environment(\.sidebarActions, self.sidebarActions))+ }+ shell = ShellView(frame: window.contentView!.bounds,+ background: SpaceBackground(palette: palette),+ sidebar: env(AnyView(SidebarRootView())),+ toolbar: env(AnyView(ContentToolbarView(palette: palette))),+ 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) },+ onClose: { [weak self] in self?.hideFindBar() })))+ shell.sidebarWidth = CGFloat(store.prefs.sidebarWidth)+ shell.sidebarVisible = store.prefs.sidebarVisible+ shell.showToolbar = store.settings.showToolbar+ lastSidebarVisible = store.prefs.sidebarVisible+ lastSidebarWidth = CGFloat(store.prefs.sidebarWidth)+ window.contentView = shell+ window.backgroundColor = NSColor(palette.gradientColors.first ?? .gray)++ browsers = BrowserManager(store: store, favicons: app.favicons, container: shell.webContainer)+ browsers.delegate = self++ commandPanel = CommandBarPanel()+ commandHost = NSHostingView(rootView: AnyView(CommandBarView(controller: commandBar).environment(app.favicons)))+ commandPanel.contentView = commandHost+ commandPanel.delegate = self++ wireActions()+ shell.resizeHandle.onDrag = { [weak self] dx in+ guard let self else { return }+ let w = min(max(CraMetrics.sidebarMinWidth, shell.sidebarWidth + dx), CraMetrics.sidebarMaxWidth)+ shell.sidebarWidth = w+ shell.layoutSubtreeIfNeeded()+ }+ shell.resizeHandle.onEnd = { [weak self] in+ guard let self else { return }+ store.prefs.sidebarWidth = Double(shell.sidebarWidth)+ lastSidebarWidth = shell.sidebarWidth+ }+ shell.onEdgeHover = { [weak self] show in self?.setFloatingSidebar(show) }++ installSwipeMonitor()+ observeStore()+ refresh()+ shell.onDevToolsFrame = { [weak self] rect in self?.positionDevToolsWindow(rect) }+ NotificationCenter.default.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in+ Task { @MainActor in self?.shell.windowActive = true }+ }+ NotificationCenter.default.addObserver(forName: NSApplication.didResignActiveNotification, object: nil, queue: .main) { [weak self] _ in+ Task { @MainActor in self?.shell.windowActive = false }+ }+ }++ required init?(coder: NSCoder) { fatalError() }++ // MARK: Wiring++ private func wireActions() {+ sidebarActions.openCommandBar = { [weak self] mode in self?.openCommandBar(mode) }+ sidebarActions.closeTab = { [weak self] id in self?.closeTab(id) }+ sidebarActions.goBack = { [weak self] in self?.currentBrowser?.goBack() }+ sidebarActions.goForward = { [weak self] in self?.currentBrowser?.goForward() }+ sidebarActions.reload = { [weak self] in+ guard let b = self?.currentBrowser else { return }+ b.isLoading ? b.stopLoading() : b.reload()+ }+ sidebarActions.editSpace = { [weak self] s in self?.showSpaceEditor(space: s) }+ sidebarActions.toggleSidebar = { [weak self] in self?.toggleSidebar() }+ sidebarActions.showArchive = { [weak self] in self?.app.showArchiveWindow() }+ sidebarActions.resetPinnedTab = { [weak self] id in self?.resetPinnedTab(id) }+ sidebarActions.openURL = { [weak self] url in self?.store.createTab(url: url) }+ sidebarActions.performAction = { [weak self] id in+ if id.hasPrefix("muteTab:"), let uuid = UUID(uuidString: String(id.dropFirst(8))) {+ let muted = self?.store.item(uuid)?.tab?.muted ?? false+ self?.browsers.runtime(for: uuid)?.browser.setAudioMuted(muted)+ } else {+ self?.app.perform(id)+ }+ }+ commandBar.onCommit = { [weak self] s, typed, mode, force in self?.handleCommit(s, typed: typed, mode: mode, forceNewTab: force) }+ commandBar.onClose = { [weak self] in self?.hideCommandPanel() }+ commandBar.spaceName = { [weak self] id in self?.store.space(id)?.title ?? "" }+ }++ // MARK: Observation++ private func observeStore() {+ withObservationTracking {+ _ = store.revision+ _ = store.prefs+ _ = store.settings+ _ = store.spaces+ } onChange: { [weak self] in+ Task { @MainActor in+ self?.refresh()+ self?.observeStore()+ }+ }+ }++ func refresh() {+ let space = store.focusedSpace+ let palette = space.theme.palette+ shell.backgroundHost.rootView = SpaceBackground(palette: palette)+ shell.toolbarHost.rootView = AnyView(ContentToolbarView(palette: palette)+ .environment(store).environment(sidebarUI).environment(app.favicons).environment(\.sidebarActions, sidebarActions))+ shell.placeholderHost.rootView = AnyView(EmptyContentView(space: space))+ window?.appearance = NSAppearance(named: palette.isDark ? .darkAqua : .aqua)+ // Vibrant themes see through to the desktop like Arc; others are opaque.+ shell.vibrancy.isHidden = !palette.vibrant+ shell.vibrancyLift.isHidden = !palette.vibrant+ shell.vibrantDark = palette.isDark+ shell.refreshLift()+ window?.isOpaque = !palette.vibrant+ window?.backgroundColor = palette.vibrant ? .clear : NSColor(palette.gradientColors.first ?? .gray)++ browsers.pruneMissingTabs()+ let selected = store.selectedTabID+ if selected != browsers.visibleTabID || (selected != nil && browsers.runtime(for: selected!) == nil) {+ browsers.show(selected, focus: !commandBar.isOpen)+ }+ shell.hasTab = selected != nil+ shell.showToolbar = store.settings.showToolbar+ shell.placeholderHost.isHidden = selected != nil+ shell.layoutContentChildren()+ syncSidebarUI()+ window?.title = store.selectedTab?.displayTitle ?? space.title++ if store.prefs.sidebarVisible != lastSidebarVisible {+ lastSidebarVisible = store.prefs.sidebarVisible+ shell.animateSidebar(visible: lastSidebarVisible, floating: false, fullscreen: shell.contentFullscreen, width: shell.sidebarWidth)+ }+ if CGFloat(store.prefs.sidebarWidth) != lastSidebarWidth {+ lastSidebarWidth = CGFloat(store.prefs.sidebarWidth)+ shell.sidebarWidth = lastSidebarWidth+ }+ }++ private func syncSidebarUI() {+ sidebarUI.loadedTabIDs = Set(browsers.runtimes.keys)+ let b = browsers.visibleRuntime?.browser+ sidebarUI.canGoBack = b?.canGoBack ?? false+ sidebarUI.canGoForward = b?.canGoForward ?? false+ sidebarUI.isLoading = b?.isLoading ?? false+ sidebarUI.pageThemeColor = browsers.visibleRuntime?.themeColor ?? ""+ for (id, rt) in browsers.runtimes { sidebarUI.progress[id] = rt.progress }+ }++ // MARK: BrowserManagerDelegate++ func browserManagerDidUpdate(_ tabID: UUID) {+ syncSidebarUI()+ if tabID == browsers.visibleTabID { window?.title = store.item(tabID)?.displayTitle ?? "Cra" }+ }++ func browserManager(statusMessage: String) {+ overlay.status = statusMessage+ shell.statusVisible = !statusMessage.isEmpty+ shell.layoutContentChildren()+ }++ 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+ shell.layoutContentChildren()+ if download.state != .inProgress {+ let id = toast.id+ DispatchQueue.main.asyncAfter(deadline: .now() + 8) { [weak self] in+ guard let self else { return }+ self.overlay.toasts.removeAll { $0.id == id }+ self.shell.toastCount = self.overlay.toasts.count+ self.shell.layoutContentChildren()+ }+ }+ }++ func browserManager(fullscreen: Bool, tabID: UUID) {+ guard let window else { return }+ shell.contentFullscreen = fullscreen+ if fullscreen, !window.styleMask.contains(.fullScreen) {+ enteredFullscreenForContent = true+ window.toggleFullScreen(nil)+ } else if !fullscreen, enteredFullscreenForContent, window.styleMask.contains(.fullScreen) {+ enteredFullscreenForContent = false+ window.toggleFullScreen(nil)+ }+ }++ /// CEF owns the DevTools window (embedding in our NSView trips a Chromium CHECK on macOS).+ /// DevTools docks inside the content card (Chrome's default), to the right of the page.+ func browserManagerDevToolsHost(for tabID: UUID) -> NSView? {+ shell.devToolsVisible = true+ shell.needsLayout = true+ shell.layoutSubtreeIfNeeded()+ return shell.devToolsHost+ }++ /// Docks the visible tab's DevTools window (CEF-owned, borderless) over the+ /// dock area as a child window; other tabs' DevTools windows are hidden.+ func browserManagerDevToolsChanged() {+ guard let window else { return }+ let visible = browsers.visibleDevToolsWindow+ for (_, view) in browsers.devToolsViews {+ if let w = view.window, w !== visible { w.orderOut(nil) }+ }+ shell.devToolsVisible = visible != nil+ shell.needsLayout = true+ shell.layoutSubtreeIfNeeded()+ guard let w = visible else { return }+ if w.parent !== window {+ // CEF made a normal titled window; strip its chrome so only the DevTools content shows.+ w.styleMask.insert(.fullSizeContentView)+ w.styleMask.remove([.closable, .miniaturizable])+ w.titlebarAppearsTransparent = true+ w.titleVisibility = .hidden+ for type in [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton] { w.standardWindowButton(type)?.isHidden = true }+ w.hasShadow = false+ w.isMovable = false+ w.isMovableByWindowBackground = false+ // Round the right-hand corners to the card radius; the left edge meets the divider.+ w.isOpaque = false+ w.backgroundColor = .clear+ if let cv = w.contentView {+ cv.wantsLayer = true+ cv.layer?.cornerRadius = CraMetrics.contentCornerRadius+ cv.layer?.cornerCurve = .continuous+ cv.layer?.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner]+ cv.layer?.masksToBounds = true+ }+ window.addChildWindow(w, ordered: .above)+ }+ positionDevToolsWindow(shell.contentContainer.convert(shell.devToolsHost.frame, to: nil))+ w.orderFront(nil)+ }+++ private func positionDevToolsWindow(_ rectInWindow: NSRect) {+ guard let window, let w = browsers.visibleDevToolsWindow else { return }+ let onScreen = window.convertToScreen(rectInWindow)+ if w.frame != onScreen { w.setFrame(onScreen, display: true) }+ if let cv = w.contentView, let id = browsers.visibleTabID, let v = browsers.devToolsViews[id], v.frame != cv.bounds {+ v.frame = cv.bounds+ }+ }++ func browserManagerHandleKey(_ event: NSEvent) -> Bool { app.handleReservedKey(event) }+ func browserManagerHandleUnhandledKey(_ event: NSEvent) -> Bool { app.handleUnhandledKey(event) }+ func browserManagerFocusedBrowser(_ tabID: UUID) {}+ func browserManagerOpenInternalURL(_ url: String) {+ if let u = URL(string: url) { app.handleInternalURL(u) }+ }++ // MARK: Tabs++ func closeCurrentTab() {+ guard let id = store.selectedTabID else { return }+ closeTab(id)+ }++ /// Today tabs are archived. Pinned tabs and favorites stay; they unload+ /// and return to their pinned page (Arc's close-on-pinned behaviour).+ func closeTab(_ id: UUID) {+ guard let item = store.item(id), item.isTab else { return }+ if store.isPinned(id) {+ let wasSelected = store.selectedTabID == id+ _ = store.resetPinnedTab(id)+ browsers.unload(id)+ if wasSelected {+ let back = item.tab?.activeTabBeforeCreationID+ if let back, store.item(back)?.isTab == true, store.spaceID(ofItem: back) == store.focusedSpaceID {+ store.selectTab(back)+ } else {+ store.selectTab(nil)+ }+ }+ } else {+ store.archiveTab(id, reason: .manual)+ }+ }++ func resetPinnedTab(_ id: UUID) {+ guard let home = store.resetPinnedTab(id) else { return }+ browsers.runtime(for: id)?.browser.loadURL(home)+ }++ func cycleTab(_ delta: Int) {+ let tabs = store.visibleTabs(in: store.focusedSpaceID)+ guard !tabs.isEmpty else { return }+ let idx = store.selectedTabID.flatMap { id in tabs.firstIndex { $0.id == id } } ?? -1+ let n = tabs.count+ store.selectTab(tabs[((idx + delta) % n + n) % n].id)+ }++ func zoom(by delta: Double) {+ guard let b = currentBrowser else { return }+ b.setZoomLevel(b.zoomLevel() + delta)+ }++ /// Arc's Capture: save a PNG of the page area to ~/Downloads.+ func capturePage() {+ guard let window else { return }+ let rectInWindow = shell.webContainer.convert(shell.webContainer.bounds, to: nil)+ var screenRect = window.convertToScreen(rectInWindow)+ // CGWindowList uses top-left origin.+ if let screen = NSScreen.screens.first {+ screenRect.origin.y = screen.frame.height - screenRect.maxY+ }+ guard let image = CGWindowListCreateImage(screenRect, .optionIncludingWindow, CGWindowID(window.windowNumber), [.bestResolution]) else { return }+ let rep = NSBitmapImageRep(cgImage: image)+ guard let png = rep.representation(using: .png, properties: [:]) else { return }+ let f = DateFormatter()+ f.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss"+ let url = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0]+ .appendingPathComponent("Cra Capture \(f.string(from: Date())).png")+ try? png.write(to: url)+ NSWorkspace.shared.activateFileViewerSelecting([url])+ }++ // MARK: Sidebar++ func toggleSidebar() {+ store.prefs.sidebarVisible.toggle()+ if !store.prefs.sidebarVisible { setFloatingSidebar(false) }+ }++ private func setFloatingSidebar(_ show: Bool) {+ guard !store.prefs.sidebarVisible, shell.floatingSidebar != show else { return }+ shell.animateSidebar(visible: false, floating: show, fullscreen: shell.contentFullscreen, width: shell.sidebarWidth, duration: 0.18)+ }++ private func installSwipeMonitor() {+ scrollMonitor = NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { [weak self] event in+ guard let self, event.window === self.window, self.shell.sidebarVisible || self.shell.floatingSidebar else { return event }+ let p = self.shell.convert(event.locationInWindow, from: nil)+ guard self.shell.sidebarHost.frame.contains(p) else { return event }+ switch event.phase {+ case .began:+ self.swipeX = 0; self.swipeY = 0; self.swipeFired = false+ case .changed:+ self.swipeX += event.scrollingDeltaX+ self.swipeY += event.scrollingDeltaY+ if !self.swipeFired, abs(self.swipeX) > 70, abs(self.swipeX) > abs(self.swipeY) * 1.5 {+ self.swipeFired = true+ self.store.focusSpace(offset: self.swipeX < 0 ? 1 : -1)+ }+ default: break+ }+ return event+ }+ }++ // MARK: Command bar++ private var commandBarAttached: Bool {+ commandBar.mode == .editURL && store.settings.showToolbar && store.selectedTab != nil && store.prefs.sidebarVisible+ }++ func openCommandBar(_ mode: CommandBarMode) {+ guard let window else { return }+ let prefill = mode == .editURL ? store.selectedTab?.tab?.url : nil+ let effectiveMode: CommandBarMode = (mode == .editURL && store.selectedTab == nil) ? .newTab : mode+ commandBar.highlight = store.focusedSpace.theme.palette.commandHighlight+ commandBar.focusedSpaceID = store.focusedSpaceID+ commandBar.open(mode: effectiveMode, prefill: prefill)+ commandBar.attached = commandBarAttached+ commandBar.panelWidth = commandBarAttached ? shell.contentContainer.frame.width : min(CraMetrics.commandBarWidth, window.frame.width - 80)+ commandPanel.appearance = nil+ positionCommandPanel()+ if commandPanel.parent == nil { window.addChildWindow(commandPanel, ordered: .above) }+ commandBarOpenedAt = Date()+ NSApp.activate(ignoringOtherApps: true)+ // Key immediately (typing never waits); CommandBarView fades itself in.+ commandPanel.makeKeyAndOrderFront(nil)+ observeCommandBar()+ }++ private func observeCommandBar() {+ guard !commandObserving else { return }+ commandObserving = true+ withObservationTracking {+ _ = commandBar.result.items.count+ _ = commandBar.isOpen+ } onChange: { [weak self] in+ Task { @MainActor in+ self?.commandObserving = false+ guard let self, self.commandBar.isOpen else { return }+ self.positionCommandPanel()+ self.observeCommandBar()+ }+ }+ }++ private func positionCommandPanel() {+ guard let window else { return }+ let rows = commandBar.result.items.count+ let h = CommandBarView.height(forRows: rows)+ let w = commandBar.panelWidth+ let wf = window.frame+ if commandBar.attached {+ // Hang off the toolbar: same x and width as the content card.+ let cardInWindow = shell.convert(shell.contentContainer.frame, to: nil)+ let cardOnScreen = window.convertToScreen(cardInWindow)+ commandPanel.setFrame(NSRect(x: cardOnScreen.minX, y: cardOnScreen.maxY - h, width: w, height: h), display: true)+ } else {+ // Arc centers the bar in the window.+ let x = wf.midX - w / 2+ let y = wf.midY - h / 2 + 40+ commandPanel.setFrame(NSRect(x: x, y: y, width: w, height: h), display: true)+ }+ }++ private func hideCommandPanel() {+ if commandPanel.parent != nil { window?.removeChildWindow(commandPanel) }+ let panel = commandPanel!+ // Let CommandBarView's fade-out (0.08 s) play before the panel goes away.+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.09) { [weak self] in+ guard let self, !self.commandBar.isOpen else { return }+ panel.orderOut(nil)+ }+ window?.makeKeyAndOrderFront(nil)+ currentBrowser?.setFocused(true)+ }++ private func handleCommit(_ s: Suggestion?, typed: String, mode: CommandBarMode, forceNewTab: Bool) {+ let query = commandBar.query+ func open(_ url: String) {+ store.recordQuerySelection(query: query, url: url)+ if mode == .editURL && !forceNewTab, let id = store.selectedTabID {+ store.updateTab(id, url: url)+ if let rt = browsers.ensureRuntime(for: id) { rt.browser.loadURL(url) } else { refresh() }+ browsers.show(id, focus: true)+ } else {+ store.createTab(url: url)+ }+ }+ guard let s else {+ if typed.isEmpty { return }+ open(SuggestionEngine.looksLikeURL(typed) ? SuggestionEngine.urlFromInput(typed) : store.settings.searchEngine.searchURL(typed))+ return+ }+ switch s.kind {+ case .switchToTab(let id):+ store.recordQuerySelection(query: query, url: s.url ?? "")+ store.selectTab(id)+ case .archived(let id):+ store.restoreArchived(id)+ case .navigate:+ let url = typed == commandBar.query ? (s.url ?? SuggestionEngine.urlFromInput(typed)) : SuggestionEngine.urlFromInput(typed)+ open(url)+ case .search:+ open(s.url ?? store.settings.searchEngine.searchURL(typed))+ case .history, .topDomain:+ open(s.url ?? "")+ case .command(let id):+ app.perform(id)+ case .switchSpace(let id):+ store.focusSpace(id)+ case .moveToSpace(let id):+ if let t = store.selectedTabID { store.moveTab(t, toSpace: id) }+ case .moveToFolder(let id):+ if let t = store.selectedTabID { store.moveItem(t, to: id, index: nil) }+ }+ }++ // MARK: Find++ func showFindBar() {+ overlay.findVisible = true+ overlay.findFocusToken += 1+ shell.findVisible = true+ shell.layoutContentChildren()+ window?.makeFirstResponder(shell.findHost)+ }++ func hideFindBar() {+ overlay.findVisible = false+ shell.findVisible = false+ currentBrowser?.stopFinding(true)+ shell.layoutContentChildren()+ currentBrowser?.setFocused(true)+ }++ func findNext(forward: Bool) {+ if !overlay.findVisible { showFindBar(); return }+ find(overlay.findQuery, forward: forward, next: true)+ }++ private func find(_ q: String, forward: Bool, next: Bool) {+ guard let b = currentBrowser else { return }+ if q.isEmpty { b.stopFinding(true); return }+ b.findText(q, forward: forward, matchCase: false, findNext: next)+ }++ // MARK: Sheets++ func showSpaceEditor(space: Space?) {+ guard let window else { return }+ let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 520, height: 520), styleMask: [.titled], backing: .buffered, defer: false)+ let view = SpaceEditorView(existing: space, onSave: { [weak self, weak panel] title, emoji, theme in+ guard let self else { return }+ if var s = space {+ s.title = title; s.emoji = emoji; s.theme = theme+ self.store.updateSpace(s)+ } else {+ self.store.createSpace(title: title, emoji: emoji, theme: theme)+ }+ if let panel { window.endSheet(panel) }+ }, onCancel: { [weak panel] in if let panel { window.endSheet(panel) } })+ panel.contentView = NSHostingView(rootView: view)+ spaceEditor = panel+ window.beginSheet(panel) { [weak self] _ in self?.spaceEditor = nil }+ }++ func showImport() {+ guard let window, importPanel == nil else { return }+ let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 460, height: 360), styleMask: [.titled], backing: .buffered, defer: false)+ let view = ImportView(onDone: { [weak self, weak panel] in if let panel { window.endSheet(panel) }; self?.importPanel = nil })+ .environment(store).environment(app.favicons)+ panel.contentView = NSHostingView(rootView: view)+ importPanel = panel+ window.beginSheet(panel) { [weak self] _ in self?.importPanel = nil }+ }++ /// Close whatever transient UI is up (used by cra://dismiss for scripting).+ func dismissTransientUI() {+ if let sheet = window?.attachedSheet { window?.endSheet(sheet) }+ importPanel = nil+ commandBar.close()+ if overlay.findVisible { hideFindBar() }+ }++ // MARK: NSWindowDelegate++ func windowDidResize(_ notification: Notification) {+ guard (notification.object as? NSWindow) === window else { return }+ shell.needsLayout = true+ browsers.layoutVisible()+ if commandBar.isOpen { positionCommandPanel() }+ saveFrame()+ }++ func windowDidMove(_ notification: Notification) {+ guard (notification.object as? NSWindow) === window else { return }+ if commandBar.isOpen { positionCommandPanel() }+ saveFrame()+ }++ func windowDidBecomeKey(_ notification: Notification) {+ if (notification.object as? NSWindow) === window { shell.windowActive = true }+ }++ func windowDidResignKey(_ notification: Notification) {+ guard (notification.object as? NSWindow) === commandPanel, commandBar.isOpen else { return }+ if Date().timeIntervalSince(commandBarOpenedAt) < 0.6 {+ DispatchQueue.main.async { [weak self] in+ guard let self, self.commandBar.isOpen else { return }+ self.commandPanel.makeKeyAndOrderFront(nil)+ }+ return+ }+ commandBar.close()+ }++ func windowDidEnterFullScreen(_ notification: Notification) { shell.needsLayout = true }+ func windowDidExitFullScreen(_ notification: Notification) {+ if shell.contentFullscreen { shell.contentFullscreen = false }+ enteredFullscreenForContent = false+ shell.needsLayout = true+ }++ private func saveFrame() {+ guard let window, !window.styleMask.contains(.fullScreen) else { return }+ store.prefs.windowFrame = NSStringFromRect(window.frame)+ }++ func windowShouldClose(_ sender: NSWindow) -> Bool {+ if sender === window { commandBar.close() }+ return true+ }+}+++/// Window with Arc's taller title row: the traffic lights sit 24pt from the top+/// and, like Arc, stay hidden until the pointer reaches the sidebar's title row.+final class CraWindow: NSWindow {+ var trafficLightsRevealed = false {+ didSet { if oldValue != trafficLightsRevealed { updateTrafficLightAlpha(animated: true) } }+ }++ override func layoutIfNeeded() {+ super.layoutIfNeeded()+ positionTrafficLights()+ }++ private var dimDots: [NSView] = []++ /// Arc shows the window buttons as muted grey discs and only colours them+ /// while the pointer is over the sidebar's title row.+ private func updateTrafficLightAlpha(animated: Bool) {+ let revealed = trafficLightsRevealed || styleMask.contains(.fullScreen)+ let buttons: [NSWindow.ButtonType] = [.closeButton, .miniaturizeButton, .zoomButton]+ for (i, type) in buttons.enumerated() {+ guard let b = standardWindowButton(type), let sv = b.superview else { continue }+ if dimDots.count <= i {+ let dot = NSView(frame: .zero)+ dot.wantsLayer = true+ dot.layer?.cornerRadius = 5.5+ dot.layer?.backgroundColor = NSColor(white: 0, alpha: 0.11).cgColor+ dot.layer?.borderColor = NSColor(white: 0, alpha: 0.06).cgColor+ dot.layer?.borderWidth = 0.5+ dimDots.append(dot)+ }+ let dot = dimDots[i]+ if dot.superview !== sv { sv.addSubview(dot, positioned: .above, relativeTo: b) }+ dot.frame = NSRect(x: b.frame.midX - 5.5, y: b.frame.midY - 5.5, width: 11, height: 11)+ let set = { b.alphaValue = revealed ? 1 : 0; dot.alphaValue = revealed ? 0 : 1 }+ if animated {+ NSAnimationContext.runAnimationGroup { ctx in+ ctx.duration = 0.15+ b.animator().alphaValue = revealed ? 1 : 0+ dot.animator().alphaValue = revealed ? 0 : 1+ }+ } else {+ set()+ }+ }+ }++ override func makeKeyAndOrderFront(_ sender: Any?) {+ super.makeKeyAndOrderFront(sender)+ positionTrafficLights()+ }++ private func positionTrafficLights() {+ guard !styleMask.contains(.fullScreen) else { return }+ let buttons: [NSWindow.ButtonType] = [.closeButton, .miniaturizeButton, .zoomButton]+ for (i, type) in buttons.enumerated() {+ guard let b = standardWindowButton(type), let sv = b.superview else { continue }+ let x: CGFloat = 13 + CGFloat(i) * 24+ let y = sv.bounds.height - CraMetrics.titleRowCenter - b.frame.height / 2+ let target = NSPoint(x: x, y: y)+ if abs(b.frame.origin.x - target.x) > 0.5 || abs(b.frame.origin.y - target.y) > 0.5 {+ b.setFrameOrigin(target)+ }+ }+ updateTrafficLightAlpha(animated: false)+ }+}diff --git a/Sources/Cra/UI/Windows/SettingsView.swift b/Sources/Cra/UI/Windows/SettingsView.swiftnew file mode 100644index 0000000..23b34f1--- /dev/null+++ b/Sources/Cra/UI/Windows/SettingsView.swift@@ -0,0 +1,82 @@+import SwiftUI+import CraCEF++struct SettingsView: View {+ @Environment(SidebarStore.self) private var store+ @Environment(KeyBindingRegistry.self) private var bindings+ @Environment(AccountStore.self) private var account+ let onImport: () -> Void+ let onAccount: () -> Void++ var body: some View {+ @Bindable var store = store+ Form {+ Section("Account") {+ if let u = account.user {+ LabeledContent("Signed in as", value: u.name.map { "\($0) · \(u.email)" } ?? u.email)+ Button("Manage Account…") { onAccount() }+ } else {+ Text("Sign in to sync settings and back up your sidebar.").foregroundStyle(.secondary)+ Button("Sign In…") { onAccount() }+ }+ }+ Section("Tabs") {+ Picker("Archive today tabs after", selection: $store.settings.autoArchive) {+ ForEach(AutoArchiveThreshold.allCases) { Text($0.label).tag($0) }+ }+ Toggle("New tabs open at the top of Today", isOn: $store.settings.newTabsAtTop)+ Toggle("Show toolbar above the page (⇧⌘D)", isOn: $store.settings.showToolbar)+ }+ Section("Search") {+ Picker("Search engine", selection: $store.settings.searchEngine) {+ ForEach(SearchEngine.allCases) { Text($0.label).tag($0) }+ }+ }+ Section("Import") {+ Text(ArcImporter.isAvailable || DiaImporter.isAvailable+ ? "Bring spaces, pinned tabs, folders, favorites and the archive over from \([ArcImporter.isAvailable ? "Arc" : nil, DiaImporter.isAvailable ? "Dia" : nil].compactMap { $0 }.joined(separator: " or "))."+ : "No Arc or Dia data found on this Mac.")+ .foregroundStyle(.secondary)+ Button("Import…") { onImport() }.disabled(!(ArcImporter.isAvailable || DiaImporter.isAvailable))+ }+ Section {+ ForEach(bindings.actions) { a in+ HStack(spacing: 8) {+ Text(a.name)+ Spacer()+ ShortcutRecorder(action: a)+ Button("Reset") { bindings.resetShortcuts(for: a.id) }+ .buttonStyle(.link).font(.system(size: 11))+ .opacity(bindings.isOverridden(a.id) ? 1 : 0)+ .disabled(!bindings.isOverridden(a.id))+ }+ }+ HStack {+ Text("Click a shortcut, then press the new keys. Esc cancels, ⌫ removes it.")+ .font(.system(size: 11)).foregroundStyle(.secondary)+ Spacer()+ Button("Reset All to Arc Defaults") { bindings.resetOverrides() }+ }+ } header: {+ Text("Shortcuts")+ }+ Section("About") {+ HStack(spacing: 12) {+ BrandMark(size: 44)+ VStack(alignment: .leading, spacing: 2) {+ Text("Cra").font(.system(size: 16, weight: .semibold))+ Text("Version \(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "dev")")+ .font(.system(size: 12)).foregroundStyle(.secondary)+ }+ }+ .padding(.vertical, 4)+ LabeledContent("Chromium", value: CraCEFRuntime.chromiumVersion())+ LabeledContent("CEF", value: CraCEFRuntime.cefVersion())+ LabeledContent("Backend", value: ConvexConfig.url.host ?? "")+ LabeledContent("Data", value: AppPaths.supportDir.path)+ }+ }+ .formStyle(.grouped)+ .frame(width: 540, height: 640)+ }+}diff --git a/Sources/Cra/UI/Windows/ShortcutRecorder.swift b/Sources/Cra/UI/Windows/ShortcutRecorder.swiftnew file mode 100644index 0000000..2cb5a43--- /dev/null+++ b/Sources/Cra/UI/Windows/ShortcutRecorder.swift@@ -0,0 +1,59 @@+import AppKit+import SwiftUI++/// Click-to-record shortcut field for the Settings window.+struct ShortcutRecorder: View {+ let action: KeyAction+ @Environment(KeyBindingRegistry.self) private var bindings+ @State private var recording = false+ @State private var monitor: Any?++ private var conflict: String? {+ guard let s = action.primary else { return nil }+ return bindings.actions.first { $0.id != action.id && $0.shortcuts.contains(s) }?.name+ }++ var body: some View {+ HStack(spacing: 6) {+ if let c = conflict {+ Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.orange).help("Also used by \(c)")+ }+ Button {+ recording ? stop() : start()+ } label: {+ Text(recording ? "Press keys…" : (action.shortcuts.isEmpty ? "None" : action.shortcuts.map(\.display).joined(separator: " ")))+ .font(.system(size: 12, design: .monospaced))+ .foregroundStyle(recording ? Color.accentColor : .secondary)+ .frame(minWidth: 84)+ .padding(.horizontal, 8).padding(.vertical, 3)+ .background(RoundedRectangle(cornerRadius: 6).fill(Color.primary.opacity(0.06)))+ .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(recording ? Color.accentColor : Color.clear))+ }+ .buttonStyle(.plain)+ .help("Click, then press the new shortcut. Esc cancels, ⌫ removes it.")+ }+ .onDisappear { stop() }+ }++ private func start() {+ recording = true+ monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { e in+ handle(e)+ return nil+ }+ }++ private func stop() {+ recording = false+ if let m = monitor { NSEvent.removeMonitor(m) }+ monitor = nil+ }++ private func handle(_ e: NSEvent) {+ if e.keyCode == 53 { stop(); return } // esc+ if e.keyCode == 51 || e.keyCode == 117 { bindings.setShortcuts([], for: action.id); stop(); return } // ⌫ / ⌦+ guard let s = Shortcut.from(event: e) else { return }+ bindings.setShortcuts([s], for: action.id)+ stop()+ }+}diff --git a/Sources/Cra/UI/Windows/SpaceEditorView.swift b/Sources/Cra/UI/Windows/SpaceEditorView.swiftnew file mode 100644index 0000000..8861cf6--- /dev/null+++ b/Sources/Cra/UI/Windows/SpaceEditorView.swift@@ -0,0 +1,115 @@+import SwiftUI++/// Create or edit a space: name, emoji, colors, intensity, grain, appearance+/// (Arc: SpaceCreation + SpaceStyleEditor + SpaceIconPicker).+struct SpaceEditorView: View {+ let existing: Space?+ let onSave: (String, String, SpaceTheme) -> Void+ let onCancel: () -> Void++ @State private var title: String+ @State private var emoji: String+ @State private var theme: SpaceTheme+ @State private var color1: Color+ @State private var color2: Color++ private static let emojis = ["🌱", "💼", "🏠", "🎨", "🧪", "📚", "🎮", "🎵", "🛒", "✈️", "💡", "🔥", "🌊", "🍕", "🐦", "🧑💻",+ "📈", "🧠", "❤️", "⭐️", "🌙", "☕️", "🏃", "📷", "🎬", "🧩", "🪴", "🏔️", "🛠️", "💰", "📝", "🎯"]++ init(existing: Space?, onSave: @escaping (String, String, SpaceTheme) -> Void, onCancel: @escaping () -> Void) {+ self.existing = existing+ self.onSave = onSave+ self.onCancel = onCancel+ let t = existing?.theme ?? SpaceTheme.presets[Int.random(in: 0..<5)]+ _title = State(initialValue: existing?.title ?? "")+ _emoji = State(initialValue: existing?.emoji ?? "🌱")+ _theme = State(initialValue: t)+ _color1 = State(initialValue: Color(hex: t.colors.first ?? "#CCCCCC"))+ _color2 = State(initialValue: Color(hex: t.colors.count > 1 ? t.colors[1] : (t.colors.first ?? "#CCCCCC")))+ }++ var body: some View {+ VStack(spacing: 16) {+ Text(existing == nil ? "New Space" : "Edit Space").font(.system(size: 16, weight: .semibold))+ HStack(spacing: 12) {+ // Preview+ ZStack {+ SpaceBackground(palette: theme.palette)+ VStack(spacing: 6) {+ Text(emoji).font(.system(size: 28))+ Text(title.isEmpty ? "Space" : title).font(.system(size: 13, weight: .semibold)).foregroundStyle(theme.palette.textPrimary)+ RoundedRectangle(cornerRadius: 6).fill(theme.palette.selectedFill).frame(width: 100, height: 22)+ RoundedRectangle(cornerRadius: 6).fill(theme.palette.hoverFill).frame(width: 100, height: 22)+ }+ }+ .frame(width: 180, height: 200)+ .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))++ VStack(alignment: .leading, spacing: 10) {+ TextField("Name", text: $title).textFieldStyle(.roundedBorder)+ LazyVGrid(columns: Array(repeating: GridItem(.fixed(28), spacing: 4), count: 8), spacing: 4) {+ ForEach(Self.emojis, id: \.self) { e in+ Text(e).font(.system(size: 16)).frame(width: 28, height: 28)+ .background(RoundedRectangle(cornerRadius: 6).fill(e == emoji ? Color.accentColor.opacity(0.25) : .clear))+ .onTapGesture { emoji = e }+ }+ }+ HStack {+ Text("Custom emoji").font(.system(size: 11)).foregroundStyle(.secondary)+ TextField("", text: $emoji).textFieldStyle(.roundedBorder).frame(width: 50)+ .onChange(of: emoji) { _, v in if v.count > 2 { emoji = String(v.suffix(2)) } }+ }+ }+ }+ Divider()+ VStack(alignment: .leading, spacing: 8) {+ HStack(spacing: 6) {+ ForEach(SpaceTheme.presets.indices, id: \.self) { i in+ let p = SpaceTheme.presets[i]+ Circle().fill(p.palette.gradient).frame(width: 26, height: 26)+ .overlay(Circle().strokeBorder(Color.primary.opacity(0.15)))+ .onTapGesture {+ theme = p+ color1 = Color(hex: p.colors[0]); color2 = Color(hex: p.colors[1])+ }+ }+ Spacer()+ ColorPicker("", selection: $color1, supportsOpacity: false).labelsHidden()+ ColorPicker("", selection: $color2, supportsOpacity: false).labelsHidden()+ }+ HStack {+ Text("Intensity").frame(width: 70, alignment: .leading)+ Slider(value: $theme.intensity, in: 0...1)+ }+ HStack {+ Text("Grain").frame(width: 70, alignment: .leading)+ Slider(value: $theme.noise, in: 0...1)+ }+ Picker("Appearance", selection: $theme.appearance) {+ Text("Auto").tag("auto"); Text("Light").tag("light"); Text("Dark").tag("dark")+ }+ .pickerStyle(.segmented)+ }+ HStack {+ Button("Cancel") { onCancel() }.keyboardShortcut(.cancelAction)+ Spacer()+ Button(existing == nil ? "Create Space" : "Save") {+ onSave(title.isEmpty ? "Space" : title, emoji.isEmpty ? "🌱" : emoji, theme)+ }+ .keyboardShortcut(.defaultAction)+ .disabled(title.trimmingCharacters(in: .whitespaces).isEmpty && existing == nil)+ }+ }+ .padding(20)+ .frame(width: 520)+ .onChange(of: color1) { _, c in theme.colors = [c.hexString, color2.hexString] }+ .onChange(of: color2) { _, c in theme.colors = [color1.hexString, c.hexString] }+ }+}++extension Color {+ var hexString: String {+ let ns = NSColor(self).usingColorSpace(.sRGB) ?? .gray+ return String(format: "#%02X%02X%02X", Int(round(ns.redComponent * 255)), Int(round(ns.greenComponent * 255)), Int(round(ns.blueComponent * 255)))+ }+}diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mmnew file mode 100644index 0000000..7dd89c3--- /dev/null+++ b/Sources/CraCEF/CraCEF.mm@@ -0,0 +1,843 @@+// Objective-C++ bridge between Swift and CEF. See include/CraCEF.h.+#import "CraCEF.h"++#include <crt_externs.h>+#include <atomic>+#include <string>+#include <vector>++#include "include/cef_app.h"+#include "include/cef_application_mac.h"+#include "include/cef_browser.h"+#include "include/cef_client.h"+#include "include/cef_command_line.h"+#include "include/cef_context_menu_handler.h"+#include "include/cef_display_handler.h"+#include "include/cef_download_handler.h"+#include "include/cef_focus_handler.h"+#include "include/cef_keyboard_handler.h"+#include "include/cef_life_span_handler.h"+#include "include/cef_load_handler.h"+#include "include/cef_parser.h"+#include "include/cef_permission_handler.h"+#include "include/cef_request_handler.h"+#include "include/cef_version.h"+#include "include/wrapper/cef_helpers.h"+#include "include/wrapper/cef_library_loader.h"++// MARK: - Globals++static CefScopedLibraryLoader* g_libraryLoader = nullptr;+static std::atomic<bool> g_contextInitialized{false};+static std::atomic<int> g_liveBrowsers{0};+static bool g_quitting = false;+static bool g_useChromeStyle = false;+static NSMutableArray<CraBrowser*>* g_pendingCreation = nil;+static void (^g_relaunchHandler)(NSArray<NSString*>*) = nil;+static BOOL g_alreadyRunning = NO;+static NSHashTable<CraBrowser*>* g_allBrowsers = nil;++static NSString* NSStringFromCef(const CefString& s) {+ std::string utf8 = s.ToString();+ NSString* r = [[NSString alloc] initWithBytes:utf8.data() length:utf8.size() encoding:NSUTF8StringEncoding];+ return r ?: @"";+}++static CefString CefStringFromNS(NSString* s) {+ return CefString(std::string(s.UTF8String ?: ""));+}++enum CraMenuCommand {+ kMenuOpenLinkInNewTab = MENU_ID_USER_FIRST + 1,+ kMenuOpenLinkInBackgroundTab,+ kMenuCopyLink,+ kMenuInspectElement,+ kMenuOpenImageInNewTab,+ kMenuCopyImageURL,+};++// MARK: - Downloads++@implementation CraDownloadInfo+@end++// MARK: - CraBrowser private interface++class CraClient;++@interface CraBrowser ()+@property (nonatomic, strong) NSView* containerView;+@property (nonatomic, copy) NSString* currentURL;+@property (nonatomic, copy) NSString* currentTitle;+@property (nonatomic) BOOL isLoading;+@property (nonatomic) BOOL canGoBack;+@property (nonatomic) BOOL canGoForward;+@property (nonatomic) BOOL isCreated;+@property (nonatomic) BOOL isClosed;+- (void)adoptBrowser:(CefRefPtr<CefBrowser>)browser;+- (void)browserClosed;+- (CefRefPtr<CefBrowser>)cefBrowser;+- (CefRefPtr<CefClient>)cefClient;+- (void)createNow;+@end++// MARK: - CEF app++class CraApp : public CefApp, public CefBrowserProcessHandler {+public:+ CefRefPtr<CefBrowserProcessHandler> GetBrowserProcessHandler() override { return this; }++ void OnBeforeCommandLineProcessing(const CefString& process_type,+ CefRefPtr<CefCommandLine> command_line) override {+ if (!process_type.empty()) return;+ // Avoid the "wants to use your confidential information stored in+ // Chromium Safe Storage" keychain prompt. Cookies are still encrypted,+ // just with a key that is not in the user's keychain.+ command_line->AppendSwitch("use-mock-keychain");+ command_line->AppendSwitchWithValue("autoplay-policy", "document-user-activation-required");+ }++ // Another Cra process started (LaunchServices, `open -n`). Chromium's+ // process singleton hands its command line to us. Without this CEF opens+ // a stock Chrome-style window.+ bool OnAlreadyRunningAppRelaunch(CefRefPtr<CefCommandLine> command_line,+ const CefString& current_directory) override {+ CEF_REQUIRE_UI_THREAD();+ std::vector<CefString> args;+ command_line->GetArguments(args);+ NSMutableArray<NSString*>* urls = [NSMutableArray array];+ for (const auto& a : args) {+ NSString* str = NSStringFromCef(a);+ if ([str hasPrefix:@"http://"] || [str hasPrefix:@"https://"] || [str hasPrefix:@"cra://"] || [str hasPrefix:@"file://"]) {+ [urls addObject:str];+ }+ }+ if (g_relaunchHandler) g_relaunchHandler(urls);+ return true;+ }++ void OnContextInitialized() override {+ CEF_REQUIRE_UI_THREAD();+ g_contextInitialized = true;+ NSArray<CraBrowser*>* pending = [g_pendingCreation copy];+ [g_pendingCreation removeAllObjects];+ for (CraBrowser* b in pending) {+ [b createNow];+ }+ }++private:+ IMPLEMENT_REFCOUNTING(CraApp);+};++// MARK: - Favicon download++class FaviconCallback : public CefDownloadImageCallback {+public:+ explicit FaviconCallback(CraBrowser* owner) : owner_(owner) {}++ void OnDownloadImageFinished(const CefString& image_url, int http_status_code,+ CefRefPtr<CefImage> image) override {+ CraBrowser* owner = owner_;+ if (!owner || !image || image->IsEmpty()) return;+ int w = 0, h = 0;+ CefRefPtr<CefBinaryValue> png = image->GetAsPNG(2.0f, true, w, h);+ if (!png || png->GetSize() == 0) png = image->GetAsPNG(1.0f, true, w, h);+ if (!png || png->GetSize() == 0) return;+ size_t n = png->GetSize();+ std::vector<uint8_t> bytes(n);+ png->GetData(bytes.data(), n, 0);+ NSData* data = [NSData dataWithBytes:bytes.data() length:n];+ NSImage* img = [[NSImage alloc] initWithData:data];+ if (!img) return;+ [owner.delegate browser:owner didLoadFavicon:img forURL:NSStringFromCef(image_url)];+ }++private:+ __weak CraBrowser* owner_;+ IMPLEMENT_REFCOUNTING(FaviconCallback);+};++// MARK: - DevTools client (minimal, just keeps the live count honest)++class DevToolsClient : public CefClient, public CefLifeSpanHandler, public CefLoadHandler, public CefDisplayHandler {+public:+ DevToolsClient(NSRect frame, CraBrowser* owner, NSView* host) : frame_(frame), owner_(owner), host_(host) {}+ CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() override { return this; }+ CefRefPtr<CefLoadHandler> GetLoadHandler() override { return this; }+ CefRefPtr<CefDisplayHandler> GetDisplayHandler() override { return this; }++ // Docked mode. CEF runs the frontend with can_dock=false (Chrome's docked+ // variant reserves a page placeholder and loses the target in CEF), which+ // hides Chrome's close button, so a close button is added to the main+ // toolbar; it and closeWindow() come back to us as a console message.+ void OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) override {+ if (!host_ || !frame->IsMain()) return;+ std::string url = frame->GetURL().ToString();+ if (url.rfind("devtools://", 0) != 0) return;+ std::string js =+ "(function(){var h=window.InspectorFrontendHost;if(h){h.closeWindow=function(){console.log('__cra_devtools_close');};}"+ "function find(root,sel){var r=root.querySelector(sel);if(r)return r;var all=root.querySelectorAll('*');"+ "for(var i=0;i<all.length;i++){if(all[i].shadowRoot){var f=find(all[i].shadowRoot,sel);if(f)return f;}}return null;}"+ "function make(){var b=document.createElement('button');b.id='cra-close';b.title='Close DevTools';b.setAttribute('aria-label','Close DevTools');"+ "b.style.cssText='all:unset;box-sizing:border-box;cursor:pointer;width:26px;height:26px;margin:0 2px;display:inline-flex;align-items:center;justify-content:center;border-radius:4px;color:var(--icon-default,#9aa0a6)';"+ "b.innerHTML='<svg width=\"14\" height=\"14\" viewBox=\"0 0 14 14\"><path d=\"M2 2l10 10M12 2L2 12\" stroke=\"currentColor\" stroke-width=\"1.6\" stroke-linecap=\"round\" fill=\"none\"/></svg>';"+ "b.onmouseenter=function(){b.style.background='var(--sys-color-state-hover-on-subtle,rgba(128,128,128,.25))';};"+ "b.onmouseleave=function(){b.style.background='';};b.onclick=function(){console.log('__cra_devtools_close');};return b;}"+ "function install(){if(find(document,'#cra-close'))return true;var bar=find(document,'.tabbed-pane-right-toolbar');"+ "if(!bar||!bar.parentNode)return false;var b=make();b.style.alignSelf='center';b.style.margin='0 4px 0 2px';b.style.order='9999';"+ "bar.parentNode.appendChild(b);return true;}"+ "var n=0;var t=setInterval(function(){if(install()){clearInterval(t);return;}if(++n>60){clearInterval(t);"+ "var b=make();b.style.position='fixed';b.style.top='1px';b.style.right='4px';b.style.zIndex='2147483647';document.body.appendChild(b);}},150);})();";+ frame->ExecuteJavaScript(js, frame->GetURL(), 0);+ }++ bool OnConsoleMessage(CefRefPtr<CefBrowser> browser, cef_log_severity_t level, const CefString& message,+ const CefString& source, int line) override {+ if (message.ToString() == "__cra_devtools_close") {+ if (CraBrowser* o = owner_) [o closeDevTools];+ return true;+ }+ return false;+ }+ void OnAfterCreated(CefRefPtr<CefBrowser> browser) override {+ g_liveBrowsers++;+ NSView* view = (__bridge NSView*)browser->GetHost()->GetWindowHandle();+ if (host_) {+ // Docked mode: CEF owns a hidden Alloy window; the shell attaches it+ // as a child window over the dock area. (A child *browser* for+ // DevTools trips a CHECK in CEF 154, and re-parenting the view is+ // unsafe because CEF closes `view.window` when DevTools closes.)+ if (CraBrowser* o = owner_) [o.delegate browser:o didCreateDevToolsView:view];+ return;+ }+ // CEF sizes its own DevTools window with a default; put it where we want it.+ NSWindow* w = view.window;+ if (w && frame_.size.width > 0) {+ [w setFrame:frame_ display:YES];+ [w makeKeyAndOrderFront:nil];+ }+ }+ bool DoClose(CefRefPtr<CefBrowser> browser) override { return false; }+ void OnBeforeClose(CefRefPtr<CefBrowser> browser) override {+ g_liveBrowsers--;+ if (CraBrowser* o = owner_) [o.delegate browserDidCloseDevTools:o];+ if (g_quitting && g_liveBrowsers <= 0) CefQuitMessageLoop();+ }+private:+ NSRect frame_;+ __weak CraBrowser* owner_;+ NSView* host_;+ IMPLEMENT_REFCOUNTING(DevToolsClient);+};++// MARK: - Browser client++class CraClient : public CefClient,+ public CefLifeSpanHandler,+ public CefLoadHandler,+ public CefDisplayHandler,+ public CefRequestHandler,+ public CefContextMenuHandler,+ public CefKeyboardHandler,+ public CefDownloadHandler,+ public CefFocusHandler,+ public CefPermissionHandler {+public:+ explicit CraClient(CraBrowser* owner) : owner_(owner) {}++ CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() override { return this; }+ CefRefPtr<CefLoadHandler> GetLoadHandler() override { return this; }+ CefRefPtr<CefDisplayHandler> GetDisplayHandler() override { return this; }+ CefRefPtr<CefRequestHandler> GetRequestHandler() override { return this; }+ CefRefPtr<CefContextMenuHandler> GetContextMenuHandler() override { return this; }+ CefRefPtr<CefKeyboardHandler> GetKeyboardHandler() override { return this; }+ CefRefPtr<CefDownloadHandler> GetDownloadHandler() override { return this; }+ CefRefPtr<CefFocusHandler> GetFocusHandler() override { return this; }+ CefRefPtr<CefPermissionHandler> GetPermissionHandler() override { return this; }++ // Life span -----------------------------------------------------------++ void OnAfterCreated(CefRefPtr<CefBrowser> browser) override {+ CEF_REQUIRE_UI_THREAD();+ g_liveBrowsers++;+ if (CraBrowser* o = owner_) [o adoptBrowser:browser];+ }++ bool DoClose(CefRefPtr<CefBrowser> browser) override { return false; }++ void OnBeforeClose(CefRefPtr<CefBrowser> browser) override {+ CEF_REQUIRE_UI_THREAD();+ g_liveBrowsers--;+ if (CraBrowser* o = owner_) [o browserClosed];+ if (g_quitting && g_liveBrowsers <= 0) CefQuitMessageLoop();+ }++ bool OnBeforePopup(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int popup_id,+ const CefString& target_url, const CefString& target_frame_name,+ WindowOpenDisposition target_disposition, bool user_gesture,+ const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo,+ CefRefPtr<CefClient>& client, CefBrowserSettings& settings,+ CefRefPtr<CefDictionaryValue>& extra_info, bool* no_javascript_access) override {+ CEF_REQUIRE_UI_THREAD();+ CraBrowser* o = owner_;+ if (!o || !o.delegate) return true;+ BOOL background = (target_disposition == CEF_WOD_NEW_BACKGROUND_TAB);+ CraBrowser* host = [o.delegate browser:o popupHostForURL:NSStringFromCef(target_url) inBackground:background];+ if (!host) return true; // blocked+ NSView* view = host.containerView;+ NSRect b = view.bounds;+ windowInfo.SetAsChild((__bridge void*)view, CefRect(0, 0, (int)b.size.width, (int)b.size.height));+ if (g_useChromeStyle) windowInfo.runtime_style = CEF_RUNTIME_STYLE_CHROME;+ client = [host cefClient];+ return false; // allow, CEF creates it into our view with the opener kept+ }++ // Load ----------------------------------------------------------------++ void OnLoadingStateChange(CefRefPtr<CefBrowser> browser, bool isLoading, bool canGoBack,+ bool canGoForward) override {+ CraBrowser* o = owner_;+ if (!o) return;+ o.isLoading = isLoading;+ o.canGoBack = canGoBack;+ o.canGoForward = canGoForward;+ [o.delegate browser:o didChangeLoading:isLoading canGoBack:canGoBack canGoForward:canGoForward];+ }++ void OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) override {+ if (!frame->IsMain()) return;+ CraBrowser* o = owner_;+ if (!o) return;+ [o.delegate browser:o didFinishLoadingURL:NSStringFromCef(frame->GetURL()) title:o.currentTitle+ statusCode:httpStatusCode];+ // Ask the page for its theme colour; the answer comes back through OnConsoleMessage.+ frame->ExecuteJavaScript(+ "(function(){function probe(){try{var c='';var ms=document.querySelectorAll('meta[name=\"theme-color\"]');"+ "for(var i=0;i<ms.length;i++){if(!ms[i].getAttribute('media')){c=ms[i].getAttribute('content')||'';if(c)break;}}"+ "if(!c){c='__none__';}"+ "if(!c){var b=getComputedStyle(document.body).backgroundColor;if(b&&b!=='rgba(0, 0, 0, 0)'&&b!=='transparent'){c=b;}}"+ "if(!c){var h=getComputedStyle(document.documentElement).backgroundColor;if(h&&h!=='rgba(0, 0, 0, 0)'){c=h;}}"+ "if(c==='__none__'){console.log('__cra_theme:none');return;}"+ "var d=document.createElement('div');d.style.color=c;document.body.appendChild(d);"+ "var rgb=getComputedStyle(d).color;d.remove();console.log('__cra_theme:'+rgb);}catch(e){}}"+ "probe();setTimeout(probe,1500);})();",+ frame->GetURL(), 0);+ }++ bool OnConsoleMessage(CefRefPtr<CefBrowser> browser, cef_log_severity_t level, const CefString& message,+ const CefString& source, int line) override {+ std::string m = message.ToString();+ const std::string prefix = "__cra_theme:";+ if (m.compare(0, prefix.size(), prefix) != 0) return false;+ CraBrowser* o = owner_;+ if (!o) return true;+ std::string rgb = m.substr(prefix.size()); // "rgb(r, g, b)", "rgba(…)" or "none"+ int r = 0, g = 0, b = 0; float a = 1;+ NSString* hex = @"";+ if (rgb == "none") hex = @"none";+ if (sscanf(rgb.c_str(), "rgba(%d, %d, %d, %f)", &r, &g, &b, &a) == 4 || sscanf(rgb.c_str(), "rgb(%d, %d, %d)", &r, &g, &b) == 3) {+ if (a > 0.5f) hex = [NSString stringWithFormat:@"#%02X%02X%02X", r, g, b];+ }+ [o.delegate browser:o didReportThemeColor:hex];+ return true; // keep it out of the console+ }++ void OnLoadError(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, ErrorCode errorCode,+ const CefString& errorText, const CefString& failedUrl) override {+ if ((int)errorCode == -3 /* ERR_ABORTED */ || !frame->IsMain()) return;+ std::string url = failedUrl.ToString();+ std::string err = errorText.ToString();+ std::string html =+ "<!doctype html><html><head><meta charset=utf-8><title>Can’t reach this page</title>"+ "<style>html{background:#f5f5f7;color:#1d1d1f;font:15px -apple-system,system-ui}"+ "@media(prefers-color-scheme:dark){html{background:#1c1c1e;color:#f5f5f7}}"+ "body{display:flex;min-height:90vh;align-items:center;justify-content:center;margin:0}"+ "main{max-width:420px;padding:32px}h1{font-size:22px;margin:0 0 8px}p{opacity:.7;margin:0 0 6px}"+ "code{font:13px ui-monospace,Menlo;opacity:.6;word-break:break-all}</style></head><body><main>"+ "<h1>Cra can’t reach this page</h1><p>" + err + " (" + std::to_string((int)errorCode) + ")</p>"+ "<code>" + url + "</code></main></body></html>";+ CefString encoded = CefBase64Encode(html.data(), html.size());+ frame->LoadURL("data:text/html;base64," + encoded.ToString());+ }++ // Display -------------------------------------------------------------++ void OnAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& url) override {+ if (!frame->IsMain()) return;+ CraBrowser* o = owner_;+ if (!o) return;+ o.currentURL = NSStringFromCef(url);+ [o.delegate browser:o didChangeURL:o.currentURL];+ }++ void OnTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title) override {+ CraBrowser* o = owner_;+ if (!o) return;+ o.currentTitle = NSStringFromCef(title);+ [o.delegate browser:o didChangeTitle:o.currentTitle];+ }++ void OnFaviconURLChange(CefRefPtr<CefBrowser> browser, const std::vector<CefString>& icon_urls) override {+ CraBrowser* o = owner_;+ if (!o || icon_urls.empty()) return;+ // Prefer PNG/ICO-looking URLs over SVG, which CEF can't decode.+ CefString chosen = icon_urls.front();+ for (const auto& u : icon_urls) {+ std::string s = u.ToString();+ if (s.find(".svg") == std::string::npos) { chosen = u; break; }+ }+ std::string chosenStr = chosen.ToString();+ if (chosenStr == last_icon_url_) return;+ last_icon_url_ = chosenStr;+ browser->GetHost()->DownloadImage(chosen, true, 64, false, new FaviconCallback(o));+ }++ void OnFullscreenModeChange(CefRefPtr<CefBrowser> browser, bool fullscreen) override {+ if (CraBrowser* o = owner_) [o.delegate browser:o didChangeFullscreen:fullscreen];+ }++ void OnStatusMessage(CefRefPtr<CefBrowser> browser, const CefString& value) override {+ if (CraBrowser* o = owner_) [o.delegate browser:o didChangeStatusMessage:NSStringFromCef(value)];+ }++ void OnLoadingProgressChange(CefRefPtr<CefBrowser> browser, double progress) override {+ if (CraBrowser* o = owner_) [o.delegate browser:o didChangeProgress:progress];+ }++ // Request -------------------------------------------------------------++ bool OnOpenURLFromTab(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& target_url,+ WindowOpenDisposition target_disposition, bool user_gesture) override {+ CraBrowser* o = owner_;+ if (!o) return false;+ BOOL background = (target_disposition == CEF_WOD_NEW_BACKGROUND_TAB);+ [o.delegate browser:o requestsNewTabWithURL:NSStringFromCef(target_url) inBackground:background];+ return true;+ }++ // Context menu --------------------------------------------------------++ void OnBeforeContextMenu(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,+ CefRefPtr<CefContextMenuParams> params, CefRefPtr<CefMenuModel> model) override {+ size_t index = 0;+ if (!params->GetLinkUrl().empty()) {+ model->InsertItemAt(index++, kMenuOpenLinkInNewTab, "Open Link in New Tab");+ model->InsertItemAt(index++, kMenuOpenLinkInBackgroundTab, "Open Link in Background Tab");+ model->InsertItemAt(index++, kMenuCopyLink, "Copy Link");+ model->InsertSeparatorAt(index++);+ }+ if ((params->GetTypeFlags() & CM_TYPEFLAG_MEDIA) && !params->GetSourceUrl().empty()) {+ model->InsertItemAt(index++, kMenuOpenImageInNewTab, "Open Image in New Tab");+ model->InsertItemAt(index++, kMenuCopyImageURL, "Copy Image Address");+ model->InsertSeparatorAt(index++);+ }+ if (model->GetCount() > 0) model->AddSeparator();+ model->AddItem(kMenuInspectElement, "Inspect Element");+ }++ bool OnContextMenuCommand(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,+ CefRefPtr<CefContextMenuParams> params, int command_id,+ EventFlags event_flags) override {+ CraBrowser* o = owner_;+ if (!o) return false;+ switch (command_id) {+ case kMenuOpenLinkInNewTab:+ [o.delegate browser:o requestsNewTabWithURL:NSStringFromCef(params->GetLinkUrl()) inBackground:NO];+ return true;+ case kMenuOpenLinkInBackgroundTab:+ [o.delegate browser:o requestsNewTabWithURL:NSStringFromCef(params->GetLinkUrl()) inBackground:YES];+ return true;+ case kMenuOpenImageInNewTab:+ [o.delegate browser:o requestsNewTabWithURL:NSStringFromCef(params->GetSourceUrl()) inBackground:NO];+ return true;+ case kMenuCopyLink:+ case kMenuCopyImageURL: {+ NSString* s = NSStringFromCef(command_id == kMenuCopyLink ? params->GetUnfilteredLinkUrl()+ : params->GetSourceUrl());+ NSPasteboard* pb = [NSPasteboard generalPasteboard];+ [pb clearContents];+ [pb setString:s forType:NSPasteboardTypeString];+ return true;+ }+ case kMenuInspectElement:+ [o showDevToolsInspectingPoint:NSMakePoint(params->GetXCoord(), params->GetYCoord())];+ return true;+ default:+ return false;+ }+ }++ // Keyboard ------------------------------------------------------------++ bool OnPreKeyEvent(CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event,+ bool* is_keyboard_shortcut) override {+ if (event.type != KEYEVENT_RAWKEYDOWN || !os_event) return false;+ CraBrowser* o = owner_;+ if (!o) return false;+ NSEvent* e = (__bridge NSEvent*)os_event;+ if (e.type != NSEventTypeKeyDown) return false; // modifier-only presses arrive as flagsChanged+ return [o.delegate browser:o handleKeyEvent:e] ? true : false;+ }++ bool OnKeyEvent(CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event) override {+ if (event.type != KEYEVENT_RAWKEYDOWN || !os_event) return false;+ CraBrowser* o = owner_;+ if (!o) return false;+ NSEvent* e = (__bridge NSEvent*)os_event;+ if (e.type != NSEventTypeKeyDown) return false;+ return [o.delegate browser:o handleUnhandledKeyEvent:e] ? true : false;+ }++ // Downloads -----------------------------------------------------------++ bool OnBeforeDownload(CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> download_item,+ const CefString& suggested_name, CefRefPtr<CefBeforeDownloadCallback> callback) override {+ NSString* name = NSStringFromCef(suggested_name);+ if (name.length == 0) name = @"download";+ NSString* dir = [NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory, NSUserDomainMask, YES) firstObject];+ NSString* path = [dir stringByAppendingPathComponent:name];+ NSFileManager* fm = [NSFileManager defaultManager];+ NSString* base = [name stringByDeletingPathExtension];+ NSString* ext = [name pathExtension];+ int n = 1;+ while ([fm fileExistsAtPath:path]) {+ NSString* candidate = ext.length ? [NSString stringWithFormat:@"%@ (%d).%@", base, n, ext]+ : [NSString stringWithFormat:@"%@ (%d)", base, n];+ path = [dir stringByAppendingPathComponent:candidate];+ n++;+ }+ callback->Continue(CefStringFromNS(path), false);+ return true;+ }++ void OnDownloadUpdated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefDownloadItem> item,+ CefRefPtr<CefDownloadItemCallback> callback) override {+ CraBrowser* o = owner_;+ if (!o) return;+ CraDownloadInfo* info = [CraDownloadInfo new];+ info.identifier = item->GetId();+ info.url = NSStringFromCef(item->GetURL());+ info.fullPath = NSStringFromCef(item->GetFullPath());+ info.suggestedName = NSStringFromCef(item->GetSuggestedFileName());+ info.receivedBytes = item->GetReceivedBytes();+ info.totalBytes = item->GetTotalBytes();+ info.percent = item->GetPercentComplete();+ if (item->IsComplete()) info.state = CraDownloadStateComplete;+ else if (item->IsCanceled()) info.state = CraDownloadStateCancelled;+ else if (item->IsInterrupted()) info.state = CraDownloadStateInterrupted;+ else info.state = CraDownloadStateInProgress;+ [o.delegate browser:o didUpdateDownload:info];+ }++ // Focus ---------------------------------------------------------------++ void OnGotFocus(CefRefPtr<CefBrowser> browser) override {+ if (CraBrowser* o = owner_) [o.delegate browserDidReceiveFocus:o];+ }++ // Permissions ---------------------------------------------------------++ bool OnRequestMediaAccessPermission(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,+ const CefString& requesting_origin, uint32_t requested_permissions,+ CefRefPtr<CefMediaAccessCallback> callback) override {+ CraBrowser* o = owner_;+ if (!o || !o.delegate) return false;+ NSUInteger kinds = 0;+ if (requested_permissions & (CEF_MEDIA_PERMISSION_DEVICE_VIDEO_CAPTURE | CEF_MEDIA_PERMISSION_DESKTOP_VIDEO_CAPTURE)) kinds |= 1;+ if (requested_permissions & (CEF_MEDIA_PERMISSION_DEVICE_AUDIO_CAPTURE | CEF_MEDIA_PERMISSION_DESKTOP_AUDIO_CAPTURE)) kinds |= 2;+ CefRefPtr<CefMediaAccessCallback> cb = callback;+ uint32_t requested = requested_permissions;+ [o.delegate browser:o requestsPermissionForOrigin:NSStringFromCef(requesting_origin) kinds:kinds+ completion:^(BOOL allowed) {+ cb->Continue(allowed ? requested : CEF_MEDIA_PERMISSION_NONE);+ }];+ return true;+ }++ bool OnShowPermissionPrompt(CefRefPtr<CefBrowser> browser, uint64_t prompt_id,+ const CefString& requesting_origin, uint32_t requested_permissions,+ CefRefPtr<CefPermissionPromptCallback> callback) override {+ CraBrowser* o = owner_;+ if (!o || !o.delegate) return false;+ NSUInteger kinds = 0;+ if (requested_permissions & (CEF_PERMISSION_TYPE_CAMERA_STREAM | CEF_PERMISSION_TYPE_CAMERA_PAN_TILT_ZOOM)) kinds |= 1;+ if (requested_permissions & CEF_PERMISSION_TYPE_MIC_STREAM) kinds |= 2;+ if (requested_permissions & CEF_PERMISSION_TYPE_GEOLOCATION) kinds |= 4;+ if (requested_permissions & CEF_PERMISSION_TYPE_NOTIFICATIONS) kinds |= 8;+ if (kinds == 0) kinds = 16;+ CefRefPtr<CefPermissionPromptCallback> cb = callback;+ [o.delegate browser:o requestsPermissionForOrigin:NSStringFromCef(requesting_origin) kinds:kinds+ completion:^(BOOL allowed) {+ cb->Continue(allowed ? CEF_PERMISSION_RESULT_ACCEPT : CEF_PERMISSION_RESULT_DENY);+ }];+ return true;+ }++private:+ __weak CraBrowser* owner_;+ std::string last_icon_url_;+ IMPLEMENT_REFCOUNTING(CraClient);+};++// MARK: - CraBrowser++@implementation CraBrowser {+ CefRefPtr<CefBrowser> _browser;+ CefRefPtr<CraClient> _client;+ NSString* _pendingURL;+ BOOL _pendingFocus;+ BOOL _isPopupHost;+}++- (instancetype)initWithFrame:(NSRect)frame url:(NSString*)url delegate:(id<CraBrowserDelegate>)delegate {+ self = [super init];+ if (!self) return nil;+ _delegate = delegate;+ _currentURL = url ?: @"";+ _currentTitle = @"";+ _pendingURL = url;+ _isPopupHost = (url == nil);+ _containerView = [[NSView alloc] initWithFrame:frame];+ _containerView.wantsLayer = YES;+ _containerView.autoresizesSubviews = YES;+ _client = new CraClient(self);+ if (!g_allBrowsers) g_allBrowsers = [NSHashTable weakObjectsHashTable];+ [g_allBrowsers addObject:self];+ if (!_isPopupHost) {+ if (g_contextInitialized) {+ [self createNow];+ } else {+ if (!g_pendingCreation) g_pendingCreation = [NSMutableArray array];+ [g_pendingCreation addObject:self];+ }+ }+ return self;+}++- (void)createNow {+ if (_isClosed || _browser) return;+ CefWindowInfo windowInfo;+ NSRect b = _containerView.bounds;+ windowInfo.SetAsChild((__bridge void*)_containerView,+ CefRect(0, 0, (int)MAX(b.size.width, 1), (int)MAX(b.size.height, 1)));+ if (g_useChromeStyle) windowInfo.runtime_style = CEF_RUNTIME_STYLE_CHROME;+ CefBrowserSettings settings;+ CefBrowserHost::CreateBrowser(windowInfo, _client, CefStringFromNS(_pendingURL ?: @"about:blank"), settings,+ nullptr, nullptr);+}++- (CefRefPtr<CefBrowser>)cefBrowser { return _browser; }+- (CefRefPtr<CefClient>)cefClient { return _client; }++- (void)adoptBrowser:(CefRefPtr<CefBrowser>)browser {+ _browser = browser;+ self.isCreated = YES;+ if (_pendingFocus) {+ _pendingFocus = NO;+ browser->GetHost()->SetFocus(true);+ }+}++- (void)browserClosed {+ _browser = nullptr;+ self.isClosed = YES;+ [g_allBrowsers removeObject:self];+ id<CraBrowserDelegate> d = self.delegate;+ [d browserDidClose:self];+}++- (BOOL)hasDevTools { return _browser ? _browser->GetHost()->HasDevTools() : NO; }++- (void)loadURL:(NSString*)url {+ if (_browser) {+ _browser->GetMainFrame()->LoadURL(CefStringFromNS(url));+ } else {+ _pendingURL = url;+ }+}++- (void)goBack { if (_browser) _browser->GoBack(); }+- (void)goForward { if (_browser) _browser->GoForward(); }+- (void)reload { if (_browser) _browser->Reload(); }+- (void)reloadIgnoringCache { if (_browser) _browser->ReloadIgnoreCache(); }+- (void)stopLoading { if (_browser) _browser->StopLoad(); }++- (void)setFocused:(BOOL)focused {+ if (_browser) _browser->GetHost()->SetFocus(focused);+ else if (focused) _pendingFocus = YES;+}++- (void)showDevToolsInspectingPoint:(NSPoint)point {+ if (!_browser) return;+ if (_browser->GetHost()->HasDevTools()) {+ _browser->GetHost()->ShowDevTools(CefWindowInfo(), nullptr, CefBrowserSettings(),+ CefPoint((int)point.x, (int)point.y));+ return;+ }+ NSView* host = [self.delegate devToolsHostViewForBrowser:self];+ CefWindowInfo windowInfo;+ NSRect target = NSZeroRect;+ if (host) {+ NSRect b = host.bounds;+ windowInfo.bounds = CefRect(0, 0, (int)MAX(b.size.width, 1), (int)MAX(b.size.height, 1));+ windowInfo.runtime_style = CEF_RUNTIME_STYLE_ALLOY;+ windowInfo.hidden = true;+ CefString(&windowInfo.window_name) = "DevTools";+ } else {+ // No parent view: CEF creates its own top-level DevTools window (what+ // cefclient does on macOS); we resize it once it exists.+ NSWindow* w = _containerView.window;+ NSRect f = w ? w.frame : NSMakeRect(100, 100, 1100, 760);+ CGFloat width = MIN(1100, MAX(700, f.size.width * 0.8));+ CGFloat height = MIN(800, MAX(500, f.size.height * 0.8));+ target = NSMakeRect(NSMidX(f) - width / 2 + 40, NSMidY(f) - height / 2 - 20, width, height);+ CefString(&windowInfo.window_name) = "DevTools";+ }+ CefBrowserSettings settings;+ _browser->GetHost()->ShowDevTools(windowInfo, new DevToolsClient(target, self, host), settings,+ CefPoint((int)point.x, (int)point.y));+}++- (void)showDevTools { [self showDevToolsInspectingPoint:NSZeroPoint]; }+- (void)closeDevTools { if (_browser) _browser->GetHost()->CloseDevTools(); }++- (double)zoomLevel { return _browser ? _browser->GetHost()->GetZoomLevel() : 0; }+- (void)setZoomLevel:(double)level { if (_browser) _browser->GetHost()->SetZoomLevel(level); }++- (void)findText:(NSString*)text forward:(BOOL)forward matchCase:(BOOL)matchCase findNext:(BOOL)findNext {+ if (_browser) _browser->GetHost()->Find(CefStringFromNS(text), forward, matchCase, findNext);+}+- (void)stopFinding:(BOOL)clearSelection { if (_browser) _browser->GetHost()->StopFinding(clearSelection); }+- (void)setAudioMuted:(BOOL)muted { if (_browser) _browser->GetHost()->SetAudioMuted(muted); }+- (void)print { if (_browser) _browser->GetHost()->Print(); }+- (void)viewSource { if (_browser) _browser->GetMainFrame()->ViewSource(); }+- (void)executeJavaScript:(NSString*)script {+ if (_browser) _browser->GetMainFrame()->ExecuteJavaScript(CefStringFromNS(script), _browser->GetMainFrame()->GetURL(), 0);+}+- (void)notifyMoveOrResizeStarted { if (_browser) _browser->GetHost()->NotifyMoveOrResizeStarted(); }++- (void)close {+ if (_isClosed) return;+ if (_browser) {+ _browser->GetHost()->CloseBrowser(true);+ } else {+ // Never created; drop it from the pending list and report closed.+ [g_pendingCreation removeObject:self];+ [self browserClosed];+ }+}++@end++// MARK: - Runtime++@implementation CraCEFRuntime+++ (BOOL)initializeWithCachePath:(NSString*)cachePath+ userAgentProduct:(NSString*)product+ logPath:(NSString*)logPath+ useChromeStyle:(BOOL)useChromeStyle {+ if (g_libraryLoader) return YES;+ g_useChromeStyle = useChromeStyle;+ g_libraryLoader = new CefScopedLibraryLoader();+ if (!g_libraryLoader->LoadInMain()) {+ NSLog(@"CraCEF: failed to load Chromium Embedded Framework");+ return NO;+ }+ // Make sure the CefAppProtocol NSApplication exists before CefInitialize.+ [CraApplication sharedApplication];++ CefMainArgs mainArgs(*_NSGetArgc(), *_NSGetArgv());+ CefSettings settings;+ settings.no_sandbox = true;+ CefString(&settings.cache_path) = CefStringFromNS(cachePath);+ CefString(&settings.root_cache_path) = CefStringFromNS(cachePath);+ settings.persist_session_cookies = true;+ CefString(&settings.user_agent_product) = CefStringFromNS(product);+ CefString(&settings.log_file) = CefStringFromNS(logPath);+ settings.log_severity = LOGSEVERITY_WARNING;+ settings.background_color = CefColorSetARGB(255, 255, 255, 255);++ CefRefPtr<CraApp> app(new CraApp());+ if (!CefInitialize(mainArgs, settings, app.get(), nullptr)) {+ int code = CefGetExitCode();+ g_alreadyRunning = (code == CEF_RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED);+ NSLog(@"CraCEF: CefInitialize failed (exit code %d%@)", code, g_alreadyRunning ? @", another instance is running" : @"");+ return NO;+ }+ return YES;+}+++ (BOOL)anotherInstanceWasNotified { return g_alreadyRunning; }++ (void)setRelaunchHandler:(void (^)(NSArray<NSString*>*))handler { g_relaunchHandler = [handler copy]; }+++ (void)runMessageLoop { CefRunMessageLoop(); }++ (void)quitMessageLoop { CefQuitMessageLoop(); }++ (void)shutdown { CefShutdown(); }+++ (void)closeAllBrowsersAndQuit {+ g_quitting = true;+ NSArray<CraBrowser*>* all = [g_allBrowsers allObjects];+ if (all.count == 0 || g_liveBrowsers <= 0) {+ CefQuitMessageLoop();+ return;+ }+ for (CraBrowser* b in all) [b close];+}+++ (NSInteger)liveBrowserCount { return g_liveBrowsers; }++ (NSString*)chromiumVersion {+ return [NSString stringWithFormat:@"%d.%d.%d.%d", CHROME_VERSION_MAJOR, CHROME_VERSION_MINOR,+ CHROME_VERSION_BUILD, CHROME_VERSION_PATCH];+}++ (NSString*)cefVersion { return @CEF_VERSION; }++@end++// MARK: - NSApplication subclass++@interface CraApplication () <CefAppProtocol>+@end++@implementation CraApplication {+ BOOL _handlingSendEvent;+}++- (BOOL)isHandlingSendEvent { return _handlingSendEvent; }+- (void)setHandlingSendEvent:(BOOL)handlingSendEvent { _handlingSendEvent = handlingSendEvent; }++// Chrome's rule: when a web view has focus, ⌘-shortcuts go to the page+// first and only reach the menu bar if the page leaves them alone (so ⌘F in+// Google Docs or ⌘← in a text field keep working). Reserved shortcuts are+// taken in OnPreKeyEvent, the rest in OnKeyEvent.+- (void)sendEvent:(NSEvent*)event {+ CefScopedSendingEvent sendingEventScoper;+ if (event.type == NSEventTypeKeyDown && (event.modifierFlags & NSEventModifierFlagCommand)) {+ NSWindow* key = self.keyWindow;+ NSResponder* fr = key.firstResponder;+ if ([fr isKindOfClass:[NSView class]]) {+ NSView* v = (NSView*)fr;+ for (CraBrowser* b in [g_allBrowsers allObjects]) {+ if ([v isDescendantOf:b.containerView]) {+ [key sendEvent:event];+ return;+ }+ }+ }+ }+ [super sendEvent:event];+}++// Cmd-Q, the Dock, logout: give the delegate a say, then tear Chromium down+// in order (browsers first, then the message loop, then CefShutdown in main).+- (void)terminate:(id)sender {+ id<NSApplicationDelegate> delegate = self.delegate;+ if ([delegate respondsToSelector:@selector(applicationShouldTerminate:)]) {+ NSApplicationTerminateReply reply = [delegate applicationShouldTerminate:self];+ if (reply == NSTerminateCancel) return;+ }+ [CraCEFRuntime closeAllBrowsersAndQuit];+}++@enddiff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.hnew file mode 100644index 0000000..f02197f--- /dev/null+++ b/Sources/CraCEF/include/CraCEF.h@@ -0,0 +1,134 @@+// CraCEF: the Objective-C surface Swift uses to drive Chromium (CEF).+// Everything here runs on the main thread.+#import <Cocoa/Cocoa.h>++NS_ASSUME_NONNULL_BEGIN++@class CraBrowser;++typedef NS_ENUM(NSInteger, CraDownloadState) {+ CraDownloadStateInProgress = 0,+ CraDownloadStateComplete = 1,+ CraDownloadStateCancelled = 2,+ CraDownloadStateInterrupted = 3,+};++@interface CraDownloadInfo : NSObject+@property (nonatomic) uint32_t identifier;+@property (nonatomic, copy) NSString *url;+@property (nonatomic, copy) NSString *fullPath;+@property (nonatomic, copy) NSString *suggestedName;+@property (nonatomic) int64_t receivedBytes;+@property (nonatomic) int64_t totalBytes;+@property (nonatomic) NSInteger percent;+@property (nonatomic) CraDownloadState state;+@end++@protocol CraBrowserDelegate <NSObject>+- (void)browser:(CraBrowser *)browser didChangeTitle:(NSString *)title;+- (void)browser:(CraBrowser *)browser didChangeURL:(NSString *)url;+- (void)browser:(CraBrowser *)browser didChangeLoading:(BOOL)loading canGoBack:(BOOL)canGoBack canGoForward:(BOOL)canGoForward;+- (void)browser:(CraBrowser *)browser didChangeProgress:(double)progress;+- (void)browser:(CraBrowser *)browser didFinishLoadingURL:(NSString *)url title:(NSString *)title statusCode:(NSInteger)statusCode;+- (void)browser:(CraBrowser *)browser didLoadFavicon:(NSImage *)image forURL:(NSString *)iconURL;+- (void)browser:(CraBrowser *)browser didChangeStatusMessage:(NSString *)message;+/// The page's theme colour (meta theme-color or body background) as "#RRGGBB", or "" when unknown.+- (void)browser:(CraBrowser *)browser didReportThemeColor:(NSString *)hex;+- (void)browser:(CraBrowser *)browser didChangeFullscreen:(BOOL)fullscreen;+/// Cmd-click, middle-click and similar: open a plain new tab.+- (void)browser:(CraBrowser *)browser requestsNewTabWithURL:(NSString *)url inBackground:(BOOL)background;+/// window.open / target=_blank: return a popup host (a CraBrowser created with+/// a nil URL) so the popup keeps its opener relationship, or nil to block it.+- (nullable CraBrowser *)browser:(CraBrowser *)browser popupHostForURL:(NSString *)url inBackground:(BOOL)background;+/// Return a view to host DevTools in (Cra docks it inside the content card);+/// nil makes CEF open its own DevTools window.+- (nullable NSView *)devToolsHostViewForBrowser:(CraBrowser *)browser;+/// DevTools was created for docking (a host view was returned): `view.window`+/// is CEF's hidden Alloy window, to be attached as a child window.+- (void)browser:(CraBrowser *)browser didCreateDevToolsView:(NSView *)view;+/// The DevTools browser closed (either mode).+- (void)browserDidCloseDevTools:(CraBrowser *)browser;+/// Reserved shortcuts, before the page sees the key. Return YES to consume.+- (BOOL)browser:(CraBrowser *)browser handleKeyEvent:(NSEvent *)event;+/// Keys the page did not handle (Chrome gives the page first chance at+/// unreserved shortcuts like ⌘F). Return YES to consume.+- (BOOL)browser:(CraBrowser *)browser handleUnhandledKeyEvent:(NSEvent *)event;+- (void)browser:(CraBrowser *)browser didUpdateDownload:(CraDownloadInfo *)download;+/// Ask the user. `kinds` is a bitmask: 1 = camera, 2 = microphone,+/// 4 = location, 8 = notifications, 16 = other.+- (void)browser:(CraBrowser *)browser requestsPermissionForOrigin:(NSString *)origin kinds:(NSUInteger)kinds completion:(void (^)(BOOL allowed))completion;+- (void)browserDidReceiveFocus:(CraBrowser *)browser;+- (void)browserDidClose:(CraBrowser *)browser;+@end++@interface CraBrowser : NSObject+@property (nonatomic, weak, nullable) id<CraBrowserDelegate> delegate;+/// A plain NSView that owns the Chromium view. Put it in your hierarchy and+/// size it; Chromium follows.+@property (nonatomic, readonly) NSView *containerView;+@property (nonatomic, readonly, copy) NSString *currentURL;+@property (nonatomic, readonly, copy) NSString *currentTitle;+@property (nonatomic, readonly) BOOL isLoading;+@property (nonatomic, readonly) BOOL canGoBack;+@property (nonatomic, readonly) BOOL canGoForward;+@property (nonatomic, readonly) BOOL isCreated;+@property (nonatomic, readonly) BOOL isClosed;+@property (nonatomic, readonly) BOOL hasDevTools;+/// Anything you want to hang on the browser (Swift stores the tab id).+@property (nonatomic, strong, nullable) id userInfo;++/// Pass a URL to create a browser now. Pass nil to create a popup host that+/// adopts the next popup CEF gives it (see -browser:popupHostForURL:...).+- (instancetype)initWithFrame:(NSRect)frame url:(nullable NSString *)url delegate:(nullable id<CraBrowserDelegate>)delegate;++- (void)loadURL:(NSString *)url;+- (void)goBack;+- (void)goForward;+- (void)reload;+- (void)reloadIgnoringCache;+- (void)stopLoading;+- (void)setFocused:(BOOL)focused;+- (void)showDevToolsInspectingPoint:(NSPoint)point;+- (void)showDevTools;+- (void)closeDevTools;+- (double)zoomLevel;+- (void)setZoomLevel:(double)level;+- (void)findText:(NSString *)text forward:(BOOL)forward matchCase:(BOOL)matchCase findNext:(BOOL)findNext;+- (void)stopFinding:(BOOL)clearSelection;+- (void)setAudioMuted:(BOOL)muted;+- (void)print;+- (void)viewSource;+- (void)executeJavaScript:(NSString *)script;+- (void)notifyMoveOrResizeStarted;+/// Asynchronous. -browserDidClose: fires when Chromium is done.+- (void)close;+@end++@interface CraCEFRuntime : NSObject+/// Call once, after NSApplication exists, before creating browsers.++ (BOOL)initializeWithCachePath:(NSString *)cachePath+ userAgentProduct:(NSString *)product+ logPath:(NSString *)logPath+ useChromeStyle:(BOOL)useChromeStyle;+/// Runs the Chromium-integrated AppKit run loop. Returns after -quitMessageLoop.++ (void)runMessageLoop;++ (void)quitMessageLoop;++ (void)shutdown;+/// Closes every browser, then quits the message loop once they are gone.++ (void)closeAllBrowsersAndQuit;++ (NSInteger)liveBrowserCount;+/// YES when initialize failed because another Cra is running and was told+/// about this launch (exit quietly).++ (BOOL)anotherInstanceWasNotified;+/// Called in the running instance when another launch is handed over.++ (void)setRelaunchHandler:(void (^)(NSArray<NSString *> *urls))handler;++ (NSString *)chromiumVersion;++ (NSString *)cefVersion;+@end++/// NSApplication subclass CEF requires (CefAppProtocol). Set as+/// NSPrincipalClass and created with +sharedApplication before anything else.+@interface CraApplication : NSApplication+@end++NS_ASSUME_NONNULL_ENDdiff --git a/Sources/CraHelper/main.cc b/Sources/CraHelper/main.ccnew file mode 100644index 0000000..31b21be--- /dev/null+++ b/Sources/CraHelper/main.cc@@ -0,0 +1,14 @@+// Entry point for every Chromium subprocess (renderer, GPU, utility, plugin,+// alerts). Loads the framework from the enclosing Cra.app bundle and hands+// control to CEF.+#include "include/cef_app.h"+#include "include/wrapper/cef_library_loader.h"++int main(int argc, char* argv[]) {+ CefScopedLibraryLoader library_loader;+ if (!library_loader.LoadInHelper()) {+ return 1;+ }+ CefMainArgs main_args(argc, argv);+ return CefExecuteProcess(main_args, nullptr, nullptr);+}diff --git a/backend/.gitignore b/backend/.gitignorenew file mode 100644index 0000000..7b5a8b7--- /dev/null+++ b/backend/.gitignore@@ -0,0 +1,2 @@+node_modules/+.env.localdiff --git a/backend/convex/_generated/api.d.ts b/backend/convex/_generated/api.d.tsnew file mode 100644index 0000000..95eb97b--- /dev/null+++ b/backend/convex/_generated/api.d.ts@@ -0,0 +1,55 @@+/* eslint-disable */+/**+ * Generated `api` utility.+ *+ * THIS CODE IS AUTOMATICALLY GENERATED.+ *+ * To regenerate, run `npx convex dev`.+ * @module+ */++import type * as auth from "../auth.js";+import type * as http from "../http.js";+import type * as lib from "../lib.js";+import type * as settings from "../settings.js";++import type {+ ApiFromModules,+ FilterApi,+ FunctionReference,+} from "convex/server";++declare const fullApi: ApiFromModules<{+ auth: typeof auth;+ http: typeof http;+ lib: typeof lib;+ settings: typeof settings;+}>;++/**+ * A utility for referencing Convex functions in your app's public API.+ *+ * Usage:+ * ```js+ * const myFunctionReference = api.myModule.myFunction;+ * ```+ */+export declare const api: FilterApi<+ typeof fullApi,+ FunctionReference<any, "public">+>;++/**+ * A utility for referencing Convex functions in your app's internal API.+ *+ * Usage:+ * ```js+ * const myFunctionReference = internal.myModule.myFunction;+ * ```+ */+export declare const internal: FilterApi<+ typeof fullApi,+ FunctionReference<any, "internal">+>;++export declare const components: {};diff --git a/backend/convex/_generated/api.js b/backend/convex/_generated/api.jsnew file mode 100644index 0000000..44bf985--- /dev/null+++ b/backend/convex/_generated/api.js@@ -0,0 +1,23 @@+/* eslint-disable */+/**+ * Generated `api` utility.+ *+ * THIS CODE IS AUTOMATICALLY GENERATED.+ *+ * To regenerate, run `npx convex dev`.+ * @module+ */++import { anyApi, componentsGeneric } from "convex/server";++/**+ * A utility for referencing Convex functions in your app's API.+ *+ * Usage:+ * ```js+ * const myFunctionReference = api.myModule.myFunction;+ * ```+ */+export const api = anyApi;+export const internal = anyApi;+export const components = componentsGeneric();diff --git a/backend/convex/_generated/dataModel.d.ts b/backend/convex/_generated/dataModel.d.tsnew file mode 100644index 0000000..f97fd19--- /dev/null+++ b/backend/convex/_generated/dataModel.d.ts@@ -0,0 +1,60 @@+/* eslint-disable */+/**+ * Generated data model types.+ *+ * THIS CODE IS AUTOMATICALLY GENERATED.+ *+ * To regenerate, run `npx convex dev`.+ * @module+ */++import type {+ DataModelFromSchemaDefinition,+ DocumentByName,+ TableNamesInDataModel,+ SystemTableNames,+} from "convex/server";+import type { GenericId } from "convex/values";+import schema from "../schema.js";++/**+ * The names of all of your Convex tables.+ */+export type TableNames = TableNamesInDataModel<DataModel>;++/**+ * The type of a document stored in Convex.+ *+ * @typeParam TableName - A string literal type of the table name (like "users").+ */+export type Doc<TableName extends TableNames> = DocumentByName<+ DataModel,+ TableName+>;++/**+ * An identifier for a document in Convex.+ *+ * Convex documents are uniquely identified by their `Id`, which is accessible+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).+ *+ * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.+ *+ * IDs are just strings at runtime, but this type can be used to distinguish them from other+ * strings when type checking.+ *+ * @typeParam TableName - A string literal type of the table name (like "users").+ */+export type Id<TableName extends TableNames | SystemTableNames> =+ GenericId<TableName>;++/**+ * A type describing your Convex data model.+ *+ * This type includes information about what tables you have, the type of+ * documents stored in those tables, and the indexes defined on them.+ *+ * This type is used to parameterize methods like `queryGeneric` and+ * `mutationGeneric` to make them type-safe.+ */+export type DataModel = DataModelFromSchemaDefinition<typeof schema>;diff --git a/backend/convex/_generated/server.d.ts b/backend/convex/_generated/server.d.tsnew file mode 100644index 0000000..f235db4--- /dev/null+++ b/backend/convex/_generated/server.d.ts@@ -0,0 +1,162 @@+/* eslint-disable */+/**+ * Generated utilities for implementing server-side Convex query and mutation functions.+ *+ * THIS CODE IS AUTOMATICALLY GENERATED.+ *+ * To regenerate, run `npx convex dev`.+ * @module+ */++import {+ ActionBuilder,+ HttpActionBuilder,+ MutationBuilder,+ QueryBuilder,+ GenericActionCtx,+ GenericMutationCtx,+ GenericQueryCtx,+ GenericDatabaseReader,+ GenericDatabaseWriter,+} from "convex/server";+import type { DataModel } from "./dataModel.js";++/**+ * Typesafe environment variables.+ *+ * This includes platform-provided env vars and any variables declared in+ * `convex.config.ts`.+ */+type Env = {+ readonly CONVEX_CLOUD_URL: string;+ readonly CONVEX_SITE_URL: string;+};++/**+ * Define a query in this Convex app's public API.+ *+ * This function will be allowed to read your Convex database and will be accessible from the client.+ *+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.+ */+export declare const query: QueryBuilder<DataModel, "public">;++/**+ * Define a query that is only accessible from other Convex functions (but not from the client).+ *+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.+ *+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.+ */+export declare const internalQuery: QueryBuilder<DataModel, "internal">;++/**+ * Define a mutation in this Convex app's public API.+ *+ * This function will be allowed to modify your Convex database and will be accessible from the client.+ *+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.+ */+export declare const mutation: MutationBuilder<DataModel, "public">;++/**+ * Define a mutation that is only accessible from other Convex functions (but not from the client).+ *+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.+ *+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.+ */+export declare const internalMutation: MutationBuilder<DataModel, "internal">;++/**+ * Define an action in this Convex app's public API.+ *+ * An action is a function which can execute any JavaScript code, including non-deterministic+ * code and code with side-effects, like calling third-party services.+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.+ *+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.+ */+export declare const action: ActionBuilder<DataModel, "public">;++/**+ * Define an action that is only accessible from other Convex functions (but not from the client).+ *+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.+ */+export declare const internalAction: ActionBuilder<DataModel, "internal">;++/**+ * Define an HTTP action.+ *+ * The wrapped function will be used to respond to HTTP requests received+ * by a Convex deployment if the requests matches the path and method where+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.+ *+ * @param func - The function. It receives an {@link ActionCtx} as its first argument+ * and a Fetch API `Request` object as its second.+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.+ */+export declare const httpAction: HttpActionBuilder;++/**+ * Typesafe environment variables.+ *+ * This includes platform-provided env vars and any variables declared in+ * `convex.config.ts`.+ */+export declare const env: Env;++/**+ * A set of services for use within Convex query functions.+ *+ * The query context is passed as the first argument to any Convex query+ * function run on the server.+ *+ * This differs from the {@link MutationCtx} because all of the services are+ * read-only.+ */+export type QueryCtx = GenericQueryCtx<DataModel>;++/**+ * A set of services for use within Convex mutation functions.+ *+ * The mutation context is passed as the first argument to any Convex mutation+ * function run on the server.+ */+export type MutationCtx = GenericMutationCtx<DataModel>;++/**+ * A set of services for use within Convex action functions.+ *+ * The action context is passed as the first argument to any Convex action+ * function run on the server.+ */+export type ActionCtx = GenericActionCtx<DataModel>;++/**+ * An interface to read from the database within Convex query functions.+ *+ * The two entry points are {@link DatabaseReader.get}, which fetches a single+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts+ * building a query.+ */+export type DatabaseReader = GenericDatabaseReader<DataModel>;++/**+ * An interface to read from and write to the database within Convex mutation+ * functions.+ *+ * Convex guarantees that all writes within a single mutation are+ * executed atomically, so you never have to worry about partial writes leaving+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)+ * for the guarantees Convex provides your functions.+ */+export type DatabaseWriter = GenericDatabaseWriter<DataModel>;diff --git a/backend/convex/_generated/server.js b/backend/convex/_generated/server.jsnew file mode 100644index 0000000..2dbe0db--- /dev/null+++ b/backend/convex/_generated/server.js@@ -0,0 +1,101 @@+/* eslint-disable */+/**+ * Generated utilities for implementing server-side Convex query and mutation functions.+ *+ * THIS CODE IS AUTOMATICALLY GENERATED.+ *+ * To regenerate, run `npx convex dev`.+ * @module+ */++import {+ actionGeneric,+ httpActionGeneric,+ queryGeneric,+ mutationGeneric,+ internalActionGeneric,+ internalMutationGeneric,+ internalQueryGeneric,+} from "convex/server";++/**+ * Define a query in this Convex app's public API.+ *+ * This function will be allowed to read your Convex database and will be accessible from the client.+ *+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.+ */+export const query = queryGeneric;++/**+ * Define a query that is only accessible from other Convex functions (but not from the client).+ *+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.+ *+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.+ */+export const internalQuery = internalQueryGeneric;++/**+ * Define a mutation in this Convex app's public API.+ *+ * This function will be allowed to modify your Convex database and will be accessible from the client.+ *+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.+ */+export const mutation = mutationGeneric;++/**+ * Define a mutation that is only accessible from other Convex functions (but not from the client).+ *+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.+ *+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.+ */+export const internalMutation = internalMutationGeneric;++/**+ * Define an action in this Convex app's public API.+ *+ * An action is a function which can execute any JavaScript code, including non-deterministic+ * code and code with side-effects, like calling third-party services.+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.+ *+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.+ */+export const action = actionGeneric;++/**+ * Define an action that is only accessible from other Convex functions (but not from the client).+ *+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.+ */+export const internalAction = internalActionGeneric;++/**+ * Define an HTTP action.+ *+ * The wrapped function will be used to respond to HTTP requests received+ * by a Convex deployment if the requests matches the path and method where+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.+ *+ * @param func - The function. It receives an {@link ActionCtx} as its first argument+ * and a Fetch API `Request` object as its second.+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.+ */+export const httpAction = httpActionGeneric;++/**+ * Typesafe environment variables.+ *+ * This includes platform-provided env vars and any variables declared in+ * `convex.config.ts`.+ */+export const env = process.env;diff --git a/backend/convex/auth.ts b/backend/convex/auth.tsnew file mode 100644index 0000000..32f44ec--- /dev/null+++ b/backend/convex/auth.ts@@ -0,0 +1,236 @@+import { v } from "convex/values";+import { internal } from "./_generated/api";+import type { Id } from "./_generated/dataModel";+import { action, internalMutation, internalQuery, mutation, query } from "./_generated/server";+import { createSession, fullName, hashPassword, publicUser, randomHex, splitName, userForToken } from "./lib";++// ─── Email + password ───────────────────────────────────────────────++export const signUp = mutation({+ args: { email: v.string(), password: v.string(), name: v.optional(v.string()), device: v.optional(v.string()) },+ handler: async (ctx, { email, password, name, device }) => {+ const normalizedEmail = email.toLowerCase().trim();+ if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(normalizedEmail)) throw new Error("Enter a valid email address.");+ const existing = await ctx.db.query("users").withIndex("by_email", (q) => q.eq("email", normalizedEmail)).first();+ if (existing) throw new Error("An account with this email already exists.");+ if (password.length < 6) throw new Error("Password must be at least 6 characters.");+ const salt = randomHex(16);+ const passwordHash = await hashPassword(password, salt);+ const parsed = splitName(name);+ const now = Date.now();+ const userId = await ctx.db.insert("users", {+ email: normalizedEmail,+ passwordHash,+ salt,+ name: fullName(parsed.firstName, parsed.lastName),+ firstName: parsed.firstName,+ lastName: parsed.lastName,+ authProvider: "email",+ emailVerified: false,+ createdAt: now,+ lastLoginAt: now,+ });+ const token = await createSession(ctx, userId, device);+ const user = await ctx.db.get(userId);+ return { token, user: publicUser(user) };+ },+});++export const login = mutation({+ args: { email: v.string(), password: v.string(), device: v.optional(v.string()) },+ handler: async (ctx, { email, password, device }) => {+ const normalizedEmail = email.toLowerCase().trim();+ const user = await ctx.db.query("users").withIndex("by_email", (q) => q.eq("email", normalizedEmail)).first();+ if (!user || !user.passwordHash) throw new Error("Invalid email or password.");+ const hash = await hashPassword(password, user.salt);+ if (hash !== user.passwordHash) throw new Error("Invalid email or password.");+ const token = await createSession(ctx, user._id, device);+ return { token, user: publicUser(user) };+ },+});++export const validate = query({+ args: { token: v.string() },+ handler: async (ctx, { token }) => {+ const found = await userForToken(ctx, token);+ return found ? publicUser(found.user) : null;+ },+});++export const touch = mutation({+ args: { token: v.string() },+ handler: async (ctx, { token }) => {+ const found = await userForToken(ctx, token);+ if (found) await ctx.db.patch(found.session._id, { lastSeenAt: Date.now() });+ return found ? publicUser(found.user) : null;+ },+});++export const logout = mutation({+ args: { token: v.string() },+ handler: async (ctx, { token }) => {+ const found = await userForToken(ctx, token);+ if (found) await ctx.db.delete(found.session._id);+ return null;+ },+});++export const checkEmail = query({+ args: { email: v.string() },+ handler: async (ctx, { email }) => {+ const user = await ctx.db.query("users").withIndex("by_email", (q) => q.eq("email", email.toLowerCase().trim())).first();+ return { exists: !!user, provider: user?.authProvider ?? null };+ },+});++// ─── Google ─────────────────────────────────────────────────────────++/** What the native app needs to start Google sign-in (client id is public). */+export const googleConfig = query({+ args: {},+ handler: async () => ({+ clientId: process.env.GOOGLE_CLIENT_ID ?? null,+ configured: !!process.env.GOOGLE_CLIENT_ID && !!process.env.GOOGLE_CLIENT_SECRET,+ }),+});++export const findUserByGoogleId = internalQuery({+ args: { googleId: v.string() },+ handler: async (ctx, { googleId }) =>+ ctx.db.query("users").withIndex("by_googleId", (q) => q.eq("googleId", googleId)).first(),+});++export const findUserByEmail = internalQuery({+ args: { email: v.string() },+ handler: async (ctx, { email }) =>+ ctx.db.query("users").withIndex("by_email", (q) => q.eq("email", email)).first(),+});++export const createGoogleUser = internalMutation({+ args: {+ email: v.string(),+ googleId: v.string(),+ name: v.optional(v.string()),+ firstName: v.optional(v.string()),+ lastName: v.optional(v.string()),+ profileImageUrl: v.optional(v.string()),+ device: v.optional(v.string()),+ },+ handler: async (ctx, args) => {+ const now = Date.now();+ const userId = await ctx.db.insert("users", {+ email: args.email,+ passwordHash: "",+ salt: "",+ name: args.name ?? fullName(args.firstName, args.lastName),+ firstName: args.firstName,+ lastName: args.lastName,+ profileImageUrl: args.profileImageUrl,+ googleId: args.googleId,+ authProvider: "google",+ emailVerified: true,+ createdAt: now,+ lastLoginAt: now,+ });+ const token = await createSession(ctx, userId, args.device);+ return { userId, token };+ },+});++export const linkGoogleAndSession = internalMutation({+ args: {+ userId: v.id("users"),+ googleId: v.string(),+ profileImageUrl: v.optional(v.string()),+ firstName: v.optional(v.string()),+ lastName: v.optional(v.string()),+ device: v.optional(v.string()),+ },+ handler: async (ctx, { userId, googleId, profileImageUrl, firstName, lastName, device }) => {+ const user = await ctx.db.get(userId);+ if (!user) throw new Error("User not found.");+ await ctx.db.patch(userId, {+ googleId,+ emailVerified: true,+ profileImageUrl: user.profileImageUrl ?? profileImageUrl,+ firstName: user.firstName ?? firstName,+ lastName: user.lastName ?? lastName,+ });+ const token = await createSession(ctx, userId, device);+ return token;+ },+});++export const userById = internalQuery({+ args: { userId: v.id("users") },+ handler: async (ctx, { userId }) => ctx.db.get(userId),+});++export async function exchangeGoogleCode(code: string, redirectUri: string) {+ const clientId = process.env.GOOGLE_CLIENT_ID;+ const clientSecret = process.env.GOOGLE_CLIENT_SECRET;+ if (!clientId || !clientSecret) throw new Error("Google OAuth is not configured on the server.");+ const res = await fetch("https://oauth2.googleapis.com/token", {+ method: "POST",+ headers: { "Content-Type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({ code, client_id: clientId, client_secret: clientSecret, redirect_uri: redirectUri, grant_type: "authorization_code" }),+ });+ if (!res.ok) {+ console.error("Google token exchange failed:", await res.text());+ throw new Error("Failed to exchange Google authorization code.");+ }+ const tokens = (await res.json()) as { id_token: string };+ return tokens.id_token;+}++export async function verifyGoogleIdToken(idToken: string) {+ const res = await fetch(`https://oauth2.googleapis.com/tokeninfo?id_token=${encodeURIComponent(idToken)}`);+ if (!res.ok) throw new Error("Invalid Google token.");+ const payload = (await res.json()) as {+ sub: string; email: string; email_verified: string; name?: string; given_name?: string; family_name?: string; picture?: string; aud: string;+ };+ const expected = process.env.GOOGLE_CLIENT_ID;+ if (expected && payload.aud !== expected) throw new Error("Google token audience mismatch.");+ if (payload.email_verified !== "true") throw new Error("Google email is not verified.");+ return {+ googleId: payload.sub,+ email: payload.email.toLowerCase().trim(),+ firstName: payload.given_name,+ lastName: payload.family_name,+ name: payload.name,+ profileImageUrl: payload.picture,+ };+}++/** Find or create the user for a verified Google profile and open a session. */+export async function signInWithGoogleProfile(+ ctx: { runQuery: (fn: any, args: any) => Promise<any>; runMutation: (fn: any, args: any) => Promise<any> },+ profile: { googleId: string; email: string; name?: string; firstName?: string; lastName?: string; profileImageUrl?: string },+ device?: string,+) {+ let user: any = await ctx.runQuery(internal.auth.findUserByGoogleId, { googleId: profile.googleId });+ let token: string;+ if (!user) user = await ctx.runQuery(internal.auth.findUserByEmail, { email: profile.email });+ if (user) {+ token = await ctx.runMutation(internal.auth.linkGoogleAndSession, {+ userId: user._id, googleId: profile.googleId, profileImageUrl: profile.profileImageUrl,+ firstName: profile.firstName, lastName: profile.lastName, device,+ });+ user = await ctx.runQuery(internal.auth.userById, { userId: user._id });+ } else {+ const created = await ctx.runMutation(internal.auth.createGoogleUser, { ...profile, device });+ token = created.token;+ user = await ctx.runQuery(internal.auth.userById, { userId: created.userId as Id<"users"> });+ }+ return { token, user: publicUser(user) };+}++/** Used when the client completed the OAuth code flow itself. */+export const googleLoginWithCode = action({+ args: { code: v.string(), redirectUri: v.string(), device: v.optional(v.string()) },+ handler: async (ctx, { code, redirectUri, device }) => {+ const idToken = await exchangeGoogleCode(code, redirectUri);+ const profile = await verifyGoogleIdToken(idToken);+ return signInWithGoogleProfile(ctx, profile, device);+ },+});diff --git a/backend/convex/http.ts b/backend/convex/http.tsnew file mode 100644index 0000000..ee568de--- /dev/null+++ b/backend/convex/http.ts@@ -0,0 +1,50 @@+import { httpRouter } from "convex/server";+import { httpAction } from "./_generated/server";+import { exchangeGoogleCode, signInWithGoogleProfile, verifyGoogleIdToken } from "./auth";++const http = httpRouter();++function page(title: string, body: string, deepLink?: string) {+ const meta = deepLink ? `<meta http-equiv="refresh" content="0;url=${deepLink}">` : "";+ return `<!doctype html><html><head><meta charset="utf-8">${meta}<title>${title}</title>+<style>html{background:#1c242b;color:#f4f1ea;font:16px -apple-system,system-ui}body{display:flex;min-height:90vh;align-items:center;justify-content:center;margin:0}+main{max-width:420px;padding:32px;text-align:center}h1{font-size:22px;margin:0 0 10px}p{opacity:.75}a{display:inline-block;margin-top:18px;padding:10px 18px;border-radius:10px;background:#6944ae;color:#fff;text-decoration:none;font-weight:600}</style>+</head><body><main><h1>${title}</h1><p>${body}</p>${deepLink ? `<a href="${deepLink}">Open Cra</a>` : ""}</main></body></html>`;+}++// Google redirects here with ?code=… ; we exchange it, open a session and+// hand the result back to the app through the cra:// scheme (same pattern as+// GhostWriter's /google-callback → ghostwriter://auth-callback).+http.route({+ path: "/google-callback",+ method: "GET",+ handler: httpAction(async (ctx, request) => {+ const url = new URL(request.url);+ const code = url.searchParams.get("code");+ const error = url.searchParams.get("error");+ const headers = { "Content-Type": "text/html" };+ if (error) return new Response(page("Sign-in cancelled", "You can close this window."), { status: 400, headers });+ if (!code) return new Response(page("Sign-in failed", "No authorization code received."), { status: 400, headers });+ try {+ const redirectUri = `${url.origin}/google-callback`;+ const idToken = await exchangeGoogleCode(code, redirectUri);+ const profile = await verifyGoogleIdToken(idToken);+ const device = url.searchParams.get("state") ?? undefined;+ const result = await signInWithGoogleProfile(ctx, profile, device);+ const payload = btoa(JSON.stringify(result));+ const deepLink = `cra://auth-callback?data=${encodeURIComponent(payload)}`;+ return new Response(page(`Signed in as ${result.user.name ?? result.user.email}`, "Taking you back to Cra…", deepLink), { status: 200, headers });+ } catch (err) {+ console.error("Google OAuth callback error:", err);+ return new Response(page("Sign-in failed", "Something went wrong. Please try again."), { status: 500, headers });+ }+ }),+});++http.route({+ path: "/health",+ method: "GET",+ handler: httpAction(async () => new Response("ok", { status: 200 })),+});++export default http;diff --git a/backend/convex/lib.ts b/backend/convex/lib.tsnew file mode 100644index 0000000..61f0683--- /dev/null+++ b/backend/convex/lib.ts@@ -0,0 +1,83 @@+import type { Id } from "./_generated/dataModel";+import type { MutationCtx, QueryCtx } from "./_generated/server";++export async function hashPassword(password: string, salt: string): Promise<string> {+ const data = new TextEncoder().encode(salt + password);+ const buf = await crypto.subtle.digest("SHA-256", data);+ return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");+}++export function randomHex(bytes: number): string {+ const arr = new Uint8Array(bytes);+ crypto.getRandomValues(arr);+ return Array.from(arr).map((b) => b.toString(16).padStart(2, "0")).join("");+}++export function splitName(name?: string) {+ const trimmed = name?.trim();+ if (!trimmed) return { firstName: undefined, lastName: undefined };+ const parts = trimmed.split(/\s+/).filter(Boolean);+ if (parts.length === 1) return { firstName: parts[0], lastName: undefined };+ return { firstName: parts[0], lastName: parts.slice(1).join(" ") };+}++export function fullName(firstName?: string, lastName?: string) {+ const combined = `${firstName?.trim() ?? ""} ${lastName?.trim() ?? ""}`.trim();+ return combined || undefined;+}++export type PublicUser = {+ userId: Id<"users">;+ email: string;+ name?: string;+ firstName?: string;+ lastName?: string;+ profileImageUrl?: string;+ isAdmin: boolean;+ emailVerified: boolean;+ authProvider: string;+};++export function publicUser(user: any): PublicUser {+ const legacy = splitName(user.name);+ const firstName = user.firstName ?? legacy.firstName;+ const lastName = user.lastName ?? legacy.lastName;+ return {+ userId: user._id,+ email: user.email,+ name: fullName(firstName, lastName) ?? user.name,+ firstName,+ lastName,+ profileImageUrl: user.profileImageUrl,+ isAdmin: user.isAdmin ?? false,+ emailVerified: user.emailVerified ?? false,+ authProvider: user.authProvider ?? "email",+ };+}++export async function createSession(ctx: MutationCtx, userId: Id<"users">, device?: string) {+ const token = randomHex(32);+ const now = Date.now();+ await ctx.db.insert("sessions", { userId, token, device, createdAt: now, lastSeenAt: now });+ await ctx.db.patch(userId, { lastLoginAt: now });+ return token;+}++/** Resolve a session token to its user, or null. */+export async function userForToken(ctx: QueryCtx | MutationCtx, token: string) {+ if (!token) return null;+ const session = await ctx.db+ .query("sessions")+ .withIndex("by_token", (q) => q.eq("token", token))+ .first();+ if (!session) return null;+ const user = await ctx.db.get(session.userId);+ if (!user) return null;+ return { session, user };+}++export async function requireUser(ctx: QueryCtx | MutationCtx, token: string) {+ const found = await userForToken(ctx, token);+ if (!found) throw new Error("Not signed in.");+ return found;+}diff --git a/backend/convex/schema.ts b/backend/convex/schema.tsnew file mode 100644index 0000000..beef163--- /dev/null+++ b/backend/convex/schema.ts@@ -0,0 +1,52 @@+import { defineSchema, defineTable } from "convex/server";+import { v } from "convex/values";++// Users follow the GhostWriter/Spook shape (email + salted SHA-256 password,+// optional Google identity). Sessions carry a random token so the native app+// never has to treat a user id as a credential.+export default defineSchema({+ users: defineTable({+ email: v.string(),+ passwordHash: v.string(),+ salt: v.string(),+ name: v.optional(v.string()),+ firstName: v.optional(v.string()),+ lastName: v.optional(v.string()),+ profileImageUrl: v.optional(v.string()),+ googleId: v.optional(v.string()),+ authProvider: v.optional(v.string()), // "email" | "google"+ emailVerified: v.optional(v.boolean()),+ isAdmin: v.optional(v.boolean()),+ onboardingCompleted: v.optional(v.boolean()),+ createdAt: v.number(),+ lastLoginAt: v.optional(v.number()),+ })+ .index("by_email", ["email"])+ .index("by_googleId", ["googleId"]),++ sessions: defineTable({+ userId: v.id("users"),+ token: v.string(),+ device: v.optional(v.string()),+ createdAt: v.number(),+ lastSeenAt: v.number(),+ })+ .index("by_token", ["token"])+ .index("by_user", ["userId"]),++ // App preferences synced across devices (auto-archive, search engine...).+ userSettings: defineTable({+ userId: v.id("users"),+ settings: v.any(),+ updatedAt: v.number(),+ }).index("by_user", ["userId"]),++ // Full sidebar backup (spaces, pinned tabs, folders, favorites) per device.+ sidebarBackups: defineTable({+ userId: v.id("users"),+ device: v.string(),+ document: v.any(),+ tabCount: v.number(),+ updatedAt: v.number(),+ }).index("by_user_device", ["userId", "device"]),+});diff --git a/backend/convex/settings.ts b/backend/convex/settings.tsnew file mode 100644index 0000000..116e89d--- /dev/null+++ b/backend/convex/settings.ts@@ -0,0 +1,60 @@+import { v } from "convex/values";+import { mutation, query } from "./_generated/server";+import { requireUser } from "./lib";++export const get = query({+ args: { token: v.string() },+ handler: async (ctx, { token }) => {+ const { user } = await requireUser(ctx, token);+ const row = await ctx.db.query("userSettings").withIndex("by_user", (q) => q.eq("userId", user._id)).first();+ return row ? { settings: row.settings, updatedAt: row.updatedAt } : null;+ },+});++export const set = mutation({+ args: { token: v.string(), settings: v.any() },+ handler: async (ctx, { token, settings }) => {+ const { user } = await requireUser(ctx, token);+ const row = await ctx.db.query("userSettings").withIndex("by_user", (q) => q.eq("userId", user._id)).first();+ const now = Date.now();+ if (row) await ctx.db.patch(row._id, { settings, updatedAt: now });+ else await ctx.db.insert("userSettings", { userId: user._id, settings, updatedAt: now });+ return now;+ },+});++export const backupSidebar = mutation({+ args: { token: v.string(), device: v.string(), document: v.any(), tabCount: v.number() },+ handler: async (ctx, { token, device, document, tabCount }) => {+ const { user } = await requireUser(ctx, token);+ const row = await ctx.db+ .query("sidebarBackups")+ .withIndex("by_user_device", (q) => q.eq("userId", user._id).eq("device", device))+ .first();+ const now = Date.now();+ if (row) await ctx.db.patch(row._id, { document, tabCount, updatedAt: now });+ else await ctx.db.insert("sidebarBackups", { userId: user._id, device, document, tabCount, updatedAt: now });+ return now;+ },+});++export const listBackups = query({+ args: { token: v.string() },+ handler: async (ctx, { token }) => {+ const { user } = await requireUser(ctx, token);+ const rows = await ctx.db.query("sidebarBackups").withIndex("by_user_device", (q) => q.eq("userId", user._id)).collect();+ return rows.map((r) => ({ device: r.device, tabCount: r.tabCount, updatedAt: r.updatedAt }));+ },+});++export const getBackup = query({+ args: { token: v.string(), device: v.string() },+ handler: async (ctx, { token, device }) => {+ const { user } = await requireUser(ctx, token);+ const row = await ctx.db+ .query("sidebarBackups")+ .withIndex("by_user_device", (q) => q.eq("userId", user._id).eq("device", device))+ .first();+ return row ? { document: row.document, updatedAt: row.updatedAt } : null;+ },+});diff --git a/backend/convex/tsconfig.json b/backend/convex/tsconfig.jsonnew file mode 100644index 0000000..c3e97b7--- /dev/null+++ b/backend/convex/tsconfig.json@@ -0,0 +1,18 @@+{+ "compilerOptions": {+ "allowJs": true,+ "strict": true,+ "moduleResolution": "Bundler",+ "jsx": "react-jsx",+ "skipLibCheck": true,+ "allowSyntheticDefaultImports": true,+ "target": "ESNext",+ "lib": ["ES2021", "dom"],+ "forceConsistentCasingInFileNames": true,+ "module": "ESNext",+ "isolatedModules": true,+ "noEmit": true+ },+ "include": ["./**/*"],+ "exclude": ["./_generated"]+}diff --git a/backend/package-lock.json b/backend/package-lock.jsonnew file mode 100644index 0000000..f3ebe62--- /dev/null+++ b/backend/package-lock.json@@ -0,0 +1,546 @@+{+ "name": "cra-backend",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "cra-backend",+ "version": "0.1.0",+ "dependencies": {+ "convex": "^1.31.7"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.0.tgz",+ "integrity": "sha512-KuZrd2hRjz01y5JK9mEBSD3Vj3mbCvemhT466rSuJYeE/hjuBrHfjjcjMdTm/sz7au+++sdbJZJmuBwQLuw68A==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.0.tgz",+ "integrity": "sha512-j67aezrPNYWJEOHUNLPj9maeJte7uSMM6gMoxfPC9hOg8N02JuQi/T7ewumf4tNvJadFkvLZMlAq73b9uwdMyQ==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.0.tgz",+ "integrity": "sha512-CC3vt4+1xZrs97/PKDkl0yN7w8edvU2vZvAFGD16n9F0Cvniy5qvzRXjfO1l94efczkkQE6g1x0i73Qf5uthOQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.0.tgz",+ "integrity": "sha512-wurMkF1nmQajBO1+0CJmcN17U4BP6GqNSROP8t0X/Jiw2ltYGLHpEksp9MpoBqkrFR3kv2/te6Sha26k3+yZ9Q==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.0.tgz",+ "integrity": "sha512-uJOQKYCcHhg07DL7i8MzjvS2LaP7W7Pn/7uA0B5S1EnqAirJtbyw4yC5jQ5qcFjHK9l6o/MX9QisBg12kNkdHg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.0.tgz",+ "integrity": "sha512-8mG6arH3yB/4ZXiEnXof5MK72dE6zM9cDvUcPtxhUZsDjESl9JipZYW60C3JGreKCEP+p8P/72r69m4AZGJd5g==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.0.tgz",+ "integrity": "sha512-9FHtyO988CwNMMOE3YIeci+UV+x5Zy8fI2qHNpsEtSF83YPBmE8UWmfYAQg6Ux7Gsmd4FejZqnEUZCMGaNQHQw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.0.tgz",+ "integrity": "sha512-zCMeMXI4HS/tXvJz8vWGexpZj2YVtRAihHLk1imZj4efx1BQzN76YFeKqlDr3bUWI26wHwLWPd3rwh6pe4EV7g==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.0.tgz",+ "integrity": "sha512-t76XLQDpxgmq2cNXKTVEB7O7YMb42atj2Re2Haf45HkaUpjM2J0UuJZDuaGbPbamzZ7bawyGFUkodL+zcE+jvQ==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.0.tgz",+ "integrity": "sha512-AS18v0V+vZiLJyi/4LphvBE+OIX682Pu7ZYNsdUHyUKSoRwdnOsMf6FDekwoAFKej14WAkOef3zAORJgAtXnlQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.0.tgz",+ "integrity": "sha512-Mz1jxqm/kfgKkc/KLHC5qIujMvnnarD9ra1cEcrs7qshTUSksPihGrWHVG5+osAIQ68577Zpww7SGapmzSt4Nw==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.0.tgz",+ "integrity": "sha512-QbEREjdJeIreIAbdG2hLU1yXm1uu+LTdzoq1KCo4G4pFOLlvIspBm36QrQOar9LFduavoWX2msNFAAAY9j4BDg==",+ "cpu": [+ "loong64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.0.tgz",+ "integrity": "sha512-sJz3zRNe4tO2wxvDpH/HYJilb6+2YJxo/ZNbVdtFiKDufzWq4JmKAiHy9iGoLjAV7r/W32VgaHGkk35cUXlNOg==",+ "cpu": [+ "mips64el"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.0.tgz",+ "integrity": "sha512-z9N10FBD0DCS2dmSABDBb5TLAyF1/ydVb+N4pi88T45efQ/w4ohr/F/QYCkxDPnkhkp6AIpIcQKQ8F0ANoA2JA==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.0.tgz",+ "integrity": "sha512-pQdyAIZ0BWIC5GyvVFn5awDiO14TkT/19FTmFcPdDec94KJ1uZcmFs21Fo8auMXzD4Tt+diXu1LW1gHus9fhFQ==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.0.tgz",+ "integrity": "sha512-hPlRWR4eIDDEci953RI1BLZitgi5uqcsjKMxwYfmi4LcwyWo2IcRP+lThVnKjNtk90pLS8nKdroXYOqW+QQH+w==",+ "cpu": [+ "s390x"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.0.tgz",+ "integrity": "sha512-1hBWx4OUJE2cab++aVZ7pObD6s+DK4mPGpemtnAORBvb5l/g5xFGk0vc0PjSkrDs0XaXj9yyob3d14XqvnQ4gw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.0.tgz",+ "integrity": "sha512-6m0sfQfxfQfy1qRuecMkJlf1cIzTOgyaeXaiVaaki8/v+WB+U4hc6ik15ZW6TAllRlg/WuQXxWj1jx6C+dfy3w==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.0.tgz",+ "integrity": "sha512-xbbOdfn06FtcJ9d0ShxxvSn2iUsGd/lgPIO2V3VZIPDbEaIj1/3nBBe1AwuEZKXVXkMmpr6LUAgMkLD/4D2PPA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.0.tgz",+ "integrity": "sha512-fWgqR8uNbCQ/GGv0yhzttj6sU/9Z5/Sv/VGU3F5OuXK6J6SlriONKrQ7tNlwBrJZXRYk5jUhuWvF7GYzGguBZQ==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.0.tgz",+ "integrity": "sha512-aCwlRdSNMNxkGGqQajMUza6uXzR/U0dIl1QmLjPtRbLOx3Gy3otfFu/VjATy4yQzo9yFDGTxYDo1FfAD9oRD2A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.0.tgz",+ "integrity": "sha512-nyvsBccxNAsNYz2jVFYwEGuRRomqZ149A39SHWk4hV0jWxKM0hjBPm3AmdxcbHiFLbBSwG6SbpIcUbXjgyECfA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.0.tgz",+ "integrity": "sha512-Q1KY1iJafM+UX6CFEL+F4HRTgygmEW568YMqDA5UV97AuZSm21b7SXIrRJDwXWPzr8MGr75fUZPV67FdtMHlHA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.0.tgz",+ "integrity": "sha512-W1eyGNi6d+8kOmZIwi/EDjrL9nxQIQ0MiGqe/AWc6+IaHloxHSGoeRgDRKHFISThLmsewZ5nHFvGFWdBYlgKPg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.0.tgz",+ "integrity": "sha512-30z1aKL9h22kQhilnYkORFYt+3wp7yZsHWus+wSKAJR8JtdfI76LJ4SBdMsCopTR3z/ORqVu5L1vtnHZWVj4cQ==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.0.tgz",+ "integrity": "sha512-aIitBcjQeyOhMTImhLZmtxfdOcuNRpwlPNmlFKPcHQYPhEssw75Cl1TSXJXpMkzaua9FUetx/4OQKq7eJul5Cg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/convex": {+ "version": "1.48.0",+ "resolved": "https://registry.npmjs.org/convex/-/convex-1.48.0.tgz",+ "integrity": "sha512-M9jEgTvCN8ziP/VgQQUH+j0ijM7g+NmQd8tFlvETK8/HMC/aaqHZwcu4hBO30X5DV2VIyYK4mOoLQGIb1766ew==",+ "license": "Apache-2.0",+ "dependencies": {+ "esbuild": "0.27.0",+ "prettier": "^3.0.0",+ "ws": "8.21.0"+ },+ "bin": {+ "convex": "bin/main.js"+ },+ "engines": {+ "node": ">=20.0.0",+ "npm": ">=7.0.0"+ },+ "peerDependencies": {+ "@auth0/auth0-react": "^2.0.1",+ "@clerk/clerk-react": "^4.12.8 || ^5.0.0",+ "@clerk/react": "^6.4.3",+ "react": "^18.0.0 || ^19.0.0-0 || ^19.0.0"+ },+ "peerDependenciesMeta": {+ "@auth0/auth0-react": {+ "optional": true+ },+ "@clerk/clerk-react": {+ "optional": true+ },+ "@clerk/react": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ }+ },+ "node_modules/esbuild": {+ "version": "0.27.0",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.0.tgz",+ "integrity": "sha512-jd0f4NHbD6cALCyGElNpGAOtWxSq46l9X/sWB0Nzd5er4Kz2YTm+Vl0qKFT9KUJvD8+fiO8AvoHhFvEatfVixA==",+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.27.0",+ "@esbuild/android-arm": "0.27.0",+ "@esbuild/android-arm64": "0.27.0",+ "@esbuild/android-x64": "0.27.0",+ "@esbuild/darwin-arm64": "0.27.0",+ "@esbuild/darwin-x64": "0.27.0",+ "@esbuild/freebsd-arm64": "0.27.0",+ "@esbuild/freebsd-x64": "0.27.0",+ "@esbuild/linux-arm": "0.27.0",+ "@esbuild/linux-arm64": "0.27.0",+ "@esbuild/linux-ia32": "0.27.0",+ "@esbuild/linux-loong64": "0.27.0",+ "@esbuild/linux-mips64el": "0.27.0",+ "@esbuild/linux-ppc64": "0.27.0",+ "@esbuild/linux-riscv64": "0.27.0",+ "@esbuild/linux-s390x": "0.27.0",+ "@esbuild/linux-x64": "0.27.0",+ "@esbuild/netbsd-arm64": "0.27.0",+ "@esbuild/netbsd-x64": "0.27.0",+ "@esbuild/openbsd-arm64": "0.27.0",+ "@esbuild/openbsd-x64": "0.27.0",+ "@esbuild/openharmony-arm64": "0.27.0",+ "@esbuild/sunos-x64": "0.27.0",+ "@esbuild/win32-arm64": "0.27.0",+ "@esbuild/win32-ia32": "0.27.0",+ "@esbuild/win32-x64": "0.27.0"+ }+ },+ "node_modules/prettier": {+ "version": "3.9.10",+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.10.tgz",+ "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==",+ "license": "MIT",+ "bin": {+ "prettier": "bin/prettier.cjs"+ },+ "engines": {+ "node": ">=14"+ },+ "funding": {+ "url": "https://github.com/prettier/prettier?sponsor=1"+ }+ },+ "node_modules/ws": {+ "version": "8.21.0",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",+ "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ }+ }+}diff --git a/backend/package.json b/backend/package.jsonnew file mode 100644index 0000000..ec3489c--- /dev/null+++ b/backend/package.json@@ -0,0 +1,14 @@+{+ "name": "cra-backend",+ "private": true,+ "version": "0.1.0",+ "description": "Convex backend for Cra (users, login, settings sync)",+ "scripts": {+ "dev": "convex dev",+ "deploy": "convex deploy",+ "deploy:both": "npx convex deploy && CONVEX_DEPLOYMENT=$(grep CONVEX_DEPLOYMENT .env.local | cut -d= -f2) npx convex dev --once"+ },+ "dependencies": {+ "convex": "^1.31.7"+ }+}diff --git a/brand/README.md b/brand/README.mdnew file mode 100644index 0000000..63e29ad--- /dev/null+++ b/brand/README.md@@ -0,0 +1,31 @@+# Cra brand marks++Chosen 2026-10-24 from the layered explorations. Both marks are built from translucent+ribbons that multiply where they overlap, wrapped in a white sticker edge.++| File | Use |+|---|---|+| `cra-segments.svg` | **Primary mark.** A C cut into four coloured segments. Transparent background: nav, documents, hero. |+| `cra-segments-mono.svg` | Single colour, inherits `currentColor`: footer, sidebar, favicons on busy backgrounds. |+| `cra-segments-icon.svg` | App icon: the mark on the sand tile with a soft shadow. Source for `website/src/app/icon.svg` and the macOS `.icns`. |+| `cra-sticker-c.svg` | **Secondary mark.** A heavy c with a caret dot. Kept for stickers, loading states, small merch. |+| `cra-sticker-c-mono.svg` | Single colour version of the above. |+| `cra-sticker-c-icon.svg` | App icon version of the above. |++## Colours++| Layer | Hex | Where it lands in Segments |+|---|---|---|+| 1 | `#3f6df5` blue | top right, the opening of the C |+| 2 | `#4fbe7e` green | bottom left |+| 3 | `#f0574f` coral | top left |+| 4 | `#f6c34a` yellow | bottom right, and the caret in Sticker c· |+| Tile | `#f2e3c4` to `#e8d3aa` | the sand gradient behind the icon |++Ribbons are drawn at 92% opacity with `mix-blend-mode: multiply`, so overlaps go darker.+On dark backgrounds use normal blending (the site's `LogoMark` does this when `onDark` is set).++## Regenerating++The geometry lives in `website/src/components/site/brand-marks.ts`, written by the same+script that produced these files. Change the colours there and in this file together.diff --git a/brand/cra-segments-icon.svg b/brand/cra-segments-icon.svgnew file mode 100644index 0000000..4bed723--- /dev/null+++ b/brand/cra-segments-icon.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64"><defs><linearGradient id="t" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#f2e3c4"/><stop offset="1" stop-color="#e8d3aa"/></linearGradient></defs><rect width="64" height="64" rx="14.3" fill="url(#t)"/><g transform="translate(3.84 3.84) scale(0.88)"><g opacity=".18" transform="translate(0 2.5)" style="filter:blur(1.5px)"><path d="M23 47.59A18 18 0 0 0 43.08 46.18" fill="none" stroke="#000" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M14.04 30.74A18 18 0 0 0 24.68 48.44" fill="none" stroke="#000" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M25.26 15.31A18 18 0 0 0 14.01 32.63" fill="none" stroke="#000" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M43.08 17.82A18 18 0 0 0 23.55 16.11" fill="none" stroke="#000" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/></g><path d="M23 47.59A18 18 0 0 0 43.08 46.18" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M14.04 30.74A18 18 0 0 0 24.68 48.44" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M25.26 15.31A18 18 0 0 0 14.01 32.63" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M43.08 17.82A18 18 0 0 0 23.55 16.11" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M23 47.59A18 18 0 0 0 43.08 46.18" fill="none" stroke="#f6c34a" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/><path d="M14.04 30.74A18 18 0 0 0 24.68 48.44" fill="none" stroke="#4fbe7e" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/><path d="M25.26 15.31A18 18 0 0 0 14.01 32.63" fill="none" stroke="#f0574f" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/><path d="M43.08 17.82A18 18 0 0 0 23.55 16.11" fill="none" stroke="#3f6df5" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/></g></svg>diff --git a/brand/cra-segments-mono.svg b/brand/cra-segments-mono.svgnew file mode 100644index 0000000..d367e95--- /dev/null+++ b/brand/cra-segments-mono.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" fill="currentColor"><path d="M23 47.59A18 18 0 0 0 43.08 46.18" fill="none" stroke="currentColor" stroke-width="12" stroke-linecap="round" stroke-linejoin="round"/><path d="M14.04 30.74A18 18 0 0 0 24.68 48.44" fill="none" stroke="currentColor" stroke-width="12" stroke-linecap="round" stroke-linejoin="round"/><path d="M25.26 15.31A18 18 0 0 0 14.01 32.63" fill="none" stroke="currentColor" stroke-width="12" stroke-linecap="round" stroke-linejoin="round"/><path d="M43.08 17.82A18 18 0 0 0 23.55 16.11" fill="none" stroke="currentColor" stroke-width="12" stroke-linecap="round" stroke-linejoin="round"/></svg>diff --git a/brand/cra-segments.svg b/brand/cra-segments.svgnew file mode 100644index 0000000..d98bb5f--- /dev/null+++ b/brand/cra-segments.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64"><path d="M23 47.59A18 18 0 0 0 43.08 46.18" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M14.04 30.74A18 18 0 0 0 24.68 48.44" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M25.26 15.31A18 18 0 0 0 14.01 32.63" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M43.08 17.82A18 18 0 0 0 23.55 16.11" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M23 47.59A18 18 0 0 0 43.08 46.18" fill="none" stroke="#f6c34a" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/><path d="M14.04 30.74A18 18 0 0 0 24.68 48.44" fill="none" stroke="#4fbe7e" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/><path d="M25.26 15.31A18 18 0 0 0 14.01 32.63" fill="none" stroke="#f0574f" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/><path d="M43.08 17.82A18 18 0 0 0 23.55 16.11" fill="none" stroke="#3f6df5" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/></svg>diff --git a/brand/cra-sticker-c-icon.svg b/brand/cra-sticker-c-icon.svgnew file mode 100644index 0000000..166e346--- /dev/null+++ b/brand/cra-sticker-c-icon.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64"><defs><linearGradient id="t" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#f2e3c4"/><stop offset="1" stop-color="#e8d3aa"/></linearGradient></defs><rect width="64" height="64" rx="14.3" fill="url(#t)"/><g transform="translate(3.84 3.84) scale(0.88)"><g opacity=".18" transform="translate(0 2.5)" style="filter:blur(1.5px)"><path d="M36.64 22.51A15 15 0 1 0 36.64 45.49" fill="none" stroke="#000" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><circle cx="51" cy="34" r="10.1" fill="#000"/></g><path d="M36.64 22.51A15 15 0 1 0 36.64 45.49" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><circle cx="51" cy="34" r="10.1" fill="#fff"/><path d="M36.64 22.51A15 15 0 1 0 36.64 45.49" fill="none" stroke="#3f6df5" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/><circle cx="51" cy="34" r="6.6" fill="#f6c34a" style="mix-blend-mode:multiply" opacity=".92"/></g></svg>diff --git a/brand/cra-sticker-c-mono.svg b/brand/cra-sticker-c-mono.svgnew file mode 100644index 0000000..19fa1b6--- /dev/null+++ b/brand/cra-sticker-c-mono.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" fill="currentColor"><path d="M36.64 22.51A15 15 0 1 0 36.64 45.49" fill="none" stroke="currentColor" stroke-width="12" stroke-linecap="round" stroke-linejoin="round"/><circle cx="51" cy="34" r="6.6" fill="currentColor"/></svg>diff --git a/brand/cra-sticker-c.svg b/brand/cra-sticker-c.svgnew file mode 100644index 0000000..5e22026--- /dev/null+++ b/brand/cra-sticker-c.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64"><path d="M36.64 22.51A15 15 0 1 0 36.64 45.49" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><circle cx="51" cy="34" r="10.1" fill="#fff"/><path d="M36.64 22.51A15 15 0 1 0 36.64 45.49" fill="none" stroke="#3f6df5" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/><circle cx="51" cy="34" r="6.6" fill="#f6c34a" style="mix-blend-mode:multiply" opacity=".92"/></svg>diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.mdnew file mode 100644index 0000000..9180cc6--- /dev/null+++ b/docs/arc-reverse-engineering.md@@ -0,0 +1,195 @@+# Arc reverse-engineering findings (for Cra)++Target: /Applications/Arc.app, version 1.168.0 (build 88413), bundle id company.thebrowser.Browser, min macOS 13.+Method: REA CLI (rea-agents 6.4.0) `decode-interface-builder`, `inspect-asset-catalog`; `strings` on the arm64 slice;+Arc's own JSON stores in ~/Library/Application Support/Arc; `defaults read company.thebrowser.Browser`.+No Ghidra/IDA/Hopper on this Mac, so no decompiled logic. Nothing below was observed at runtime.++Legend: [O] observed in shipped artifact or data file, [I] inference, [U] unknown.++## Architecture+- [O] Native Swift app. Framework "ARC" with feature modules (CommandBar, SidebarDataStore, StorableSidebar, Archive,+ SpaceStyleEditor, TypeTravel, LittleBrowser, HoverCards...). UI is AppKit: SidebarViewController, SidebarDockViewController,+ NSCollectionView layouts, CommandBarTextField, SuggestionsView.+- [O] Web content is embedded Chromium ("User Data/Default" is a Chrome profile: History, Cookies, Extensions, Preferences).+- [I] So Arc = native chrome + Chromium engine. Cra uses WKWebView instead (design choice, not a copy).++## Sidebar data model (StorableSidebar.json)+- [O] `sidebar.containers` = [ {global}, {spaces, topAppsContainerIDs, items} ]. Lists are flat [id, object, id, object...].+- [O] SpaceModel: id, title, profile, containerIDs = ["pinned", <id>, "unpinned", <id>], customInfo.iconType {emoji_v2, emoji},+ customInfo.windowTheme = blendedGradient { baseColors[2], overlayColors, modifiers{noiseFactor,intensityFactor,overlay:"grain"},+ wheel: analogous|complimentary, translucencyStyle light|dark } with appearanceBased light/dark variants, plus a+ semanticColorPalette (foregroundPrimary/Secondary/Tertiary, backgroundExtra, maxContrastColor...).+- [O] SidebarItem: id, parentID, title (null unless user renamed; custom title overrides page title), childrenIds[], isUnread,+ createdAt, originatingDevice, data = one of+ - tab { savedURL, savedTitle, savedMuteStatus, timeLastActiveAt, activeTabBeforeCreationID, referrerID?, liveItemID? }+ - list {} = folder (optional customInfo.iconType; optional automaticLiveFolderData for GitHub live folders)+ - itemContainer { containerType: topApps{profile} | spaceItems{spaceID} }+ - [O strings only] easel, splitView, arcDocument, tabGroup also exist.+- [O] Favorites = the "topApps" container, one per profile, shared by all spaces (StorableSidebar.topAppsContainerIDs).+- [O] Every space owns one pinned container and one unpinned ("Today") container; ordering = childrenIds; folders nest via parentID.+- [O] A pinned tab keeps savedURL/savedTitle as its home; strings: resetTab, resetCurrentTab, replacePinnedTab,+ PinnedTabNavigationProfile, renamePinnedTabsEnabled=1.+- [O] Section chrome: UnpinnedSectionDivider/Header (the line between pinned and Today), SidebarClearButton,+ SidebarTidyButton, SidebarPlusButton (new tab button with menu: newTab/newFolder/newEasel/newNote/newSpace),+ PinnedSectionExpansionState, spacesWithCollapsedPinnedSections.++## Window state (StorableWindows.json)+- [O] sidebarWidth 328, sidebarMode "anchored" (binary also has floating, hidden, collapsed), focusedSpaceID, lastFocusedSpaceID,+ expandedItems (folder expansion, per window), itemLastActiveDates, itemCreatedDates, splitViewState, windowContents.++## Spaces+- [O] SidebarDock = space switcher at the bottom (icons/emoji, tooltip), SidebarPagingContainer = horizontal paging between spaces,+ SpaceCreation view, SpaceStyleEditor (color pad, dial, color picker), SpaceIconPicker (emoji), SpaceManagement (reorder),+ focusNextSpace/previous, LinkRouting rules (URL match -> space or Little Arc), per-space profile.++## Archive (StorableArchiveItems.json)+- [O] { archivedAt, reason: manual|auto, source: space{id}|littleArc|standaloneSidebar|unknown, sidebarItem: <copy> }.+- [O] Auto-archive thresholds enum: twelveHours, twentyFourHours, sevenDays, thirtyDays (this Mac: sevenDays, per profile).+- [O] Actions: viewArchive, clearArchive, reopenClosedTab, resetSpace, archiveTab.++## Command bar (ARC_CommandBar.bundle + strings + StorableCommandBarAdditionalRanking.json)+- [O] Entry points: keyboardShortcutT, keyboardShortcutL, keyboardShortcutFocusSidebar, keyboardShortcutCommandOptionG,+ sidebarDoubleClick, sidebarNewTabButton, placeholderClick, littleArcPlaceholderClick, topbar, appMenu*,+ toggleBetweenTypeTravelAndCommandBar.+- [O] Result archetypes: tab (switch to open tab; carries customTitle), chromiumHistory, chromiumSearchWhatYouTyped,+ chromiumSearchSuggestion, chromiumNavigateWhatYouTyped, chromiumSearchHistory, chromiumNavigateSuggestion, chromiumBookmark,+ chromiumSearchOtherEngine, chromiumSearchCalculatorAnswer, topDomain (bundled popularDomains.json), typeTravel+ (menuItem:<id>, focusSpace:<id>, moveToFolder:<id>, openFolder<id>, webContentExtension:<name>), askGPTWhatYouTyped,+ siteSearch (scoped pill), staticQuerySuggestions.+- [O] Ranking signals: recentlySwitchedToTabs (last 10 switch times per tab), queriesToSelectedArchetype (typed prefix ->+ what the user picked, i.e. it learns), typeTravelUsage (frequency + last 15 executions), siteEngagementScore,+ fuzzySearchConfidence, hotWords match %, title/url match % and position, recency, importance, customTitlePrefix boost,+ veryRecentTabOrDocumentBoost, derankCurrentItemURL, dedupByTitleAndHostList (figma, notion, github, zoom...).+- [O] Type-travel triggers e.g. "Go to Sidebar Item 3" / "3. tab" / "3. item".+- [U] Weights of the ranking model (a CoreML tensor, CommandBarRankingTensor) are not recoverable statically.++## Key bindings (StorableKeyBindings.json + strings)+- [O] Action = {identifier, name}; binding = {keyEquivalent, deviceIndependentModifierFlags}, priority, typeTravelTriggers;+ user overrides persisted. item1..item9 = "Go to Sidebar Item N" with flags 1048576 (= Command).+- [O] Action identifiers: newTab, newWindow, newBlankWindow, newSpace, newFolder, newEasel, newNote, closeWindow, archiveTab,+ reopenClosedTab, pinTab, rename, duplicate, resetTab, addressBar, typeTravel, toggleSidebar, showSidebar, focusSidebar,+ toggleToolbar, focusNextSpace, nextTab, previousTab, selectNextTab, cycleNextTab, cycleTabForward, goBack, goForward,+ reloadPage, forceReloadPage, stopLoading, findNext, findPrevious, findAndReplace, zoomIn, zoomOut, resetZoom, fullscreen,+ readerMode, copyCurrentURL, viewArchive, clearArchive, viewHistory, viewDownloads, viewLibrary, viewPreferences,+ developerTools, inspectElements, viewSource, printPage, savePageAs, capturePage, captureFullPage, showLittleArc, peekEmail,+ addSplitView, removeSplitView, muteAllTabs, resetSpace, clearCookies, openTabIn, gptMessage, hideArc, hideOthers, minimize,+ quitArc, moveToSpace, moveToTopApps, removeFromTopApps, replacePinnedTab, renameCurrentTab, duplicateCurrentTab.+- [O] Default key equivalents read from the running Arc's menu bar through Accessibility (AXMenuItemCmdChar/+ AXMenuItemCmdModifiers, 24 Oct 2026). File: New Tab ⌘T, New Window ⌘N, Blank Window ⌃⌘N, New Incognito Window ⇧⌘N,+ New Little Arc Window ⌥⌘N, Restore Last Closed Tab ⇧⌘T, Open Command Bar ⌘L, New Easel ⌃⇧E, Close Window ⇧⌘W,+ Close Tab ⌘W, Capture ⇧⌘2, Save Page As ⇧⌘S, Print ⌘P. Edit: Copy URL ⇧⌘C, Copy URL as Markdown ⇧⌥⌘C,+ Copy URL as Quote ⌃⇧⌘C, Paste and Match Style ⇧⌘V, Find ⌘F, Find and Replace ⌥⌘F, Find Next ⌘G, Find Previous ⇧⌘G,+ Jump to Selection ⌘J. View: Hide Sidebar ⌘S, Hide Toolbar ⇧⌘D, Stop Loading ⌘., Refresh ⌘R, Force Refresh ⇧⌘R,+ Add Split View ⌃⇧=, Close Split Pane ⌃⇧-, Zoom Actual ⌘0, Zoom In ⌘+, Zoom Out ⌘-, View Source ⌥⌘U,+ Developer Tools ⌥⌘I, Inspect Elements ⌥⌘C, JavaScript Console ⌥⌘J, Enter Full Screen ⌃⌘F. Spaces: Next ⌥⌘→,+ Previous ⌥⌘←, space N ⌃N. Tabs: Pin/Unpin ⌘D, Next Tab ⌥⌘↓, Previous Tab ⌥⌘↑, Clear Today ⇧⌘K, Go to Tab N ⌘N,+ Toggle recent tabs ⌃Tab. Archive: Go Back ⌘[ (shown as ⌘Æ on a Danish layout) / ⌘←, Go Forward ⌘] / ⌘→,+ View History ⌘Y. Window: Minimize ⌘M, Open Library ⇧⌘L, View Downloads ⇧⌘J.++## Visual reference (Arc 1.168, measured at 2x from window captures)+- [O] Sidebar 328pt wide. Row 1: traffic lights, sidebar toggle right after them (~93pt), nav ← → ↻ right-aligned when a+ tab is selected and the toolbar shows the URL; with no tab the nav moves into the toolbar and the toolbar shows a+ centered "Search or Enter URL…". Favorites: 4 tiles, ~44pt tall, active tile gets a dashed outline. Space header: emoji ++ name, 13pt medium, secondary color. Rows 40pt pitch, 14pt titles, 16pt favicons, custom-titled/navigated pinned tabs show+ the host as an 11pt second line, folders use a blue folder glyph, nested rows indent ~18pt. Bottom row: library icon+ left, tiny space emoji centered (inactive dimmed), + right.+- [O] Content: rounded card inset ~8-10pt with the toolbar strip (42pt: lock + monospaced URL, copy link, extensions,+ capture, DevTools, sidebar toggle) on top; no card at all when no tab is selected.+- [O] Command bar: ~766pt wide, vertically centered, dark translucent in dark mode. Input row 60pt with the top match's+ favicon; rows 50pt single-line "Title — url"; the completion row comes first, then the typed query, then matches; open+ tabs show "Switch to Tab" + arrow box (other-space tabs show the space name); the selected row is tinted with the+ space color. ⌘L with the toolbar visible edits inline: dropdown hangs under the toolbar across the content width.++## Dia 1.54 (company.thebrowser.dia)+- [O] ~/Library/Application Support/Dia/StorableProfileContainers.json: containers per profile with `window` or+ `favorites` kinds; tabs[].contents[].variant = webContent{_0:{title,url}} | newTabPage. StorableAutoArchive.json:+ containers[].archivedTabs (empty here). Chromium profile at User Data/Profile 7 with Bookmarks whose bookmark-bar+ folders mirror Arc spaces ("Favorites", "Victor", "JYSK").++## Other observed features (not in Cra's first scope)+- Little Arc (LittleBrowser), Peek, Easels, Boosts, split view, hover cards, site control center, sidebar banners,+ sync via CloudKit + Firebase, Chromium extensions, "Tidy", Ask Arc.++## Rendering recipe fitted to Victor's Arc captures (24 Oct 2026)+- [O] Light "Victor" theme (isVibrant, intensity 0.25) renders as #93926A–#AA9470 on this desktop: gradient at 25% over the+ blurred desktop. Cra reproduces it with a behind-window NSVisualEffectView, a 22% white lift and gradient alpha = intensity.+- [O] Dark "JYSK" theme renders #292538 from base #01021F/#1A001F: about 27% of the colour over #2B2632.+- [O] Toolbar strip = first theme colour at 46% (#72601D), URL #E4E0D4 12pt monospaced starting 40pt from the card edge.+- [O] Title row centre 24pt (traffic lights at x 19/43/67, sidebar toggle at 93, nav ← → ↻⌄ at 236/270/299/314).+ Favorites tiles 70×47 with 8pt gaps, first row at y≈45. Space header centre y≈118, rows 41pt pitch, favicon centre x=26,+ text x=45. With no tab selected the content area is a faintly lighter card with a 40pt toolbar strip and a hairline.++## Calibration update, 24 Oct 2026 (afternoon)++Method that finally worked: put a full-screen solid window (white, then black) directly+behind each browser, capture the same screen region, and fit per channel+`out = c + k · backdrop`. `screencapture` output samples as sRGB (a solid #72601D window+reads back as #72601D), so no P3 conversion is needed. Window-id captures (`-l`) show+Arc's sidebar without its backdrop (equal to its inactive look) and include the window+shadow unless `-o` is passed.++Measured on the "Victor" theme (Arc base #F8D558 / #A4F454, overlay → #FF7567, intensity 0.25):++| | over white | over black |+|---|---|---|+| Arc sidebar, top | 206 200 160 | 124 118 77 |+| Arc sidebar, bottom | 212 181 141 | 154 124 82 |+| Cra (final) top | 199 192 152 | 124 117 76 |+| Cra (final) bottom | 213 184 142 | 154 125 82 |++Cra's recipe for light vibrant themes: `NSVisualEffectView` `.hudWindow`, dark appearance,+`state` driven explicitly from app activation (`.active` / `.inactive`; the key-window+heuristic left the blur half flat), no white lift while active, 0.75 lift while inactive.+Gradient top → bottom, stop opacity `intensity·1.8 → intensity·2.33`; stops from the Arc+theme: top = mix(mix(base0, base1, 0.15), white, 0.30), bottom =+mix(mix(base0, overlayEnd ?? base1, 0.30), white, 0.20). Over a dark backdrop Cra is within+2/255 of Arc at every height; over pure white the top is 7–8 darker (the HUD material+passes ~55 % of the backdrop, Arc's blur a little more). Dark vibrant themes keep the+earlier `.underWindowBackground` + 15 % lift calibration.++Toolbar band is opaque and theme-derived (same colour over any backdrop):+light = HSB(h, s + 0.10, v · 0.46) of the raw base colour (#F8D558 → #725F1D; Arc #72601D),+dark = HSB(h, s · 0.6, v · 0.8) (#010220 → #0A0B19; Arc #0E0B16). Pages with a+`theme-color` meta use that colour instead (Kildash #1A1917, Messenger white).++Other measured details: window buttons are muted grey discs (bg −10 %) until the pointer+reaches the sidebar's title row; favicons 16 pt centred 25.75 pt from the window edge; space+header 14 pt medium with no top padding above it; favorites tiles 72 × 47 with 8 pt margins+and gaps; the yellow/black dashed ring (2 pt, systemYellow, 6/6 black dashes) is Arc's+keyboard-focus indicator, shown on a tab chosen without the mouse (it appeared on every+tab selected through AppleScript, never on clicked ones). Host subtitles under pinned+tabs appear only when the tab left the pinned host (Phantom at /signin shows none); the+"Ahrefs / ahrefs.com" row in Arc stays unexplained (same host, same URL, loaded).++### DevTools docking (CEF 154 note)++`ShowDevTools` with a `SetAsChild` window info (which forces Alloy style on macOS) hits a+CHECK inside CEF 154 regardless of the parent view (tested with the real host and with a+hidden temp window). An Alloy-style top-level DevTools window works, so Cra creates that+hidden (`windowInfo.hidden`), then attaches CEF's window as a borderless child window over+the dock area and keeps its frame in sync from `ShellView.layoutContentChildren`. Moving the+DevTools NSView into Cra's window would be unsafe: CEF closes `view.window` when DevTools+closes.++### Measuring while the Mac is in use (lessons)++A TCC prompt left behind by a Cra instance launched from the agent's shell blocked every+GUI helper spawned from that shell (they never reached `applicationDidFinishLaunching`),+which silently invalidated three colour runs; `killall UserNotificationCenter` cleared it.+Run the app from ~/Applications (scripts/build.sh installs there) so no prompt appears.+Animations were verified with `screencapture -V` recordings and a per-frame difference+tool: space switch 11 consecutive 60 Hz frames, sidebar hide 10 frames with a fast start+and soft landing, command bar fade-in 7 frames; the 80 ms fade-out still lands in one frame.++### DevTools dock, final shape (24 Oct, evening)++Arc shows Chrome's docked DevTools (close button, device toggle, rounded card corner).+In CEF 154 the docked frontend (`can_dock=true`) reserves a 150 px "inspected page"+placeholder inside its own window and, after a second navigation, loses its target+connection (empty Elements panel, blue toolbar). Cra therefore keeps the undocked frontend+(fills the pane, stays connected) and injects a plain HTML close button after the ⋮ menu in+the main toolbar; that button and `InspectorFrontendHost.closeWindow()` reach the shell as a+console message, which calls `CloseDevTools()`. The CEF window is non-opaque with its right+corners masked to the card radius. Still missing versus Arc: the device-mode toggle, which+the frontend only offers when it can dock.diff --git a/resources/AppIcon.icns b/resources/AppIcon.icnsnew file mode 100644index 0000000..c0e225fBinary files /dev/null and b/resources/AppIcon.icns differdiff --git a/resources/Helper-Info.plist b/resources/Helper-Info.plistnew file mode 100644index 0000000..7605654--- /dev/null+++ b/resources/Helper-Info.plist@@ -0,0 +1,30 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleDisplayName</key>+ <string>Cra Helper__NAME_SUFFIX__</string>+ <key>CFBundleExecutable</key>+ <string>Cra Helper__NAME_SUFFIX__</string>+ <key>CFBundleIdentifier</key>+ <string>dk.kildahl.cra.helper__PLIST_SUFFIX__</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>Cra Helper__NAME_SUFFIX__</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>__VERSION__</string>+ <key>CFBundleVersion</key>+ <string>__BUILD__</string>+ <key>LSMinimumSystemVersion</key>+ <string>14.0</string>+ <key>LSUIElement</key>+ <true/>+ <key>NSSupportsAutomaticGraphicsSwitching</key>+ <true/>+</dict>+</plist>diff --git a/resources/Info.plist b/resources/Info.plistnew file mode 100644index 0000000..2add35e--- /dev/null+++ b/resources/Info.plist@@ -0,0 +1,92 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleExecutable</key>+ <string>Cra</string>+ <key>CFBundleIdentifier</key>+ <string>dk.kildahl.cra</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>Cra</string>+ <key>CFBundleDisplayName</key>+ <string>Cra</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>__VERSION__</string>+ <key>CFBundleVersion</key>+ <string>__BUILD__</string>+ <key>CFBundleIconFile</key>+ <string>AppIcon</string>+ <key>LSMinimumSystemVersion</key>+ <string>14.0</string>+ <key>LSApplicationCategoryType</key>+ <string>public.app-category.productivity</string>+ <key>NSPrincipalClass</key>+ <string>CraApplication</string>+ <key>NSHighResolutionCapable</key>+ <true/>+ <key>NSSupportsAutomaticGraphicsSwitching</key>+ <true/>+ <key>NSCameraUsageDescription</key>+ <string>Web sites you visit can ask to use the camera.</string>+ <key>NSMicrophoneUsageDescription</key>+ <string>Web sites you visit can ask to use the microphone.</string>+ <key>NSLocationUsageDescription</key>+ <string>Web sites you visit can ask for your location.</string>+ <key>CFBundleURLTypes</key>+ <array>+ <dict>+ <key>CFBundleTypeRole</key>+ <string>Viewer</string>+ <key>CFBundleURLName</key>+ <string>Web site URL</string>+ <key>CFBundleURLSchemes</key>+ <array>+ <string>http</string>+ <string>https</string>+ </array>+ </dict>+ <dict>+ <key>CFBundleTypeRole</key>+ <string>Editor</string>+ <key>CFBundleURLName</key>+ <string>Cra internal</string>+ <key>CFBundleURLSchemes</key>+ <array>+ <string>cra</string>+ </array>+ </dict>+ </array>+ <key>CFBundleDocumentTypes</key>+ <array>+ <dict>+ <key>CFBundleTypeName</key>+ <string>HTML document</string>+ <key>CFBundleTypeRole</key>+ <string>Viewer</string>+ <key>LSItemContentTypes</key>+ <array>+ <string>public.html</string>+ </array>+ </dict>+ </array>+ <key>UTExportedTypeDeclarations</key>+ <array>+ <dict>+ <key>UTTypeIdentifier</key>+ <string>dk.kildahl.cra.sidebar-item</string>+ <key>UTTypeDescription</key>+ <string>Cra sidebar item</string>+ <key>UTTypeConformsTo</key>+ <array>+ <string>public.data</string>+ </array>+ </dict>+ </array>+</dict>+</plist>diff --git a/resources/brand/cra-mark-mono.png b/resources/brand/cra-mark-mono.pngnew file mode 100644index 0000000..ce168bfBinary files /dev/null and b/resources/brand/cra-mark-mono.png differdiff --git a/resources/brand/cra-mark.png b/resources/brand/cra-mark.pngnew file mode 100644index 0000000..45d9ef0Binary files /dev/null and b/resources/brand/cra-mark.png differdiff --git a/resources/brand/cra-mark.svg b/resources/brand/cra-mark.svgnew file mode 100644index 0000000..d98bb5f--- /dev/null+++ b/resources/brand/cra-mark.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64"><path d="M23 47.59A18 18 0 0 0 43.08 46.18" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M14.04 30.74A18 18 0 0 0 24.68 48.44" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M25.26 15.31A18 18 0 0 0 14.01 32.63" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M43.08 17.82A18 18 0 0 0 23.55 16.11" fill="none" stroke="#fff" stroke-width="19" stroke-linecap="round" stroke-linejoin="round"/><path d="M23 47.59A18 18 0 0 0 43.08 46.18" fill="none" stroke="#f6c34a" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/><path d="M14.04 30.74A18 18 0 0 0 24.68 48.44" fill="none" stroke="#4fbe7e" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/><path d="M25.26 15.31A18 18 0 0 0 14.01 32.63" fill="none" stroke="#f0574f" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/><path d="M43.08 17.82A18 18 0 0 0 23.55 16.11" fill="none" stroke="#3f6df5" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" style="mix-blend-mode:multiply" opacity=".92"/></svg>diff --git a/resources/brand/[email protected] b/resources/brand/[email protected]new file mode 100644index 0000000..3ebcff2Binary files /dev/null and b/resources/brand/[email protected] differdiff --git a/scripts/build.sh b/scripts/build.shnew file mode 100755index 0000000..84fc546--- /dev/null+++ b/scripts/build.sh@@ -0,0 +1,71 @@+#!/bin/bash+# Builds Cra.app into build/Cra.app.+# scripts/build.sh release build+# scripts/build.sh debug debug build+set -euo pipefail+cd "$(dirname "$0")/.."+ROOT="$PWD"+CONFIG="${1:-release}"+VERSION="${CRA_VERSION:-0.1.0}"+BUILD_NUMBER="${CRA_BUILD:-$(date +%Y%m%d%H%M)}"++scripts/fetch-cef.sh++swift build -c "$CONFIG"+BIN="$(swift build -c "$CONFIG" --show-bin-path)"++# Stage the bundle, then sync it into place so the existing Cra.app directory+# keeps its identity (LaunchServices otherwise launches duplicate instances).+FINAL_APP="$ROOT/build/Cra.app"+STAGE="$(mktemp -d /tmp/cra-stage.XXXXXX)"+APP="$STAGE/Cra.app"+mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" "$APP/Contents/Frameworks"++cp "$BIN/Cra" "$APP/Contents/MacOS/Cra"+sed -e "s/__VERSION__/$VERSION/" -e "s/__BUILD__/$BUILD_NUMBER/" resources/Info.plist > "$APP/Contents/Info.plist"+echo -n "APPL????" > "$APP/Contents/PkgInfo"+[ -f resources/AppIcon.icns ] && cp resources/AppIcon.icns "$APP/Contents/Resources/AppIcon.icns"+[ -d resources/web ] && cp -R resources/web "$APP/Contents/Resources/web"+[ -d resources/brand ] && cp -R resources/brand "$APP/Contents/Resources/brand"++FRAMEWORK_SRC="$ROOT/vendor/cef/Release/Chromium Embedded Framework.framework"+cp -R "$FRAMEWORK_SRC" "$APP/Contents/Frameworks/"++# CEF needs one helper app per process type (see cef_variables.cmake,+# CEF_HELPER_APP_SUFFIXES). Format: "<name suffix>|<plist suffix>".+for entry in "|" " (Alerts)|.alerts" " (GPU)|.gpu" " (Plugin)|.plugin" " (Renderer)|.renderer"; do+ NAME_SUFFIX="${entry%%|*}"+ PLIST_SUFFIX="${entry#*|}"+ HELPER="$APP/Contents/Frameworks/Cra Helper${NAME_SUFFIX}.app"+ mkdir -p "$HELPER/Contents/MacOS"+ cp "$BIN/CraHelper" "$HELPER/Contents/MacOS/Cra Helper${NAME_SUFFIX}"+ sed -e "s/__NAME_SUFFIX__/${NAME_SUFFIX}/g" -e "s/__PLIST_SUFFIX__/${PLIST_SUFFIX}/g" \+ -e "s/__VERSION__/$VERSION/" -e "s/__BUILD__/$BUILD_NUMBER/" \+ resources/Helper-Info.plist > "$HELPER/Contents/Info.plist"+ echo -n "APPL????" > "$HELPER/Contents/PkgInfo"+done++# Ad-hoc signatures, innermost first.+FW="$APP/Contents/Frameworks/Chromium Embedded Framework.framework"+find "$FW/Libraries" -name '*.dylib' -exec codesign --force --sign - {} \; 2>/dev/null || true+codesign --force --sign - "$FW"+for h in "$APP"/Contents/Frameworks/*.app; do codesign --force --sign - "$h"; done+codesign --force --sign - "$APP"++LSREGISTER=/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister+mkdir -p "$FINAL_APP"+rsync -a --delete "$APP/" "$FINAL_APP/"+"$LSREGISTER" -u "$APP" >/dev/null 2>&1 || true+rm -rf "$STAGE"+"$LSREGISTER" -f "$FINAL_APP" || true+echo "Built $FINAL_APP"++# Install outside ~/Documents: an app that runs from Documents makes macOS ask for+# folder access and blocks the main thread until answered. The installed copy is the+# one LaunchServices opens for cra:// URLs.+INSTALL_APP="${CRA_INSTALL_DIR:-$HOME/Applications}/Cra.app"+mkdir -p "$(dirname "$INSTALL_APP")"+rsync -a --delete "$FINAL_APP/" "$INSTALL_APP/"+"$LSREGISTER" -u "$FINAL_APP" >/dev/null 2>&1 || true+"$LSREGISTER" -f "$INSTALL_APP" >/dev/null 2>&1 || true+echo "Installed $INSTALL_APP"diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.shnew file mode 100755index 0000000..c0f6bf7--- /dev/null+++ b/scripts/fetch-cef.sh@@ -0,0 +1,30 @@+#!/bin/bash+# Downloads the pinned CEF binary distribution into vendor/cef and builds the+# C++ wrapper library. Safe to re-run; skips what is already there.+set -euo pipefail+cd "$(dirname "$0")/.."++CEF_VERSION="${CEF_VERSION:-154.0.34+g14c5a08+chromium-154.0.8037.98}"+ARCH="${CEF_ARCH:-macosarm64}"+NAME="cef_binary_${CEF_VERSION}_${ARCH}_minimal"+URL="https://cef-builds.spotifycdn.com/${NAME}.tar.bz2"++mkdir -p vendor+if [ ! -d vendor/cef/Release ]; then+ echo "Downloading ${NAME} (about 130 MB)..."+ mkdir -p vendor/cef-download+ curl -fL --progress-bar -o "vendor/cef-download/${NAME}.tar.bz2" "$URL"+ tar -xjf "vendor/cef-download/${NAME}.tar.bz2" -C vendor/cef-download+ rm -rf vendor/cef+ mv "vendor/cef-download/${NAME}" vendor/cef+ rm -rf vendor/cef-download+fi++if [ ! -f vendor/cef/build/libcef_dll_wrapper/libcef_dll_wrapper.a ]; then+ echo "Building libcef_dll_wrapper..."+ cmake -S vendor/cef -B vendor/cef/build -G "Unix Makefiles" \+ -DCMAKE_BUILD_TYPE=Release -DPROJECT_ARCH=arm64 -DUSE_SANDBOX=OFF \+ -DCMAKE_OSX_ARCHITECTURES=arm64 > vendor/cef/build-configure.log+ cmake --build vendor/cef/build --target libcef_dll_wrapper -j "$(sysctl -n hw.ncpu)" > vendor/cef/build-wrapper.log+fi+echo "CEF ready: vendor/cef"diff --git a/scripts/make-icon.swift b/scripts/make-icon.swiftnew file mode 100644index 0000000..151fb70--- /dev/null+++ b/scripts/make-icon.swift@@ -0,0 +1,58 @@+// Renders the Cra app icon: the default space gradient with a reversed "C"+// (Arc reversed), and writes resources/AppIcon.icns via iconutil.+import Cocoa++func render(_ size: CGFloat) -> NSImage {+ let img = NSImage(size: NSSize(width: size, height: size))+ img.lockFocus()+ let r = NSRect(x: 0, y: 0, width: size, height: size)+ let inset = size * 0.08+ let path = NSBezierPath(roundedRect: r.insetBy(dx: inset, dy: inset), xRadius: size * 0.2, yRadius: size * 0.2)+ let g = NSGradient(colors: [NSColor(hex: "#F8D558"), NSColor(hex: "#A4F554")])!+ g.draw(in: path, angle: -55)+ // Reversed C: an arc open to the left.+ let stroke = NSBezierPath()+ let c = NSPoint(x: size * 0.47, y: size * 0.5)+ stroke.appendArc(withCenter: c, radius: size * 0.24, startAngle: 130, endAngle: -130, clockwise: true)+ stroke.lineWidth = size * 0.13+ stroke.lineCapStyle = .round+ NSColor.white.withAlphaComponent(0.92).setStroke()+ let shadow = NSShadow()+ shadow.shadowColor = NSColor.black.withAlphaComponent(0.18)+ shadow.shadowBlurRadius = size * 0.03+ shadow.shadowOffset = NSSize(width: 0, height: -size * 0.015)+ shadow.set()+ stroke.stroke()+ img.unlockFocus()+ return img+}++extension NSColor {+ convenience init(hex: String) {+ var s = hex; s.removeFirst()+ let v = UInt32(s, radix: 16)!+ self.init(srgbRed: CGFloat((v >> 16) & 0xff) / 255, green: CGFloat((v >> 8) & 0xff) / 255, blue: CGFloat(v & 0xff) / 255, alpha: 1)+ }+}++let out = CommandLine.arguments[1]+let set = out + "/AppIcon.iconset"+try? FileManager.default.removeItem(atPath: set)+try! FileManager.default.createDirectory(atPath: set, withIntermediateDirectories: true)+for (name, px) in [("icon_16x16", 16), ("icon_16x16@2x", 32), ("icon_32x32", 32), ("icon_32x32@2x", 64), ("icon_128x128", 128),+ ("icon_128x128@2x", 256), ("icon_256x256", 256), ("icon_256x256@2x", 512), ("icon_512x512", 512), ("icon_512x512@2x", 1024)] {+ let img = render(CGFloat(px))+ let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: px, pixelsHigh: px, bitsPerSample: 8, samplesPerPixel: 4,+ hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!+ NSGraphicsContext.saveGraphicsState()+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)+ img.draw(in: NSRect(x: 0, y: 0, width: px, height: px))+ NSGraphicsContext.restoreGraphicsState()+ try! rep.representation(using: .png, properties: [:])!.write(to: URL(fileURLWithPath: "\(set)/\(name).png"))+}+let task = Process()+task.launchPath = "/usr/bin/iconutil"+task.arguments = ["-c", "icns", set, "-o", out + "/AppIcon.icns"]+task.launch(); task.waitUntilExit()+try? FileManager.default.removeItem(atPath: set)+print("wrote \(out)/AppIcon.icns")diff --git a/scripts/run.sh b/scripts/run.shnew file mode 100755index 0000000..c2819c5--- /dev/null+++ b/scripts/run.sh@@ -0,0 +1,6 @@+#!/bin/bash+# Build (if needed) and launch Cra. Pass --rebuild to force a build.+set -euo pipefail+cd "$(dirname "$0")/.."+if [ "${1:-}" = "--rebuild" ] || [ ! -d build/Cra.app ]; then scripts/build.sh "${2:-release}"; fi+env -u ELECTRON_RUN_AS_NODE open -n build/Cra.app --args "${@:3}"