Skip to content

armgit / cra

Public Imported from GitHub
0

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

Release pipeline: Developer ID signing, notarization, DMG, GitHub Actions

Victorc8760e37a527
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..40b08f5
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,35 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ build:
+ name: Build Cra.app
+ runs-on: macos-15
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Read pinned CEF version
+ id: cef
+ run: echo "version=$(sed -n 's/^CEF_VERSION="${CEF_VERSION:-\(.*\)}"$/\1/p' scripts/fetch-cef.sh)" >> "$GITHUB_OUTPUT"
+
+ - name: Cache CEF
+ uses: actions/cache@v4
+ with:
+ path: vendor/cef
+ key: cef-${{ runner.arch }}-${{ steps.cef.outputs.version }}
+
+ - name: Build (debug, ad-hoc signed)
+ run: scripts/build.sh debug
+
+ - name: Verify bundle
+ run: |
+ codesign --verify --deep --strict --verbose=2 build/Cra.app
+ /usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' build/Cra.app/Contents/Info.plist
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..8d343a5
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,96 @@
+name: Release
+
+# Cut a release by pushing a tag: git tag v0.1.0 && git push origin v0.1.0
+# Signing and notarization run when the secrets below exist; otherwise the
+# job publishes an ad-hoc build marked as a pre-release.
+#
+# Secrets (Settings → Secrets and variables → Actions):
+# MACOS_CERTIFICATE_P12 base64 of the Developer ID Application .p12
+# MACOS_CERTIFICATE_PASSWORD password of that .p12
+# MACOS_SIGN_IDENTITY e.g. "Developer ID Application: Victor Kildahl (TEAMID)"
+# APPLE_ID Apple ID used for notarization
+# APPLE_TEAM_ID 10-character team id
+# APPLE_APP_PASSWORD app-specific password for that Apple ID
+
+on:
+ push:
+ tags: ["v*"]
+ workflow_dispatch:
+ inputs:
+ version:
+ description: Version to build (without the v)
+ required: true
+ default: 0.1.0
+
+permissions:
+ contents: write
+
+jobs:
+ release:
+ name: Build, sign, notarize, publish
+ runs-on: macos-15
+ env:
+ CRA_VERSION: ${{ github.event.inputs.version || github.ref_name }}
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Normalise version
+ run: echo "CRA_VERSION=${CRA_VERSION#v}" >> "$GITHUB_ENV"
+
+ - name: Read pinned CEF version
+ id: cef
+ run: echo "version=$(sed -n 's/^CEF_VERSION="${CEF_VERSION:-\(.*\)}"$/\1/p' scripts/fetch-cef.sh)" >> "$GITHUB_OUTPUT"
+
+ - name: Cache CEF
+ uses: actions/cache@v4
+ with:
+ path: vendor/cef
+ key: cef-${{ runner.arch }}-${{ steps.cef.outputs.version }}
+
+ - name: Import signing certificate
+ id: cert
+ if: ${{ secrets.MACOS_CERTIFICATE_P12 != '' }}
+ env:
+ P12_BASE64: ${{ secrets.MACOS_CERTIFICATE_P12 }}
+ P12_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
+ run: |
+ KEYCHAIN="$RUNNER_TEMP/signing.keychain-db"
+ KEYCHAIN_PASSWORD="$(openssl rand -hex 16)"
+ echo "$P12_BASE64" | base64 --decode > "$RUNNER_TEMP/cert.p12"
+ security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN"
+ security set-keychain-settings -lut 21600 "$KEYCHAIN"
+ security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN"
+ security import "$RUNNER_TEMP/cert.p12" -P "$P12_PASSWORD" -A -t cert -f pkcs12 -k "$KEYCHAIN"
+ security set-key-partition-list -S apple-tool:,apple: -s -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN"
+ security list-keychains -d user -s "$KEYCHAIN" login.keychain-db
+ rm "$RUNNER_TEMP/cert.p12"
+ echo "signed=true" >> "$GITHUB_OUTPUT"
+
+ - name: Build, sign, notarize, package
+ env:
+ CRA_SIGN_IDENTITY: ${{ steps.cert.outputs.signed == 'true' && secrets.MACOS_SIGN_IDENTITY || '' }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ APPLE_APP_PASSWORD: ${{ secrets.APPLE_APP_PASSWORD }}
+ run: scripts/release.sh
+
+ - name: Upload artifacts
+ uses: actions/upload-artifact@v4
+ with:
+ name: Cra-${{ env.CRA_VERSION }}
+ path: build/dist/*
+
+ - name: Publish GitHub release
+ if: ${{ startsWith(github.ref, 'refs/tags/') }}
+ env:
+ GH_TOKEN: ${{ github.token }}
+ SIGNED: ${{ steps.cert.outputs.signed == 'true' }}
+ run: |
+ NOTES="Cra ${CRA_VERSION} for macOS 14 and later (Apple silicon)."
+ FLAGS=()
+ if [ "$SIGNED" != "true" ]; then
+ FLAGS+=(--prerelease)
+ NOTES="$NOTES"$'\n\n'"This build is ad-hoc signed and not notarized. On first launch, right-click Cra and choose Open."
+ fi
+ gh release create "${{ github.ref_name }}" build/dist/* \
+ --title "Cra ${CRA_VERSION}" --notes "$NOTES" --verify-tag "${FLAGS[@]}"
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..95e664c
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Victor Kildahl
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
index e99c2b1..6569484 100644
--- a/README.md
+++ b/README.md
@@ -14,6 +14,12 @@ Shell: Swift (AppKit + SwiftUI). Engine: Chromium Embedded Framework.
Requirements: Xcode 16+, CMake (`brew install cmake`).
+## Release
+
+`scripts/release.sh` builds, signs with a Developer ID, notarizes, and packages a DMG and
+zip into `build/dist`. Pushing a `v*` tag runs the same through GitHub Actions and
+publishes a release. See `docs/release.md` for the one-time certificate setup.
+
## Layout
- `Sources/Cra` — the app (model, store, sidebar, command bar, windows)
@@ -86,3 +92,11 @@ multiply blends survive) used by `BrandMark`, and `resources/AppIcon.icns` is bu
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.
+
+## Developer Mode and shortcuts
+
+⌃D toggles Arc's per-site Developer Mode: the toolbar switches from the friendly centred
+URL (nav buttons at its left) to the full monospace URL with the developer icons, and the
+nav buttons move into the sidebar. Every shortcut can be changed in Settings → Shortcuts
+(click the shortcut, press new keys; Esc cancels, ⌫ removes; conflicts are flagged).
+Overrides live in `keybindings.json` in the app's support folder.
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index 3446461..002e3c1 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -19,13 +19,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
private var archiveWindow: NSWindow?
private var accountWindow: NSWindow?
private var lastPushedSettings: AppSettings?
+ /// Arc's Little Arc windows: small, sidebar-less, disposable (see LittleWindowController).
+ private(set) var littleWindows: [LittleWindowController] = []
/// 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",
+ "viewArchive", "openLibrary", "settings", "clearToday", "newLittleWindow", "promoteLittleWindow",
] + (1...9).flatMap { ["item\($0)", "space\($0)"] })
// MARK: Lifecycle
@@ -37,6 +39,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
bootstrapped = true
NSApp.setActivationPolicy(.regular)
installURLEventHandler()
+ CraCEFRuntime.setChromeHosting(store.settings.chromeEngine)
buildMenus()
NotificationCenter.default.addObserver(forName: .craKeyBindingsChanged, object: nil, queue: .main) { [weak self] _ in
Task { @MainActor in self?.buildMenus() }
@@ -129,6 +132,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
+ // Little Windows are not in the sidebar; keep their pages in the Library.
+ for w in littleWindows { w.archivePage() }
store.saveAll()
return .terminateNow
}
@@ -140,11 +145,47 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
handleInternalURL(u)
return
}
+ // Arc: "Links from other apps open in Little Arc".
+ if store.settings.openExternalLinksInLittleWindow {
+ openLittleWindow(url: url)
+ return
+ }
store.createTab(url: url, select: true)
main.showWindow(nil)
NSApp.activate(ignoringOtherApps: true)
}
+ // MARK: Little Windows
+
+ /// The little window that owns the key window (the window itself, or its
+ /// Chrome-style page window, which is a child).
+ var keyLittleWindow: LittleWindowController? {
+ guard let key = NSApp.keyWindow else { return nil }
+ return littleWindows.first { $0.window === key || $0.window === key.parent }
+ }
+
+ /// Creates a little window without showing it (`url` nil = popup host).
+ func makeLittleWindow(url: String?) -> LittleWindowController {
+ let w = LittleWindowController(app: self, url: url)
+ littleWindows.append(w)
+ return w
+ }
+
+ @discardableResult
+ func openLittleWindow(url: String, activate: Bool = true) -> LittleWindowController {
+ let w = makeLittleWindow(url: url)
+ if activate { w.show() } else { w.window?.orderFront(nil) }
+ return w
+ }
+
+ func removeLittleWindow(_ w: LittleWindowController) {
+ littleWindows.removeAll { $0 === w }
+ }
+
+ func closeLittleWindows() {
+ for w in littleWindows { w.window?.performClose(nil) }
+ }
+
/// 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.
@@ -153,8 +194,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
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)
+ // Actions keep their target: a key Little Window stays key (perform routes to it).
+ if u.host != "action" || keyLittleWindow == nil {
+ main.showWindow(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ }
switch u.host {
case "commandbar":
main.openCommandBar(q("mode") == "edit" ? .editURL : .newTab)
@@ -162,7 +206,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
case "action":
perform(String(u.path.dropFirst()))
case "open":
- if let url = q("url") {
+ if let url = q("url"), q("little") == "1" {
+ openLittleWindow(url: url)
+ } else 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) }
}
@@ -198,6 +244,31 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
case "debug":
var dict: [String: String] = [:]
for item in comps?.queryItems ?? [] { if let v = item.value { dict[item.name] = v } }
+ if let spikeURL = dict["chromeSpike"] {
+ CraCEFRuntime.spikeChromeWindow(withURL: spikeURL) { [weak self] w in
+ guard let self, let host = self.main.window else { return }
+ w.styleMask.insert(.fullSizeContentView)
+ w.titlebarAppearsTransparent = true
+ w.titleVisibility = .hidden
+ w.isMovable = false
+ w.hasShadow = false
+ host.addChildWindow(w, ordered: .above)
+ let rect = self.main.shell.contentContainer.convert(self.main.shell.webContainer.frame, to: nil)
+ w.setFrame(host.convertToScreen(rect), display: true)
+ w.orderFront(nil)
+ }
+ return
+ }
+ if dict["windows"] != nil {
+ for w in NSApp.windows {
+ NSLog("Cra windows: %@ '%@' frame=%@ parent=%@ visible=%d key=%d mask=%lu class=%@ children=%d",
+ String(describing: w.windowController.map { type(of: $0) } ?? nil as AnyClass?), w.title, NSStringFromRect(w.frame),
+ w.parent.map { NSStringFromRect($0.frame) } ?? "-", w.isVisible ? 1 : 0, w.isKeyWindow ? 1 : 0, w.styleMask.rawValue,
+ NSStringFromClass(type(of: w)), w.childWindows?.count ?? 0)
+ }
+ NSLog("Cra windows: little=%d tabs=%d runtimes=%d", littleWindows.count, store.allTabs().count, main.browsers.runtimes.count)
+ return
+ }
CraTuning.shared.apply(dict)
main.refresh()
if let w = main.window {
@@ -242,6 +313,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
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…"
+ case "pictureInPicture":
+ item.title = main.currentBrowser?.isInPictureInPicture == true ? "Exit Picture in Picture" : "Picture in Picture"
+ case "promoteLittleWindow": return keyLittleWindow?.hasPage ?? false
+ case "closeLittleWindows": return !littleWindows.isEmpty
default: break
}
return true
@@ -264,8 +339,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
func perform(_ id: String) {
store.recordCommandUse(id)
+ // A key Little Window takes the page/window actions first (⌘W, ⌘L, ⌘R…).
+ if let little = keyLittleWindow, little.handle(action: id) { return }
let current = store.selectedTabID
switch id {
+ case "newLittleWindow": openLittleWindow(url: "")
+ case "closeLittleWindows": closeLittleWindows()
+ case "promoteLittleWindow": break // only meaningful while a little window is key
case "newTab", "newWindow": main.openCommandBar(.newTab)
case "editURL": main.openCommandBar(.editURL)
case "newFolder":
@@ -319,6 +399,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
main.browsers.runtime(for: c)?.browser.setAudioMuted(!t.muted)
}
case "clearToday": store.clearToday()
+ case "pictureInPicture": main.currentBrowser?.requestPictureInPictureAutomatic(false)
case "nextTab": main.cycleTab(1); markKeyboardFocus()
case "previousTab": main.cycleTab(-1); markKeyboardFocus()
case "recentTab": if let id = store.mostRecentOtherTab() { store.selectTab(id); markKeyboardFocus() }
@@ -375,7 +456,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
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() },
+ w.contentView = NSHostingView(rootView: SettingsView(onImport: { [weak self] in self?.main.showImport() }, onOpenURL: { [weak self] url in guard let self else { return }; _ = self.store.createTab(url: url, select: true); self.settingsWindow?.close() },
onAccount: { [weak self] in self?.showAccountWindow() })
.environment(store).environment(bindings).environment(account))
w.isReleasedWhenClosed = false
@@ -453,7 +534,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
menubar.addItem(submenu: appMenu, title: "Cra")
let file = NSMenu(title: "File")
- for id in ["newTab", "newWindow", "reopenClosedTab", "editURL", "newFolder", "newSpace"] { file.addItem(item(id)) }
+ for id in ["newTab", "newWindow", "newLittleWindow", "reopenClosedTab", "editURL", "newFolder", "newSpace"] { file.addItem(item(id)) }
file.addItem(.separator())
file.addItem(item("closeWindow")); file.addItem(item("closeTab"))
file.addItem(.separator())
@@ -484,6 +565,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
view.addItem(.separator())
view.addItem(item("resetZoom")); view.addItem(item("zoomIn")); view.addItem(item("zoomOut"))
view.addItem(.separator())
+ view.addItem(item("pictureInPicture"))
+ view.addItem(.separator())
let dev = NSMenu(title: "Developer")
for id in ["viewSource", "devTools", "inspectElement", "jsConsole"] { dev.addItem(item(id)) }
dev.addItem(.separator())
@@ -519,6 +602,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
window.addItem(.separator())
window.addItem(item("openLibrary")); window.addItem(item("viewDownloads"))
window.addItem(.separator())
+ window.addItem(item("promoteLittleWindow")); window.addItem(item("closeLittleWindows"))
+ window.addItem(.separator())
window.addItem(std("Bring All to Front", #selector(NSApplication.arrangeInFront(_:))))
menubar.addItem(submenu: window, title: "Window")
NSApp.windowsMenu = window
diff --git a/Sources/Cra/App/KeyBindings.swift b/Sources/Cra/App/KeyBindings.swift
index 5b1be13..6b50fb7 100644
--- a/Sources/Cra/App/KeyBindings.swift
+++ b/Sources/Cra/App/KeyBindings.swift
@@ -154,6 +154,8 @@ final class KeyBindingRegistry {
// 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),
+ // Arc: File ▸ New Little Arc Window ⌥⌘N.
+ KeyAction(id: "newLittleWindow", name: "New Little Window", section: .file, shortcuts: [Shortcut("n", cmdOpt)], triggers: ["little window", "little arc"]),
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"]),
@@ -183,6 +185,8 @@ final class KeyBindingRegistry {
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),
+ // Arc: Extensions ▸ Picture in Picture (no shortcut); "Open Picture in Picture" in the command bar.
+ KeyAction(id: "pictureInPicture", name: "Picture in Picture", section: .view, shortcuts: [], triggers: ["pip", "picture in picture", "pop out", "popout", "video"]),
// 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),
@@ -206,6 +210,9 @@ final class KeyBindingRegistry {
// 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"]),
+ // Arc's Little Arc "Open in Space" button (LittleBrowserMoveButton) and "Close Little Arc Windows".
+ KeyAction(id: "promoteLittleWindow", name: "Open Little Window in Current Space", section: .window, shortcuts: [], inCommandBar: false),
+ KeyAction(id: "closeLittleWindows", name: "Close Little Windows", section: .window, shortcuts: [], triggers: ["close little"]),
// 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"]),
diff --git a/Sources/Cra/Model/SidebarModel.swift b/Sources/Cra/Model/SidebarModel.swift
index e1cad46..4231576 100644
--- a/Sources/Cra/Model/SidebarModel.swift
+++ b/Sources/Cra/Model/SidebarModel.swift
@@ -208,6 +208,9 @@ struct ArchivedItem: Codable, Identifiable, Equatable {
var sourceSpaceID: UUID?
var wasPinned: Bool
var item: SidebarItem
+ /// Closed from a Little Window (Arc: archive source `littleArc`); never
+ /// had a place in the sidebar, so restoring puts it in the focused space.
+ var fromLittleWindow: Bool? = nil
}
enum AutoArchiveThreshold: String, Codable, CaseIterable, Identifiable {
@@ -265,6 +268,14 @@ struct AppSettings: Codable, Equatable {
/// 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> = []
+ /// Host pages in Chrome-style windows: Chrome extensions and Chrome's own
+ /// DevTools docking. Needs a restart to change.
+ var chromeEngine: Bool = true
+ /// Arc's "Links from other apps open in Little Arc": URLs handed to Cra by
+ /// other apps open in a small disposable window instead of a sidebar tab.
+ var openExternalLinksInLittleWindow: Bool = true
+ /// Arc: "Enable Picture in Picture when you leave a video tab".
+ var autoPictureInPicture: Bool = true
init() {}
@@ -286,6 +297,8 @@ struct WindowPrefs: Codable, Equatable {
var collapsedPinnedSpaces: Set<UUID> = []
var selectedTabPerSpace: [UUID: UUID] = [:]
var windowFrame: String?
+ /// Last Little Window size (Arc: LittleBrowserWindow_size).
+ var littleWindowSize: String?
}
struct HistoryEntry: Codable, Equatable {
@@ -316,6 +329,9 @@ extension AppSettings {
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) ?? []
+ chromeEngine = try c.decodeIfPresent(Bool.self, forKey: .chromeEngine) ?? true
+ autoPictureInPicture = try c.decodeIfPresent(Bool.self, forKey: .autoPictureInPicture) ?? true
+ openExternalLinksInLittleWindow = try c.decodeIfPresent(Bool.self, forKey: .openExternalLinksInLittleWindow) ?? true
}
}
@@ -329,6 +345,7 @@ extension WindowPrefs {
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)
+ littleWindowSize = try c.decodeIfPresent(String.self, forKey: .littleWindowSize)
}
}
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index 23e485d..fdd0242 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -9,6 +9,12 @@ final class TabRuntime {
let browser: CraBrowser
var progress: Double = 0
var themeColor: String = ""
+ /// Cra popped this tab's video out because the user left the tab (Arc's
+ /// auto Picture in Picture); coming back brings the video home.
+ var autoPictureInPicture = false
+ var pendingAutoPictureInPicture = false
+ /// Chrome-style hosting: the page's own window (nil until created, or for Alloy).
+ var hostWindow: NSWindow? { browser.hostWindow }
init(tabID: UUID, browser: CraBrowser) {
self.tabID = tabID
self.browser = browser
@@ -24,6 +30,8 @@ protocol BrowserManagerDelegate: AnyObject {
func browserManagerDevToolsHost(for tabID: UUID) -> NSView?
/// A DevTools pane appeared or closed; the shell decides whether to show the dock.
func browserManagerDevToolsChanged()
+ /// Chrome-style hosting: page windows appeared/changed; the shell re-attaches and orders them.
+ func browserManagerPageWindowsChanged(focus: Bool)
func browserManagerHandleKey(_ event: NSEvent) -> Bool
func browserManagerHandleUnhandledKey(_ event: NSEvent) -> Bool
func browserManagerFocusedBrowser(_ tabID: UUID)
@@ -58,6 +66,18 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
return register(browser: browser, tabID: tabID)
}
+ /// Take over a live browser from elsewhere (a Little Window being promoted
+ /// to a tab): it keeps its history, scroll position and page state.
+ @discardableResult
+ func adopt(_ browser: CraBrowser, for tabID: UUID) -> TabRuntime {
+ if let host = browser.hostWindow, let parent = host.parent { parent.removeChildWindow(host) }
+ browser.containerView.removeFromSuperview()
+ browser.delegate = self
+ let rt = register(browser: browser, tabID: tabID)
+ store.updateTab(tabID, url: browser.currentURL, title: browser.currentTitle)
+ return rt
+ }
+
/// 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)
@@ -81,7 +101,9 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
}
func show(_ tabID: UUID?, focus: Bool) {
+ if let previous = visibleTabID, previous != tabID { leaveTab(previous) }
if let tabID, let rt = ensureRuntime(for: tabID) {
+ returnToTab(rt)
for (id, other) in runtimes where id != tabID { other.browser.containerView.isHidden = true }
rt.browser.containerView.frame = container.bounds
rt.browser.containerView.isHidden = false
@@ -92,6 +114,11 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
visibleTabID = nil
}
syncDevToolsVisibility()
+ delegate?.browserManagerPageWindowsChanged(focus: focus)
+ }
+
+ func browser(_ browser: CraBrowser, didCreateHostWindow window: NSWindow) {
+ delegate?.browserManagerPageWindowsChanged(focus: tabID(of: browser) == visibleTabID)
}
func unload(_ tabID: UUID) {
@@ -114,6 +141,37 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
private func tabID(of browser: CraBrowser) -> UUID? { byBrowser[ObjectIdentifier(browser)] }
+ // MARK: Picture in Picture
+
+ /// Arc: "Enable Picture in Picture when you leave a video tab". The request
+ /// goes out before the page is hidden, so the video keeps playing in the
+ /// floating window; the page answers through didChangePictureInPicture.
+ private func leaveTab(_ tabID: UUID) {
+ guard store.settings.autoPictureInPicture, let rt = runtimes[tabID], !rt.browser.isInPictureInPicture else { return }
+ rt.pendingAutoPictureInPicture = true
+ rt.browser.requestPictureInPictureAutomatic(true)
+ }
+
+ /// Back on the tab: a video Cra popped out automatically comes home (Chrome
+ /// and Arc do the same); one the user popped out stays floating.
+ private func returnToTab(_ rt: TabRuntime) {
+ rt.pendingAutoPictureInPicture = false
+ if rt.autoPictureInPicture { rt.browser.exitPictureInPicture() }
+ }
+
+ func browser(_ browser: CraBrowser, didChangePictureInPicture active: Bool) {
+ guard let id = tabID(of: browser), let rt = runtimes[id] else { return }
+ if active {
+ rt.autoPictureInPicture = rt.pendingAutoPictureInPicture
+ rt.pendingAutoPictureInPicture = false
+ // The request from leaving the tab landed after the user came back.
+ if rt.autoPictureInPicture, id == visibleTabID { browser.exitPictureInPicture() }
+ } else {
+ rt.autoPictureInPicture = false
+ }
+ delegate?.browserManagerDidUpdate(id)
+ }
+
// MARK: CraBrowserDelegate
func browser(_ browser: CraBrowser, didChangeTitle title: String) {
diff --git a/Sources/Cra/Services/ExtensionStore.swift b/Sources/Cra/Services/ExtensionStore.swift
new file mode 100644
index 0000000..66d1ac7
--- /dev/null
+++ b/Sources/Cra/Services/ExtensionStore.swift
@@ -0,0 +1,63 @@
+import AppKit
+import Observation
+
+/// Unpacked Chrome extensions, one folder each, loaded at start-up with
+/// --load-extension by the Chrome-style page windows.
+@MainActor
+@Observable
+final class ExtensionStore {
+ struct Entry: Identifiable, Hashable {
+ let id: String // folder name
+ let name: String
+ let version: String
+ let description: String
+ let url: URL
+ }
+
+ static let directory: URL = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Application Support/Cra/Extensions", isDirectory: true)
+
+ private(set) var entries: [Entry] = []
+ /// Set once the folder changed in this session; a restart loads the change.
+ private(set) var needsRestart = false
+
+ init() { reload() }
+
+ func reload() {
+ let fm = FileManager.default
+ try? fm.createDirectory(at: ExtensionStore.directory, withIntermediateDirectories: true)
+ let names = (try? fm.contentsOfDirectory(atPath: ExtensionStore.directory.path)) ?? []
+ entries = names.sorted().compactMap { name in
+ let dir = ExtensionStore.directory.appendingPathComponent(name, isDirectory: true)
+ guard let data = try? Data(contentsOf: dir.appendingPathComponent("manifest.json")),
+ let m = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }
+ func str(_ k: String) -> String { (m[k] as? String) ?? "" }
+ var title = str("name")
+ if title.hasPrefix("__MSG_") { title = name } // localized names need the extension's locale files
+ return Entry(id: name, name: title.isEmpty ? name : title, version: str("version"), description: str("description"), url: dir)
+ }
+ }
+
+ /// Copies an unpacked extension folder (one that holds manifest.json) in.
+ func add(folder: URL) throws {
+ let fm = FileManager.default
+ guard fm.fileExists(atPath: folder.appendingPathComponent("manifest.json").path) else {
+ throw NSError(domain: "Cra", code: 1, userInfo: [NSLocalizedDescriptionKey: "That folder has no manifest.json."])
+ }
+ var dest = ExtensionStore.directory.appendingPathComponent(folder.lastPathComponent, isDirectory: true)
+ var n = 2
+ while fm.fileExists(atPath: dest.path) {
+ dest = ExtensionStore.directory.appendingPathComponent("\(folder.lastPathComponent)-\(n)", isDirectory: true)
+ n += 1
+ }
+ try fm.copyItem(at: folder, to: dest)
+ needsRestart = true
+ reload()
+ }
+
+ func remove(_ entry: Entry) {
+ try? FileManager.default.removeItem(at: entry.url)
+ needsRestart = true
+ reload()
+ }
+}
diff --git a/Sources/Cra/Services/Persistence.swift b/Sources/Cra/Services/Persistence.swift
index 5175761..f265224 100644
--- a/Sources/Cra/Services/Persistence.swift
+++ b/Sources/Cra/Services/Persistence.swift
@@ -2,8 +2,10 @@ import Foundation
enum AppPaths {
static let supportDir: URL = {
- let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
- .appendingPathComponent("Cra", isDirectory: true)
+ // CRA_DATA_DIR runs a second, independent Cra (testing next to the installed one).
+ let base = ProcessInfo.processInfo.environment["CRA_DATA_DIR"].map { URL(fileURLWithPath: $0, isDirectory: true) }
+ ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("Cra", isDirectory: true)
try? FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
return base
}()
diff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swift
index 85e13eb..66dd406 100644
--- a/Sources/Cra/Services/SidebarStore.swift
+++ b/Sources/Cra/Services/SidebarStore.swift
@@ -300,6 +300,16 @@ final class SidebarStore {
items[parent] = p
}
+ /// A Little Window closed: its page goes to the Library like a closed tab
+ /// (Arc archives Little Arcs with source `littleArc`). It never had a
+ /// sidebar slot, so `sourceSpaceID` is nil and restore uses the focused space.
+ func archiveLittleWindowPage(url: String, title: String) {
+ let it = SidebarItem.tab(url, title: title, parent: nil)
+ archive.insert(ArchivedItem(archivedAt: Date(), reason: .manual, sourceSpaceID: nil, wasPinned: false, item: it, fromLittleWindow: true), at: 0)
+ if archive.count > 2000 { archive.removeLast(archive.count - 2000) }
+ touch()
+ }
+
func appendArchived(_ entry: ArchivedItem) {
archive.append(entry)
archive.sort { $0.archivedAt > $1.archivedAt }
diff --git a/Sources/Cra/UI/ContentToolbarView.swift b/Sources/Cra/UI/ContentToolbarView.swift
index 1621965..117442c 100644
--- a/Sources/Cra/UI/ContentToolbarView.swift
+++ b/Sources/Cra/UI/ContentToolbarView.swift
@@ -117,6 +117,8 @@ struct ContentToolbarView: View {
.padding(.trailing, 6)
}
.frame(height: CraMetrics.toolbarHeight)
+ .contentShape(Rectangle())
+ .onTapGesture(count: 2) { actions.titleBarDoubleClick() }
.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) }
diff --git a/Sources/Cra/UI/ShellView.swift b/Sources/Cra/UI/ShellView.swift
index 3d46fe5..b87a0e0 100644
--- a/Sources/Cra/UI/ShellView.swift
+++ b/Sources/Cra/UI/ShellView.swift
@@ -26,6 +26,13 @@ final class ShellView: NSView {
var devToolsWidth: CGFloat = 460 { didSet { needsLayout = true } }
/// Reports the dock area (window coordinates) so the DevTools child window follows it.
var onDevToolsFrame: ((NSRect) -> Void)?
+ /// Reports the page area (window coordinates) so Chrome-style page windows follow it.
+ var onWebFrame: ((NSRect) -> Void)?
+ /// Sidebar animation: target page area + duration, so page windows animate alongside.
+ var onAnimateWebFrame: ((NSRect, TimeInterval) -> Void)?
+ /// Where the status bubble, toasts and find bar live (the web container, or an
+ /// overlay panel's content view when pages are separate windows).
+ private(set) var overlayParent: NSView
/// 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
@@ -71,6 +78,7 @@ final class ShellView: NSView {
statusHost = NSHostingView(rootView: status)
toastHost = NSHostingView(rootView: toasts)
findHost = NSHostingView(rootView: find)
+ overlayParent = webContainer
super.init(frame: frame)
wantsLayer = true
@@ -235,8 +243,10 @@ final class ShellView: NSView {
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)
+ if overlayParent === webContainer {
+ 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
@@ -249,6 +259,14 @@ final class ShellView: NSView {
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)
+ if frozenWebBounds == nil { onWebFrame?(contentContainer.convert(webContainer.frame, to: nil)) }
+ }
+
+ /// Chrome-style hosting: overlays move into a panel above the page windows.
+ func moveOverlays(to view: NSView) {
+ overlayParent = view
+ for h in [statusHost, toastHost, findHost] { h.removeFromSuperview(); view.addSubview(h) }
+ needsLayout = true
}
/// Animate between sidebar states by interpolating frames.
@@ -260,6 +278,8 @@ final class ShellView: NSView {
frozenWebBounds = NSRect(x: 0, y: 0, width: target.content.width - devW, height: max(0, target.content.height - toolbarH))
layoutContentChildren()
animatingFrames = true
+ onAnimateWebFrame?(NSRect(x: target.content.minX, y: target.content.minY, width: target.content.width - devW,
+ height: max(0, target.content.height - toolbarH)), duration)
NSAnimationContext.runAnimationGroup { ctx in
ctx.duration = duration
// Fast start, soft landing: feels immediate without a visible snap.
@@ -287,6 +307,9 @@ final class ResizeHandleView: NSView {
var onEnd: (() -> Void)?
private var lastX: CGFloat = 0
+ /// The window is movable by its background; this strip must own its drags.
+ override var mouseDownCanMoveWindow: Bool { false }
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
override func resetCursorRects() { addCursorRect(bounds, cursor: .resizeLeftRight) }
override func mouseDown(with event: NSEvent) { lastX = event.locationInWindow.x }
override func mouseDragged(with event: NSEvent) {
@@ -301,6 +324,8 @@ final class ResizeHandleView: NSView {
/// Thin vertical grab area on the DevTools divider.
final class DevToolsResizeHandle: NSView {
var onDrag: ((CGFloat) -> Void)?
+ override var mouseDownCanMoveWindow: Bool { false }
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
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/SidebarRootView.swift b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
index 63673ad..5c94958 100644
--- a/Sources/Cra/UI/Sidebar/SidebarRootView.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
@@ -67,6 +67,8 @@ struct SidebarTopBar: View {
.padding(.top, CraMetrics.titleRowCenter - 14)
.padding(.bottom, CraMetrics.titleAreaHeight - CraMetrics.titleRowCenter - 14)
.padding(.horizontal, 6)
+ .contentShape(Rectangle())
+ .onTapGesture(count: 2) { actions.titleBarDoubleClick() }
if !store.settings.showToolbar {
HStack(spacing: 2) {
navButtons
diff --git a/Sources/Cra/UI/SidebarUIState.swift b/Sources/Cra/UI/SidebarUIState.swift
index 45f841e..aac5bdc 100644
--- a/Sources/Cra/UI/SidebarUIState.swift
+++ b/Sources/Cra/UI/SidebarUIState.swift
@@ -38,6 +38,8 @@ final class SidebarActions {
var resetPinnedTab: (UUID) -> Void = { _ in }
var openURL: (String) -> Void = { _ in }
var performAction: (String) -> Void = { _ in }
+ /// Double-click on an empty part of the header strip (sidebar title row or toolbar).
+ var titleBarDoubleClick: () -> Void = {}
}
private struct SidebarActionsKey: EnvironmentKey {
diff --git a/Sources/Cra/UI/Windows/ArchiveView.swift b/Sources/Cra/UI/Windows/ArchiveView.swift
index 4dbaf6a..fc9effb 100644
--- a/Sources/Cra/UI/Windows/ArchiveView.swift
+++ b/Sources/Cra/UI/Windows/ArchiveView.swift
@@ -89,6 +89,8 @@ private struct ArchiveRow: View {
Spacer()
if let sid = entry.sourceSpaceID, let s = store.space(sid) {
Text("\(s.emoji) \(s.title)").font(.system(size: 11)).foregroundStyle(.secondary)
+ } else if entry.fromLittleWindow == true {
+ Text("Little Window").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)
diff --git a/Sources/Cra/UI/Windows/LittleWindowController.swift b/Sources/Cra/UI/Windows/LittleWindowController.swift
new file mode 100644
index 0000000..a870913
--- /dev/null
+++ b/Sources/Cra/UI/Windows/LittleWindowController.swift
@@ -0,0 +1,556 @@
+import AppKit
+import CraCEF
+import SwiftUI
+
+/// Arc's Little Arc, here a "Little Window": links from other apps (and ⌥⌘N)
+/// open in a small, sidebar-less window with its own Chromium browser. The
+/// page is not in the sidebar. Closing the window archives it to the Library
+/// (Arc: archive source `littleArc`); "Open in Space" promotes it into a
+/// space's Today list, moving the live browser into the main window.
+@MainActor
+@Observable
+final class LittleWindowState {
+ var url = ""
+ var title = ""
+ var canGoBack = false
+ var canGoForward = false
+ var isLoading = false
+ var progress: Double = 0
+ var themeColor = ""
+ var palette: SpacePalette
+ /// Bumped to focus the URL field (⌘L, ⌘T, an empty window).
+ var focusURLToken = 0
+
+ init(palette: SpacePalette) { self.palette = palette }
+}
+
+/// What the toolbar needs AppKit to do.
+@MainActor
+final class LittleWindowActions {
+ var goBack: () -> Void = {}
+ var goForward: () -> Void = {}
+ var reload: () -> Void = {}
+ var navigate: (String) -> Void = { _ in }
+ var focusPage: () -> Void = {}
+ var promote: (UUID?) -> Void = { _ in }
+}
+
+enum LittleMetrics {
+ static let toolbarHeight: CGFloat = 44
+ static let defaultSize = NSSize(width: 1000, height: 700)
+ static let minSize = NSSize(width: 480, height: 360)
+}
+
+@MainActor
+final class LittleWindowController: NSWindowController, NSWindowDelegate, @preconcurrency CraBrowserDelegate {
+ unowned let app: AppDelegate
+ let state: LittleWindowState
+ let actions = LittleWindowActions()
+ private(set) var browser: CraBrowser?
+ private let shell: LittleShellView
+ private var favicon: NSImage?
+ private var promoted = false
+
+ var store: SidebarStore { app.store }
+ var currentURL: String { browser?.currentURL ?? state.url }
+ var hasPage: Bool { !currentURL.isEmpty && currentURL != "about:blank" }
+
+ /// `url` nil makes a popup host: the browser adopts the next window.open
+ /// CEF hands it (see `CraBrowserDelegate.browser:popupHostForURL:`).
+ init(app: AppDelegate, url: String?) {
+ self.app = app
+ let palette = app.store.focusedSpace.theme.palette
+ state = LittleWindowState(palette: palette)
+ let size = app.store.prefs.littleWindowSize.map { NSSizeFromString($0) }
+ .map { NSSize(width: max(LittleMetrics.minSize.width, $0.width), height: max(LittleMetrics.minSize.height, $0.height)) }
+ ?? LittleMetrics.defaultSize
+ let window = LittleWindow(contentRect: NSRect(origin: .zero, size: size),
+ styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
+ backing: .buffered, defer: false)
+ shell = LittleShellView(frame: window.contentView!.bounds, background: SpaceBackground(palette: palette))
+ super.init(window: window)
+ window.delegate = self
+ window.titlebarAppearsTransparent = true
+ window.titleVisibility = .hidden
+ window.isMovableByWindowBackground = true
+ window.minSize = LittleMetrics.minSize
+ window.isReleasedWhenClosed = false
+ window.tabbingMode = .disallowed
+ window.title = "Little Window"
+ window.contentView = shell
+ shell.toolbarHost.rootView = AnyView(LittleToolbar(state: state, actions: actions).environment(app.store))
+ applyPalette(palette)
+ placeWindow()
+
+ actions.goBack = { [weak self] in self?.browser?.goBack() }
+ actions.goForward = { [weak self] in self?.browser?.goForward() }
+ actions.reload = { [weak self] in
+ guard let b = self?.browser else { return }
+ b.isLoading ? b.stopLoading() : b.reload()
+ }
+ actions.navigate = { [weak self] text in self?.navigate(text) }
+ actions.focusPage = { [weak self] in self?.focusPage() }
+ actions.promote = { [weak self] sid in self?.promote(to: sid) }
+
+ let b = CraBrowser(frame: shell.card.bounds, url: url.map { $0.isEmpty ? "about:blank" : $0 }, delegate: self)
+ attach(b)
+ state.url = (url == "about:blank" ? "" : url) ?? ""
+ observeStore()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ private func attach(_ b: CraBrowser) {
+ browser = b
+ // Embedded (Alloy) hosting: the Chromium view lives inside the card.
+ // Chrome-style hosting delivers a window later (-browser:didCreateHostWindow:).
+ let v = b.containerView
+ v.frame = shell.card.bounds
+ v.autoresizingMask = [.width, .height]
+ shell.card.addSubview(v)
+ shell.onCardFrame = { [weak self] rect in self?.positionHostWindow(rect) }
+ if let w = b.hostWindow { attachHostWindow(w) }
+ }
+
+ /// Chrome-style hosting: the page is a frameless Chrome window; attach it
+ /// as a child window over the card and round all four corners.
+ private func attachHostWindow(_ w: NSWindow) {
+ guard let window, w.parent !== window else { return }
+ w.styleMask.insert(.fullSizeContentView)
+ w.titlebarAppearsTransparent = true
+ w.titleVisibility = .hidden
+ w.isMovable = false
+ w.hasShadow = false
+ 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 = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]
+ cv.layer?.masksToBounds = true
+ }
+ window.addChildWindow(w, ordered: .above)
+ positionHostWindow(shell.convert(shell.card.frame, to: nil))
+ w.orderFront(nil)
+ }
+
+ private func positionHostWindow(_ rectInWindow: NSRect) {
+ guard let window, let w = browser?.hostWindow, w.parent === window, !rectInWindow.isEmpty else { return }
+ let onScreen = window.convertToScreen(rectInWindow)
+ if w.frame != onScreen { w.setFrame(onScreen, display: true) }
+ if let cv = w.contentView { cv.layer?.cornerRadius = window.styleMask.contains(.fullScreen) ? 0 : CraMetrics.contentCornerRadius }
+ }
+
+ private func focusPage() {
+ guard let b = browser else { return }
+ if let w = b.hostWindow, w.parent === window { w.makeKey() }
+ b.setFocused(true)
+ }
+
+ /// Centre on the screen under the pointer, cascaded off other little windows.
+ private func placeWindow() {
+ guard let window else { return }
+ let mouse = NSEvent.mouseLocation
+ let screen = NSScreen.screens.first { $0.frame.contains(mouse) } ?? NSScreen.main ?? NSScreen.screens[0]
+ let vf = screen.visibleFrame
+ var frame = window.frame
+ frame.size.width = min(frame.width, vf.width - 40)
+ frame.size.height = min(frame.height, vf.height - 40)
+ let n = CGFloat(app.littleWindows.count)
+ frame.origin = NSPoint(x: vf.midX - frame.width / 2 + n * 24, y: vf.midY - frame.height / 2 - n * 24)
+ frame.origin.x = min(max(vf.minX, frame.origin.x), vf.maxX - frame.width)
+ frame.origin.y = min(max(vf.minY, frame.origin.y), vf.maxY - frame.height)
+ window.setFrame(frame, display: false)
+ }
+
+ func show() {
+ guard let window else { return }
+ window.makeKeyAndOrderFront(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ if hasPage { focusPage() } else { focusURL() }
+ }
+
+ func focusURL() {
+ window?.makeKeyAndOrderFront(nil)
+ window?.makeFirstResponder(shell.toolbarHost)
+ state.focusURLToken += 1
+ }
+
+ private func navigate(_ text: String) {
+ let t = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !t.isEmpty else { browser?.setFocused(true); return }
+ let url = SuggestionEngine.looksLikeURL(t) ? SuggestionEngine.urlFromInput(t) : store.settings.searchEngine.searchURL(t)
+ state.url = url
+ browser?.loadURL(url)
+ focusPage()
+ }
+
+ // MARK: Theme
+
+ private func observeStore() {
+ withObservationTracking {
+ _ = store.prefs.focusedSpaceID
+ _ = store.spaces
+ } onChange: { [weak self] in
+ Task { @MainActor in
+ guard let self else { return }
+ let p = self.store.focusedSpace.theme.palette
+ self.state.palette = p
+ self.applyPalette(p)
+ self.observeStore()
+ }
+ }
+ }
+
+ private func applyPalette(_ palette: SpacePalette) {
+ guard let window else { return }
+ shell.backgroundHost.rootView = SpaceBackground(palette: palette)
+ shell.vibrancy.isHidden = !palette.vibrant
+ shell.vibrancy.material = palette.isDark ? .underWindowBackground : .hudWindow
+ shell.vibrancy.appearance = NSAppearance(named: .darkAqua)
+ window.appearance = NSAppearance(named: palette.isDark ? .darkAqua : .aqua)
+ window.isOpaque = !palette.vibrant
+ window.backgroundColor = palette.vibrant ? .clear : NSColor(palette.gradientColors.first ?? .gray)
+ }
+
+ // MARK: Promote / close
+
+ /// Move the page into a space (nil = the focused one) as a Today tab. The
+ /// live browser goes with it, so history, scroll position and logins stay.
+ func promote(to spaceID: UUID?) {
+ guard let b = browser, hasPage else { return }
+ let sid = spaceID.flatMap { store.space($0) != nil ? $0 : nil } ?? store.focusedSpaceID
+ let tab = store.createTab(url: b.currentURL, title: b.currentTitle, in: sid, select: true)
+ if let favicon, let key = FaviconCache.key(for: b.currentURL) { app.favicons.store(favicon, forKey: key) }
+ promoted = true
+ browser = nil
+ app.main.browsers.adopt(b, for: tab.id)
+ window?.close()
+ app.main.showWindow(nil)
+ app.main.window?.makeKeyAndOrderFront(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ }
+
+ /// Archive the page to the Library (Arc keeps closed Little Arcs there too).
+ func archivePage() {
+ guard hasPage, !promoted else { return }
+ store.archiveLittleWindowPage(url: currentURL, title: browser?.currentTitle ?? state.title)
+ if let favicon, let key = FaviconCache.key(for: currentURL) { app.favicons.store(favicon, forKey: key) }
+ promoted = true // archived once; a later close must not archive again
+ }
+
+ /// Menu / key actions while this window is key. Returns false for actions
+ /// that are not the little window's (the app handles those).
+ func handle(action id: String) -> Bool {
+ switch id {
+ case "closeTab", "closeWindow": window?.performClose(nil)
+ case "newTab", "editURL": focusURL()
+ case "goBack": browser?.goBack()
+ case "goForward": browser?.goForward()
+ case "reload": browser?.reload()
+ case "hardReload": browser?.reloadIgnoringCache()
+ case "stop": browser?.stopLoading()
+ case "zoomIn": if let b = browser { b.setZoomLevel(b.zoomLevel() + 0.5) }
+ case "zoomOut": if let b = browser { b.setZoomLevel(b.zoomLevel() - 0.5) }
+ case "resetZoom": browser?.setZoomLevel(0)
+ case "copyURL": copy(currentURL)
+ case "copyURLMarkdown": copy("[\(browser?.currentTitle ?? state.title)](\(currentURL))")
+ case "viewSource": browser?.viewSource()
+ case "devTools", "jsConsole", "inspectElement": browser?.showDevTools()
+ case "print": browser?.print()
+ case "promoteLittleWindow": promote(to: nil)
+ // No find bar or capture in little windows; keep them off the main window.
+ case "find", "findNext", "findPrevious", "capturePage", "toggleSidebar", "pinTab", "favoriteTab", "renameTab",
+ "duplicateTab", "resetTab", "muteTab", "clearToday", "nextTab", "previousTab", "recentTab":
+ break
+ default: return false
+ }
+ return true
+ }
+
+ private func copy(_ s: String) {
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(s, forType: .string)
+ }
+
+ // MARK: NSWindowDelegate
+
+ func windowShouldClose(_ sender: NSWindow) -> Bool {
+ archivePage()
+ if let b = browser {
+ b.containerView.isHidden = true
+ if let w = b.hostWindow, w.parent === sender { sender.removeChildWindow(w); w.orderOut(nil) }
+ b.close() // -browserDidClose: drops the controller
+ }
+ return true
+ }
+
+ func windowWillClose(_ notification: Notification) {
+ if browser == nil { app.removeLittleWindow(self) }
+ }
+
+ func windowDidResize(_ notification: Notification) {
+ guard let window, !window.styleMask.contains(.fullScreen) else { return }
+ store.prefs.littleWindowSize = NSStringFromSize(window.frame.size)
+ }
+
+ // MARK: CraBrowserDelegate
+
+ func browser(_ browser: CraBrowser, didChangeTitle title: String) {
+ state.title = title
+ window?.title = title.isEmpty ? "Little Window" : title
+ }
+
+ func browser(_ browser: CraBrowser, didChangeURL url: String) {
+ if url.hasPrefix("data:text/html;base64,") { return }
+ state.url = url == "about:blank" ? "" : url
+ }
+
+ func browser(_ browser: CraBrowser, didChangeLoading loading: Bool, canGoBack: Bool, canGoForward: Bool) {
+ state.isLoading = loading
+ state.canGoBack = canGoBack
+ state.canGoForward = canGoForward
+ if !loading { state.progress = 0 }
+ }
+
+ func browser(_ browser: CraBrowser, didChangeProgress progress: Double) { state.progress = progress }
+
+ func browser(_ browser: CraBrowser, didFinishLoadingURL url: String, title: String, statusCode: Int) {
+ store.recordVisit(url: url, title: title)
+ }
+
+ func browser(_ browser: CraBrowser, didLoadFavicon image: NSImage, forURL iconURL: String) {
+ favicon = image
+ if let key = FaviconCache.key(for: browser.currentURL) { app.favicons.store(image, forKey: key) }
+ }
+
+ func browser(_ browser: CraBrowser, didReportThemeColor hex: String) { state.themeColor = hex }
+ func browser(_ browser: CraBrowser, didChangeStatusMessage message: String) {}
+
+ func browser(_ browser: CraBrowser, didChangeFullscreen fullscreen: Bool) {
+ guard let window else { return }
+ if fullscreen != window.styleMask.contains(.fullScreen) { window.toggleFullScreen(nil) }
+ }
+
+ /// Links that want a new tab open another little window (Arc does the same).
+ func browser(_ browser: CraBrowser, requestsNewTabWithURL url: String, inBackground background: Bool) {
+ if url.hasPrefix("cra://") { if let u = URL(string: url) { app.handleInternalURL(u) }; return }
+ let w = app.openLittleWindow(url: url, activate: !background)
+ if background { window?.makeKeyAndOrderFront(nil); _ = w }
+ }
+
+ func browser(_ browser: CraBrowser, popupHostForURL url: String, inBackground background: Bool) -> CraBrowser? {
+ if url.hasPrefix("cra://") { if let u = URL(string: url) { app.handleInternalURL(u) }; return nil }
+ let w = app.makeLittleWindow(url: nil)
+ w.state.url = url
+ w.show()
+ if background { window?.makeKeyAndOrderFront(nil) }
+ return w.browser
+ }
+
+ func devToolsHostView(for browser: CraBrowser) -> NSView? { nil }
+ func browser(_ browser: CraBrowser, didCreateDevToolsView view: NSView) {}
+ func browser(_ browser: CraBrowser, didCreateHostWindow window: NSWindow) {
+ attachHostWindow(window)
+ if hasPage, self.window?.isKeyWindow == true || window.isKeyWindow { focusPage() }
+ }
+ func browserDidCloseDevTools(_ browser: CraBrowser) {}
+ func browser(_ browser: CraBrowser, handleKeyEvent event: NSEvent) -> Bool { app.handleReservedKey(event) }
+ func browser(_ browser: CraBrowser, handleUnhandledKeyEvent event: NSEvent) -> Bool { app.handleUnhandledKey(event) }
+ func browser(_ browser: CraBrowser, didUpdateDownload download: CraDownloadInfo) { app.main.browserManager(download: download) }
+
+ func browser(_ browser: CraBrowser, requestsPermissionForOrigin origin: String, kinds: UInt, completion: @escaping (Bool) -> Void) {
+ 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 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 else { completion(false); return }
+ alert.beginSheetModal(for: window) { resp in completion(resp == .alertFirstButtonReturn) }
+ }
+
+ func browserDidReceiveFocus(_ browser: CraBrowser) {}
+
+ func browserDidClose(_ browser: CraBrowser) {
+ browser.containerView.removeFromSuperview()
+ guard self.browser === browser else { return }
+ self.browser = nil
+ if let window, window.isVisible {
+ // The page closed itself (window.close()); the window goes with it.
+ archivePage()
+ window.close()
+ }
+ app.removeLittleWindow(self)
+ }
+}
+
+/// Gradient background, toolbar strip on the gradient, rounded page card below.
+final class LittleShellView: NSView {
+ let vibrancy = NSVisualEffectView()
+ let backgroundHost: NSHostingView<SpaceBackground>
+ let toolbarHost = NSHostingView(rootView: AnyView(EmptyView()))
+ let card = NSView()
+ /// Reports the card (window coordinates) so a Chrome-style page window can follow it.
+ var onCardFrame: ((NSRect) -> Void)?
+
+ init(frame: NSRect, background: SpaceBackground) {
+ backgroundHost = NSHostingView(rootView: background)
+ super.init(frame: frame)
+ wantsLayer = true
+ vibrancy.blendingMode = .behindWindow
+ vibrancy.state = .active
+ vibrancy.isHidden = true
+ addSubview(vibrancy)
+ addSubview(backgroundHost)
+ toolbarHost.sizingOptions = []
+ addSubview(toolbarHost)
+ card.wantsLayer = true
+ card.layer?.cornerRadius = CraMetrics.contentCornerRadius
+ card.layer?.cornerCurve = .continuous
+ card.layer?.masksToBounds = true
+ card.layer?.backgroundColor = NSColor.white.cgColor
+ card.autoresizesSubviews = true
+ addSubview(card)
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override func layout() {
+ super.layout()
+ let b = bounds
+ vibrancy.frame = b
+ backgroundHost.frame = b
+ let fullscreen = window?.styleMask.contains(.fullScreen) ?? false
+ let toolbarH = LittleMetrics.toolbarHeight
+ toolbarHost.frame = NSRect(x: 0, y: b.height - toolbarH, width: b.width, height: toolbarH)
+ let inset = fullscreen ? 0 : CraMetrics.contentInset
+ card.frame = NSRect(x: inset, y: inset, width: max(0, b.width - 2 * inset), height: max(0, b.height - toolbarH - inset))
+ card.layer?.cornerRadius = fullscreen ? 0 : CraMetrics.contentCornerRadius
+ for sub in card.subviews where sub.frame != card.bounds { sub.frame = card.bounds }
+ onCardFrame?(convert(card.frame, to: nil))
+ }
+}
+
+/// Traffic lights centred on the toolbar strip.
+final class LittleWindow: NSWindow {
+ override func layoutIfNeeded() {
+ super.layoutIfNeeded()
+ positionTrafficLights()
+ }
+
+ override func makeKeyAndOrderFront(_ sender: Any?) {
+ super.makeKeyAndOrderFront(sender)
+ positionTrafficLights()
+ }
+
+ private func positionTrafficLights() {
+ guard !styleMask.contains(.fullScreen) else { return }
+ for (i, type) in [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton].enumerated() {
+ guard let b = standardWindowButton(type), let sv = b.superview else { continue }
+ let target = NSPoint(x: 13 + CGFloat(i) * 20, y: sv.bounds.height - LittleMetrics.toolbarHeight / 2 - b.frame.height / 2)
+ if abs(b.frame.origin.x - target.x) > 0.5 || abs(b.frame.origin.y - target.y) > 0.5 { b.setFrameOrigin(target) }
+ }
+ }
+}
+
+/// Nav buttons, the URL field, and "Open in Space" on the gradient strip.
+struct LittleToolbar: View {
+ let state: LittleWindowState
+ let actions: LittleWindowActions
+ @Environment(SidebarStore.self) private var store
+ @State private var text = ""
+ @State private var hoverURL = false
+ @FocusState private var editing: Bool
+
+ private var palette: SpacePalette { state.palette }
+ private var fg: Color { palette.textPrimary }
+ private var fgDim: Color { palette.textSecondary }
+ private var human: String { SuggestionEngine.humanURL(state.url) }
+
+ var body: some View {
+ HStack(spacing: 2) {
+ Spacer().frame(width: 72) // traffic lights
+ ToolbarIcon(symbol: "arrow.left", fg: fgDim, help: "Go Back (⌘[)", enabled: state.canGoBack, width: 32, iconSize: 15) { actions.goBack() }
+ ToolbarIcon(symbol: "arrow.right", fg: fgDim, help: "Go Forward (⌘])", enabled: state.canGoForward, width: 32, iconSize: 15) { actions.goForward() }
+ ToolbarIcon(symbol: state.isLoading ? "xmark" : "arrow.clockwise", fg: fgDim, help: "Refresh (⌘R)", width: 32, iconSize: 15) { actions.reload() }
+ Spacer(minLength: 8)
+ urlField
+ .frame(maxWidth: 640)
+ Spacer(minLength: 8)
+ openInSpace
+ .padding(.trailing, 10)
+ }
+ .frame(height: LittleMetrics.toolbarHeight)
+ .overlay(alignment: .bottomLeading) {
+ if state.isLoading && state.progress > 0 {
+ GeometryReader { g in
+ Capsule().fill(palette.folderTint.opacity(0.9))
+ .frame(width: max(8, g.size.width * state.progress), height: 2)
+ }
+ .frame(height: 2)
+ .padding(.horizontal, CraMetrics.contentInset)
+ }
+ }
+ .onAppear { text = human }
+ .onChange(of: state.url) { _, _ in if !editing { text = human } }
+ .onChange(of: editing) { _, on in text = on ? state.url : human }
+ .onChange(of: state.focusURLToken) { _, _ in editing = true }
+ .ignoresSafeArea()
+ }
+
+ private var urlField: some View {
+ HStack(spacing: 7) {
+ Image(systemName: editing ? "magnifyingglass" : (state.url.hasPrefix("https://") ? "lock.fill" : "link"))
+ .font(.system(size: 12, weight: .medium))
+ .foregroundStyle(fgDim)
+ TextField("Search or enter URL…", text: $text)
+ .textFieldStyle(.plain)
+ .font(.system(size: 13, design: editing ? .monospaced : .default))
+ .foregroundStyle(fg)
+ .multilineTextAlignment(editing ? .leading : .center)
+ .focused($editing)
+ .onSubmit { editing = false; actions.navigate(text) }
+ .onExitCommand { editing = false; text = human; actions.focusPage() }
+ }
+ .padding(.horizontal, 10)
+ .frame(height: 28)
+ .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(editing || hoverURL ? palette.selectedFill : palette.pillFill))
+ .onHover { hoverURL = $0 }
+ .help(state.url)
+ }
+
+ private var openInSpace: some View {
+ let focused = store.focusedSpace
+ return Menu {
+ Button("\(focused.emoji) \(focused.title)") { actions.promote(focused.id) }
+ if store.orderedSpaces.count > 1 {
+ Divider()
+ ForEach(store.orderedSpaces.filter { $0.id != focused.id }) { s in
+ Button("\(s.emoji) \(s.title)") { actions.promote(s.id) }
+ }
+ }
+ } label: {
+ HStack(spacing: 5) {
+ Image(systemName: "arrow.up.forward.app").font(.system(size: 12, weight: .medium))
+ Text("Open in Space").font(.system(size: 12, weight: .medium))
+ Image(systemName: "chevron.down").font(.system(size: 9, weight: .semibold))
+ }
+ .foregroundStyle(fg)
+ .padding(.horizontal, 10)
+ .frame(height: 28)
+ .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(palette.pillFill))
+ }
+ .menuStyle(.button)
+ .buttonStyle(.plain)
+ .menuIndicator(.hidden)
+ .fixedSize()
+ .disabled(state.url.isEmpty)
+ .help("Move this page into a space as a tab")
+ }
+}
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index a34cc64..a25c0ad 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -94,6 +94,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
observeStore()
refresh()
shell.onDevToolsFrame = { [weak self] rect in self?.positionDevToolsWindow(rect) }
+ shell.onWebFrame = { [weak self] rect in self?.positionPageWindows(rect) }
+ shell.onAnimateWebFrame = { [weak self] rect, d in self?.animatePageWindows(to: rect, duration: d) }
NotificationCenter.default.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in
Task { @MainActor in self?.shell.windowActive = true }
}
@@ -107,6 +109,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// MARK: Wiring
private func wireActions() {
+ sidebarActions.titleBarDoubleClick = { [weak self] in (self?.window as? CraWindow)?.performTitleDoubleClickAction() }
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() }
@@ -215,6 +218,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
let toast = DownloadToast(id: download.identifier, name: name, percent: download.percent, state: download.state.rawValue, path: download.fullPath)
if let i = overlay.toasts.firstIndex(where: { $0.id == toast.id }) { overlay.toasts[i] = toast } else { overlay.toasts.append(toast) }
shell.toastCount = overlay.toasts.count
+ overlayPanel?.ignoresMouseEvents = overlay.toasts.isEmpty && !overlay.findVisible
shell.layoutContentChildren()
if download.state != .inProgress {
let id = toast.id
@@ -248,6 +252,86 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
return shell.devToolsHost
}
+ // MARK: Chrome-style page windows
+
+ private var overlayPanel: NSPanel?
+ private var lastWebRectInWindow: NSRect = .zero
+
+ private func ensureOverlayPanel() {
+ guard overlayPanel == nil, let window else { return }
+ let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300),
+ styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
+ panel.isOpaque = false
+ panel.backgroundColor = .clear
+ panel.hasShadow = false
+ panel.isMovable = false
+ panel.ignoresMouseEvents = true
+ panel.hidesOnDeactivate = false
+ panel.contentView = NSView(frame: panel.contentRect(forFrameRect: panel.frame))
+ shell.moveOverlays(to: panel.contentView!)
+ window.addChildWindow(panel, ordered: .above)
+ overlayPanel = panel
+ }
+
+ /// Attaches the visible tab's Chrome window over the page area, hides the others.
+ func browserManagerPageWindowsChanged(focus: Bool) {
+ guard let window else { return }
+ ensureOverlayPanel()
+ let visible = browsers.visibleRuntime?.hostWindow
+ for rt in browsers.runtimes.values {
+ guard let w = rt.hostWindow else { continue }
+ if w !== visible { if w.isVisible { w.orderOut(nil) }; continue }
+ if w.parent !== window {
+ w.styleMask.insert(.fullSizeContentView)
+ w.titlebarAppearsTransparent = true
+ w.titleVisibility = .hidden
+ w.isMovable = false
+ w.hasShadow = false
+ 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 = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
+ cv.layer?.masksToBounds = true
+ }
+ window.addChildWindow(w, ordered: .above)
+ }
+ positionPageWindows(lastWebRectInWindow)
+ w.orderFront(nil)
+ if focus { w.makeKey() }
+ }
+ // Keep the overlay panel above the page windows.
+ if let panel = overlayPanel {
+ window.removeChildWindow(panel)
+ window.addChildWindow(panel, ordered: .above)
+ panel.orderFront(nil)
+ }
+ }
+
+ private func positionPageWindows(_ rectInWindow: NSRect) {
+ guard let window, !rectInWindow.isEmpty else { return }
+ lastWebRectInWindow = rectInWindow
+ let onScreen = window.convertToScreen(rectInWindow)
+ for rt in browsers.runtimes.values {
+ if let w = rt.hostWindow, w.frame != onScreen { w.setFrame(onScreen, display: true) }
+ }
+ if let panel = overlayPanel, panel.frame != onScreen { panel.setFrame(onScreen, display: true) }
+ }
+
+ private func animatePageWindows(to rectInWindow: NSRect, duration: TimeInterval) {
+ guard let window, let w = browsers.visibleRuntime?.hostWindow else { return }
+ lastWebRectInWindow = rectInWindow
+ let onScreen = window.convertToScreen(rectInWindow)
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = duration
+ ctx.timingFunction = CAMediaTimingFunction(controlPoints: 0.2, 0.85, 0.25, 1)
+ w.animator().setFrame(onScreen, display: true)
+ overlayPanel?.animator().setFrame(onScreen, display: true)
+ }
+ }
+
/// 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() {
@@ -298,7 +382,13 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
func browserManagerHandleKey(_ event: NSEvent) -> Bool { app.handleReservedKey(event) }
func browserManagerHandleUnhandledKey(_ event: NSEvent) -> Bool { app.handleUnhandledKey(event) }
- func browserManagerFocusedBrowser(_ tabID: UUID) {}
+ /// A hidden page asked for focus: the Picture in Picture window's "back to tab" button.
+ func browserManagerFocusedBrowser(_ tabID: UUID) {
+ guard tabID != browsers.visibleTabID, browsers.runtime(for: tabID)?.browser.isInPictureInPicture == true else { return }
+ store.selectTab(tabID)
+ showWindow(nil)
+ NSApp.activate(ignoringOtherApps: true)
+ }
func browserManagerOpenInternalURL(_ url: String) {
if let u = URL(string: url) { app.handleInternalURL(u) }
}
@@ -358,7 +448,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
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 captureWindow = browsers.visibleRuntime?.hostWindow ?? window
+ guard let image = CGWindowListCreateImage(screenRect, .optionIncludingWindow, CGWindowID(captureWindow.windowNumber), [.bestResolution]) else { return }
let rep = NSBitmapImageRep(cgImage: image)
guard let png = rep.representation(using: .png, properties: [:]) else { return }
let f = DateFormatter()
@@ -521,6 +612,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
overlay.findVisible = true
overlay.findFocusToken += 1
shell.findVisible = true
+ overlayPanel?.ignoresMouseEvents = false
+ overlayPanel?.makeKeyAndOrderFront(nil)
shell.layoutContentChildren()
window?.makeFirstResponder(shell.findHost)
}
@@ -528,6 +621,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
func hideFindBar() {
overlay.findVisible = false
shell.findVisible = false
+ overlayPanel?.ignoresMouseEvents = overlay.toasts.isEmpty
currentBrowser?.stopFinding(true)
shell.layoutContentChildren()
currentBrowser?.setFocused(true)
@@ -640,6 +734,20 @@ final class CraWindow: NSWindow {
didSet { if oldValue != trafficLightsRevealed { updateTrafficLightAlpha(animated: true) } }
}
+ /// The real title bar is hidden under the content, so double-clicks on the
+ /// header strip never reach AppKit's zoom handling. The SwiftUI header rows
+ /// call this on a double-click of their empty parts; it performs the system
+ /// "double-click a window's title bar" action from System Settings.
+ func performTitleDoubleClickAction() {
+ guard !styleMask.contains(.fullScreen) else { return }
+ let action = UserDefaults.standard.string(forKey: "AppleActionOnDoubleClick") ?? "Maximize"
+ switch action {
+ case "None": break
+ case "Minimize": miniaturize(nil)
+ default: zoom(nil) // "Maximize" and "Fill"
+ }
+ }
+
override func layoutIfNeeded() {
super.layoutIfNeeded()
positionTrafficLights()
diff --git a/Sources/Cra/UI/Windows/SettingsView.swift b/Sources/Cra/UI/Windows/SettingsView.swift
index 23b34f1..f94ec4a 100644
--- a/Sources/Cra/UI/Windows/SettingsView.swift
+++ b/Sources/Cra/UI/Windows/SettingsView.swift
@@ -5,7 +5,10 @@ struct SettingsView: View {
@Environment(SidebarStore.self) private var store
@Environment(KeyBindingRegistry.self) private var bindings
@Environment(AccountStore.self) private var account
+ @State private var extensions = ExtensionStore()
+ @State private var extensionError: String?
let onImport: () -> Void
+ var onOpenURL: (String) -> Void = { _ in }
let onAccount: () -> Void
var body: some View {
@@ -26,6 +29,9 @@ struct SettingsView: View {
}
Toggle("New tabs open at the top of Today", isOn: $store.settings.newTabsAtTop)
Toggle("Show toolbar above the page (⇧⌘D)", isOn: $store.settings.showToolbar)
+ Toggle("Enable Picture in Picture when you leave a video tab", isOn: $store.settings.autoPictureInPicture)
+ Toggle("Links from other apps open in a Little Window", isOn: $store.settings.openExternalLinksInLittleWindow)
+ Toggle("Chrome engine for pages (extensions, Chrome DevTools) — restart Cra to apply", isOn: $store.settings.chromeEngine)
}
Section("Search") {
Picker("Search engine", selection: $store.settings.searchEngine) {
@@ -39,6 +45,45 @@ struct SettingsView: View {
.foregroundStyle(.secondary)
Button("Import…") { onImport() }.disabled(!(ArcImporter.isAvailable || DiaImporter.isAvailable))
}
+ Section {
+ if extensions.entries.isEmpty {
+ Text("No extensions installed. Add an unpacked extension folder (the kind Chrome's \"Load unpacked\" takes).")
+ .foregroundStyle(.secondary)
+ }
+ ForEach(extensions.entries) { e in
+ HStack(alignment: .firstTextBaseline) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("\(e.name) \(e.version)").font(.system(size: 13, weight: .medium))
+ if !e.description.isEmpty { Text(e.description).font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(2) }
+ }
+ Spacer()
+ Button("Remove") { extensions.remove(e) }.buttonStyle(.link).font(.system(size: 11))
+ }
+ }
+ HStack {
+ Button("Add Unpacked Extension…") {
+ let panel = NSOpenPanel()
+ panel.canChooseDirectories = true
+ panel.canChooseFiles = false
+ panel.allowsMultipleSelection = false
+ panel.prompt = "Add"
+ panel.message = "Choose an unpacked extension folder (it holds manifest.json)."
+ if panel.runModal() == .OK, let url = panel.url {
+ do { try extensions.add(folder: url); extensionError = nil } catch { extensionError = error.localizedDescription }
+ }
+ }
+ Button("Open Chrome's Extension Manager") { onOpenURL("chrome://extensions") }
+ .disabled(!store.settings.chromeEngine)
+ Spacer()
+ }
+ if let err = extensionError { Text(err).font(.system(size: 11)).foregroundStyle(.red) }
+ Text(store.settings.chromeEngine
+ ? (extensions.needsRestart ? "Restart Cra to apply the change." : "Extensions load when Cra starts.")
+ : "Extensions need the Chrome engine (Tabs section).")
+ .font(.system(size: 11)).foregroundStyle(.secondary)
+ } header: {
+ Text("Extensions")
+ }
Section {
ForEach(bindings.actions) { a in
HStack(spacing: 8) {
diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mm
index 7dd89c3..e8dcde7 100644
--- a/Sources/CraCEF/CraCEF.mm
+++ b/Sources/CraCEF/CraCEF.mm
@@ -1,6 +1,10 @@
// Objective-C++ bridge between Swift and CEF. See include/CraCEF.h.
#import "CraCEF.h"
+#include "include/views/cef_browser_view.h"
+#include "include/views/cef_browser_view_delegate.h"
+#include "include/views/cef_window.h"
+#include "include/views/cef_window_delegate.h"
#include <crt_externs.h>
#include <atomic>
#include <string>
@@ -10,6 +14,7 @@
#include "include/cef_application_mac.h"
#include "include/cef_browser.h"
#include "include/cef_client.h"
+#include "include/cef_command_ids.h"
#include "include/cef_command_line.h"
#include "include/cef_context_menu_handler.h"
#include "include/cef_display_handler.h"
@@ -32,6 +37,7 @@ 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 BOOL g_chromeHosting = NO;
static NSMutableArray<CraBrowser*>* g_pendingCreation = nil;
static void (^g_relaunchHandler)(NSArray<NSString*>*) = nil;
static BOOL g_alreadyRunning = NO;
@@ -54,6 +60,7 @@ enum CraMenuCommand {
kMenuInspectElement,
kMenuOpenImageInNewTab,
kMenuCopyImageURL,
+ kMenuPictureInPicture,
};
// MARK: - Downloads
@@ -74,11 +81,16 @@ class CraClient;
@property (nonatomic) BOOL canGoForward;
@property (nonatomic) BOOL isCreated;
@property (nonatomic) BOOL isClosed;
+@property (nonatomic) BOOL isInPictureInPicture;
+- (void)requestPictureInPictureInFrame:(CefRefPtr<CefFrame>)frame automatic:(BOOL)automatic x:(int)x y:(int)y;
- (void)adoptBrowser:(CefRefPtr<CefBrowser>)browser;
- (void)browserClosed;
- (CefRefPtr<CefBrowser>)cefBrowser;
- (CefRefPtr<CefClient>)cefClient;
- (void)createNow;
+- (void)hostWindowCreated:(NSWindow*)window;
+- (void)hostPopupBrowserView:(CefRefPtr<CefBrowserView>)view;
+@property (nonatomic, strong, nullable) NSWindow* hostWindow;
@end
// MARK: - CEF app
@@ -94,6 +106,21 @@ public:
// 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");
+ // Chrome-style windows are ours; Chrome must not restore or reopen them.
+ command_line->AppendSwitch("no-startup-window");
+ command_line->AppendSwitch("disable-session-crashed-bubble");
+ command_line->AppendSwitch("hide-crash-restore-bubble");
+ command_line->AppendSwitch("no-first-run");
+ // Unpacked Chrome extensions (Chrome-style browsers only): one folder per extension.
+ if (process_type.empty()) {
+ NSString* dir = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/Cra/Extensions"];
+ NSMutableArray<NSString*>* paths = [NSMutableArray array];
+ for (NSString* name in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:nil]) {
+ NSString* p = [dir stringByAppendingPathComponent:name];
+ if ([[NSFileManager defaultManager] fileExistsAtPath:[p stringByAppendingPathComponent:@"manifest.json"]]) [paths addObject:p];
+ }
+ if (paths.count) command_line->AppendSwitchWithValue("load-extension", CefStringFromNS([paths componentsJoinedByString:@","]));
+ }
command_line->AppendSwitchWithValue("autoplay-policy", "document-user-activation-required");
}
@@ -208,6 +235,9 @@ public:
// 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.)
+ // Views-hosted (Chrome-style) DevTools are reported by
+ // CraDevToolsWindowDelegate once their window exists.
+ if (browser->GetHost()->HasView()) return;
if (CraBrowser* o = owner_) [o.delegate browser:o didCreateDevToolsView:view];
return;
}
@@ -244,6 +274,7 @@ class CraClient : public CefClient,
public CefFocusHandler,
public CefPermissionHandler {
public:
+ CraBrowser* owner() { return owner_; }
explicit CraClient(CraBrowser* owner) : owner_(owner) {}
CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() override { return this; }
@@ -273,6 +304,15 @@ public:
if (g_quitting && g_liveBrowsers <= 0) CefQuitMessageLoop();
}
+ void OnBeforeDevToolsPopup(CefRefPtr<CefBrowser> browser, CefWindowInfo& windowInfo, CefRefPtr<CefClient>& client,
+ CefBrowserSettings& settings, CefRefPtr<CefDictionaryValue>& extra_info,
+ bool* use_default_window) override {
+ CraBrowser* o = owner_;
+ if (!o) return;
+ client = new DevToolsClient(NSZeroRect, o, o.containerView);
+ *use_default_window = false;
+ }
+
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,
@@ -285,11 +325,12 @@ public:
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
+ client = [host cefClient];
+ if (g_chromeHosting) return false; // Views path: CraChromeViewDelegate hosts the popup view
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
}
@@ -306,6 +347,13 @@ public:
}
void OnLoadEnd(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int httpStatusCode) override {
+ // Every frame reports Picture in Picture changes (the events don't bubble, hence capture).
+ frame->ExecuteJavaScript(
+ "(function(){if(window.__craPip)return;window.__craPip=1;"
+ "document.addEventListener('enterpictureinpicture',function(){console.log('__cra_pip:1');},true);"
+ "document.addEventListener('leavepictureinpicture',function(){console.log('__cra_pip:0');},true);"
+ "if(document.pictureInPictureElement)console.log('__cra_pip:1');})();",
+ frame->GetURL(), 0);
if (!frame->IsMain()) return;
CraBrowser* o = owner_;
if (!o) return;
@@ -328,6 +376,22 @@ public:
bool OnConsoleMessage(CefRefPtr<CefBrowser> browser, cef_log_severity_t level, const CefString& message,
const CefString& source, int line) override {
std::string m = message.ToString();
+ if (m.compare(0, 10, "__cra_pip:") == 0) {
+ CraBrowser* o = owner_;
+ if (!o) return true;
+ std::string v = m.substr(10);
+ if (v == "1" || v == "0") {
+ BOOL active = (v == "1");
+ if (o.isInPictureInPicture != active) {
+ o.isInPictureInPicture = active;
+ if ([o.delegate respondsToSelector:@selector(browser:didChangePictureInPicture:)])
+ [o.delegate browser:o didChangePictureInPicture:active];
+ }
+ } else if (v.compare(0, 3, "err") == 0) {
+ NSLog(@"CraCEF: Picture in Picture %s", v.c_str());
+ }
+ return true;
+ }
const std::string prefix = "__cra_theme:";
if (m.compare(0, prefix.size(), prefix) != 0) return false;
CraBrowser* o = owner_;
@@ -432,6 +496,13 @@ public:
model->InsertItemAt(index++, kMenuCopyImageURL, "Copy Image Address");
model->InsertSeparatorAt(index++);
}
+ // Chrome-style menus already carry Chrome's own "Picture in picture" item.
+ if (params->GetMediaType() == CM_MEDIATYPE_VIDEO && (params->GetMediaStateFlags() & CM_MEDIAFLAG_CAN_PICTURE_IN_PICTURE) &&
+ model->GetIndexOf(IDC_CONTENT_CONTEXT_PICTUREINPICTURE) < 0) {
+ bool inPiP = params->GetMediaStateFlags() & CM_MEDIAFLAG_PICTURE_IN_PICTURE;
+ model->InsertItemAt(index++, kMenuPictureInPicture, inPiP ? "Exit Picture in Picture" : "Picture in Picture");
+ model->InsertSeparatorAt(index++);
+ }
if (model->GetCount() > 0) model->AddSeparator();
model->AddItem(kMenuInspectElement, "Inspect Element");
}
@@ -463,6 +534,9 @@ public:
case kMenuInspectElement:
[o showDevToolsInspectingPoint:NSMakePoint(params->GetXCoord(), params->GetYCoord())];
return true;
+ case kMenuPictureInPicture:
+ [o requestPictureInPictureInFrame:frame automatic:NO x:params->GetXCoord() y:params->GetYCoord()];
+ return true;
default:
return false;
}
@@ -582,6 +656,81 @@ private:
// MARK: - CraBrowser
+// MARK: - Chrome-style hosting (Views). One frameless Chrome window per page; the
+// shell attaches it as a child window over the content card.
+
+class CraDevToolsWindowDelegate : public CefWindowDelegate {
+public:
+ CraDevToolsWindowDelegate(CraBrowser* owner, CefRefPtr<CefBrowserView> view) : owner_(owner), view_(view) {}
+ void OnWindowCreated(CefRefPtr<CefWindow> window) override {
+ window->AddChildView(view_);
+ window->Show();
+ NSView* v = (__bridge NSView*)window->GetWindowHandle();
+ if (CraBrowser* o = owner_) [o.delegate browser:o didCreateDevToolsView:v];
+ }
+ bool IsFrameless(CefRefPtr<CefWindow> window) override { return true; }
+ bool WithStandardWindowButtons(CefRefPtr<CefWindow> window) override { return false; }
+ cef_runtime_style_t GetWindowRuntimeStyle() override { return CEF_RUNTIME_STYLE_CHROME; }
+ CefRect GetInitialBounds(CefRefPtr<CefWindow> window) override { return CefRect(0, 0, 10, 10); }
+private:
+ __weak CraBrowser* owner_;
+ CefRefPtr<CefBrowserView> view_;
+ IMPLEMENT_REFCOUNTING(CraDevToolsWindowDelegate);
+};
+
+class CraChromeViewDelegate : public CefBrowserViewDelegate {
+public:
+ explicit CraChromeViewDelegate(CraBrowser* owner) : owner_(owner) {}
+ ChromeToolbarType GetChromeToolbarType(CefRefPtr<CefBrowserView> browser_view) override { return CEF_CTT_NONE; }
+ cef_runtime_style_t GetBrowserRuntimeStyle() override { return CEF_RUNTIME_STYLE_CHROME; }
+ CefRefPtr<CefBrowserViewDelegate> GetDelegateForPopupBrowserView(CefRefPtr<CefBrowserView> browser_view,
+ const CefBrowserSettings& settings,
+ CefRefPtr<CefClient> client, bool is_devtools) override {
+ if (is_devtools) return new CraChromeViewDelegate(owner_);
+ CraClient* cc = static_cast<CraClient*>(client.get());
+ return new CraChromeViewDelegate(cc ? cc->owner() : nil);
+ }
+ bool OnPopupBrowserViewCreated(CefRefPtr<CefBrowserView> browser_view, CefRefPtr<CefBrowserView> popup_browser_view,
+ bool is_devtools) override {
+ if (is_devtools) {
+ // Chrome's DevTools for a Chrome-style page: host it in a frameless
+ // window of ours; the shell docks it beside the page like before.
+ CraBrowser* o = owner_;
+ if (!o) return false;
+ CefWindow::CreateTopLevelWindow(new CraDevToolsWindowDelegate(o, popup_browser_view));
+ return true;
+ }
+ CefRefPtr<CefBrowser> b = popup_browser_view->GetBrowser();
+ CraClient* cc = b ? static_cast<CraClient*>(b->GetHost()->GetClient().get()) : nullptr;
+ CraBrowser* host = cc ? cc->owner() : nil;
+ if (!host) return false;
+ [host hostPopupBrowserView:popup_browser_view];
+ return true;
+ }
+private:
+ __weak CraBrowser* owner_;
+ IMPLEMENT_REFCOUNTING(CraChromeViewDelegate);
+};
+
+class CraChromeWindowDelegate : public CefWindowDelegate {
+public:
+ CraChromeWindowDelegate(CraBrowser* owner, CefRefPtr<CefBrowserView> view) : owner_(owner), view_(view) {}
+ void OnWindowCreated(CefRefPtr<CefWindow> window) override {
+ window->AddChildView(view_);
+ window->Show();
+ NSView* v = (__bridge NSView*)window->GetWindowHandle();
+ if (CraBrowser* o = owner_) [o hostWindowCreated:v.window];
+ }
+ bool IsFrameless(CefRefPtr<CefWindow> window) override { return true; }
+ bool WithStandardWindowButtons(CefRefPtr<CefWindow> window) override { return false; }
+ cef_runtime_style_t GetWindowRuntimeStyle() override { return CEF_RUNTIME_STYLE_CHROME; }
+ CefRect GetInitialBounds(CefRefPtr<CefWindow> window) override { return CefRect(0, 0, 10, 10); }
+private:
+ __weak CraBrowser* owner_;
+ CefRefPtr<CefBrowserView> view_;
+ IMPLEMENT_REFCOUNTING(CraChromeWindowDelegate);
+};
+
@implementation CraBrowser {
CefRefPtr<CefBrowser> _browser;
CefRefPtr<CraClient> _client;
@@ -617,6 +766,13 @@ private:
- (void)createNow {
if (_isClosed || _browser) return;
+ if (g_chromeHosting) {
+ CefBrowserSettings settings;
+ CefRefPtr<CefBrowserView> view = CefBrowserView::CreateBrowserView(
+ _client, CefStringFromNS(_pendingURL ?: @"about:blank"), settings, nullptr, nullptr, new CraChromeViewDelegate(self));
+ CefWindow::CreateTopLevelWindow(new CraChromeWindowDelegate(self, view));
+ return;
+ }
CefWindowInfo windowInfo;
NSRect b = _containerView.bounds;
windowInfo.SetAsChild((__bridge void*)_containerView,
@@ -630,6 +786,15 @@ private:
- (CefRefPtr<CefBrowser>)cefBrowser { return _browser; }
- (CefRefPtr<CefClient>)cefClient { return _client; }
+- (void)hostWindowCreated:(NSWindow*)window {
+ self.hostWindow = window;
+ [self.delegate browser:self didCreateHostWindow:window];
+}
+
+- (void)hostPopupBrowserView:(CefRefPtr<CefBrowserView>)view {
+ CefWindow::CreateTopLevelWindow(new CraChromeWindowDelegate(self, view));
+}
+
- (void)adoptBrowser:(CefRefPtr<CefBrowser>)browser {
_browser = browser;
self.isCreated = YES;
@@ -670,6 +835,11 @@ private:
- (void)showDevToolsInspectingPoint:(NSPoint)point {
if (!_browser) return;
+ if (self.hostWindow) {
+ // Chrome-style: Chrome docks DevTools inside the page window itself.
+ _browser->GetHost()->ShowDevTools(CefWindowInfo(), nullptr, CefBrowserSettings(), CefPoint((int)point.x, (int)point.y));
+ return;
+ }
if (_browser->GetHost()->HasDevTools()) {
_browser->GetHost()->ShowDevTools(CefWindowInfo(), nullptr, CefBrowserSettings(),
CefPoint((int)point.x, (int)point.y));
@@ -710,6 +880,88 @@ private:
}
- (void)stopFinding:(BOOL)clearSelection { if (_browser) _browser->GetHost()->StopFinding(clearSelection); }
- (void)setAudioMuted:(BOOL)muted { if (_browser) _browser->GetHost()->SetAudioMuted(muted); }
+
+// MARK: Picture in Picture
+//
+// Chromium only lets a page enter Picture in Picture while it holds a user
+// activation, which clicks in Cra's own UI never give the page. Cra therefore
+// first sends the page a harmless key (F19: no page or Chromium shortcut
+// listens to it), which the renderer counts as an interaction, then runs the
+// request once `navigator.userActivation` reports active. `x`/`y` (view DIPs,
+// -1 for none) pick the video under a context-menu click; otherwise the
+// playing, largest video wins. Automatic requests (leaving the tab) take only
+// a playing video of some size and skip GIF-like muted loops.
+static NSString* PictureInPictureScript(BOOL automatic, int x, int y) {
+ return [NSString stringWithFormat:
+ @"(function(auto,x,y){try{"
+ "if(document.pictureInPictureElement){if(!auto){document.exitPictureInPicture().catch(function(){});}return;}"
+ "var area=function(v){var r=v.getBoundingClientRect();return r.width*r.height;};"
+ "var c=Array.prototype.slice.call(document.querySelectorAll('video')).filter(function(v){return !v.disablePictureInPicture&&v.readyState>=1&&v.videoWidth>0;});"
+ "if(auto){c=c.filter(function(v){return !v.paused&&!v.ended&&!(v.muted&&v.loop)&&area(v)>=20000;});}"
+ "if(!c.length){console.log('__cra_pip:none');return;}"
+ "var v=null;"
+ "if(x>=0){v=c.filter(function(e){var r=e.getBoundingClientRect();return x>=r.left&&x<=r.right&&y>=r.top&&y<=r.bottom;}).sort(function(a,b){return area(a)-area(b);})[0]||null;}"
+ "if(!v){c.sort(function(a,b){return ((b.paused?0:1)-(a.paused?0:1))||(area(b)-area(a));});v=c[0];}"
+ "var go=function(){v.requestPictureInPicture().then(function(){console.log('__cra_pip:ok');}).catch(function(e){console.log('__cra_pip:err '+e.name+': '+e.message);});};"
+ "var n=0;var t=setInterval(function(){if((navigator.userActivation&&navigator.userActivation.isActive)||++n>20){clearInterval(t);go();}},50);"
+ "}catch(e){console.log('__cra_pip:err '+e);}})(%d,%d,%d);", automatic ? 1 : 0, x, y];
+}
+
+- (void)nudgeUserActivation {
+ if (!_browser) return;
+ CefKeyEvent key;
+ key.windows_key_code = 0x82; // VK_F19
+ key.native_key_code = 0x50; // kVK_F19
+ key.modifiers = 0;
+ key.character = 0;
+ key.unmodified_character = 0;
+ key.is_system_key = 0;
+ key.type = KEYEVENT_RAWKEYDOWN;
+ _browser->GetHost()->SendKeyEvent(key);
+ key.type = KEYEVENT_KEYUP;
+ _browser->GetHost()->SendKeyEvent(key);
+}
+
+- (void)requestPictureInPictureInFrame:(CefRefPtr<CefFrame>)frame automatic:(BOOL)automatic x:(int)x y:(int)y {
+ if (!_browser) return;
+ if (self.isInPictureInPicture) {
+ if (!automatic) [self exitPictureInPicture];
+ return;
+ }
+ [self nudgeUserActivation];
+ double zoom = pow(1.2, _browser->GetHost()->GetZoomLevel()); // view DIPs → CSS px
+ NSString* hit = PictureInPictureScript(automatic, x < 0 ? -1 : (int)(x / zoom), y < 0 ? -1 : (int)(y / zoom));
+ NSString* any = PictureInPictureScript(automatic, -1, -1);
+ if (frame) {
+ // Click coordinates are relative to the top-level view, so only the main frame can hit-test.
+ frame->ExecuteJavaScript(CefStringFromNS(frame->IsMain() ? hit : any), frame->GetURL(), 0);
+ return;
+ }
+ // Every frame looks for a video: embedded players live in iframes.
+ std::vector<CefString> ids;
+ _browser->GetFrameIdentifiers(ids);
+ for (const auto& id : ids) {
+ CefRefPtr<CefFrame> f = _browser->GetFrameByIdentifier(id);
+ if (f && f->IsValid()) f->ExecuteJavaScript(CefStringFromNS(any), f->GetURL(), 0);
+ }
+}
+
+- (void)requestPictureInPictureAutomatic:(BOOL)automatic {
+ [self requestPictureInPictureInFrame:nullptr automatic:automatic x:-1 y:-1];
+}
+
+- (void)exitPictureInPicture {
+ if (!_browser) return;
+ std::vector<CefString> ids;
+ _browser->GetFrameIdentifiers(ids);
+ for (const auto& id : ids) {
+ CefRefPtr<CefFrame> f = _browser->GetFrameByIdentifier(id);
+ if (f && f->IsValid()) {
+ f->ExecuteJavaScript("if(document.pictureInPictureElement){document.exitPictureInPicture().catch(function(){});}",
+ f->GetURL(), 0);
+ }
+ }
+}
- (void)print { if (_browser) _browser->GetHost()->Print(); }
- (void)viewSource { if (_browser) _browser->GetMainFrame()->ViewSource(); }
- (void)executeJavaScript:(NSString*)script {
@@ -732,8 +984,48 @@ private:
// MARK: - Runtime
+// MARK: - Chrome-style spike (extensions need Chrome style; on macOS that means a Views window)
+
+static void (^g_spikeWindowHandler)(NSWindow*) = nil;
+
+class SpikeBrowserViewDelegate : public CefBrowserViewDelegate {
+public:
+ ChromeToolbarType GetChromeToolbarType(CefRefPtr<CefBrowserView> browser_view) override { return CEF_CTT_NONE; }
+ cef_runtime_style_t GetBrowserRuntimeStyle() override { return CEF_RUNTIME_STYLE_CHROME; }
+ IMPLEMENT_REFCOUNTING(SpikeBrowserViewDelegate);
+};
+
+class SpikeWindowDelegate : public CefWindowDelegate {
+public:
+ explicit SpikeWindowDelegate(CefRefPtr<CefBrowserView> view) : view_(view) {}
+ void OnWindowCreated(CefRefPtr<CefWindow> window) override {
+ window->AddChildView(view_);
+ window->Show();
+ NSView* v = (__bridge NSView*)window->GetWindowHandle();
+ if (g_spikeWindowHandler && v.window) g_spikeWindowHandler(v.window);
+ }
+ bool IsFrameless(CefRefPtr<CefWindow> window) override { return true; }
+ bool WithStandardWindowButtons(CefRefPtr<CefWindow> window) override { return false; }
+ cef_runtime_style_t GetWindowRuntimeStyle() override { return CEF_RUNTIME_STYLE_CHROME; }
+ CefRect GetInitialBounds(CefRefPtr<CefWindow> window) override { return CefRect(300, 200, 900, 640); }
+private:
+ CefRefPtr<CefBrowserView> view_;
+ IMPLEMENT_REFCOUNTING(SpikeWindowDelegate);
+};
+
@implementation CraCEFRuntime
++ (void)setChromeHosting:(BOOL)enabled { g_chromeHosting = enabled; }
++ (BOOL)chromeHosting { return g_chromeHosting; }
+
++ (void)spikeChromeWindowWithURL:(NSString*)url handler:(void (^)(NSWindow*))handler {
+ g_spikeWindowHandler = [handler copy];
+ CefBrowserSettings settings;
+ CefRefPtr<CefBrowserView> view = CefBrowserView::CreateBrowserView(
+ new DevToolsClient(NSZeroRect, nil, nil), CefStringFromNS(url), settings, nullptr, nullptr, new SpikeBrowserViewDelegate());
+ CefWindow::CreateTopLevelWindow(new SpikeWindowDelegate(view));
+}
+
+ (BOOL)initializeWithCachePath:(NSString*)cachePath
userAgentProduct:(NSString*)product
logPath:(NSString*)logPath
@@ -819,7 +1111,7 @@ private:
if ([fr isKindOfClass:[NSView class]]) {
NSView* v = (NSView*)fr;
for (CraBrowser* b in [g_allBrowsers allObjects]) {
- if ([v isDescendantOf:b.containerView]) {
+ if ([v isDescendantOf:b.containerView] || (b.hostWindow && key == b.hostWindow)) {
[key sendEvent:event];
return;
}
diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.h
index f02197f..64c8bfd 100644
--- a/Sources/CraCEF/include/CraCEF.h
+++ b/Sources/CraCEF/include/CraCEF.h
@@ -48,6 +48,8 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
- (void)browser:(CraBrowser *)browser didCreateDevToolsView:(NSView *)view;
/// The DevTools browser closed (either mode).
- (void)browserDidCloseDevTools:(CraBrowser *)browser;
+/// Chrome-style hosting: the page's window exists (also for popups).
+- (void)browser:(CraBrowser *)browser didCreateHostWindow:(NSWindow *)window;
/// 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
@@ -59,13 +61,21 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
- (void)browser:(CraBrowser *)browser requestsPermissionForOrigin:(NSString *)origin kinds:(NSUInteger)kinds completion:(void (^)(BOOL allowed))completion;
- (void)browserDidReceiveFocus:(CraBrowser *)browser;
- (void)browserDidClose:(CraBrowser *)browser;
+@optional
+/// A video of this page entered or left Chromium's Picture in Picture window
+/// (whether the page, the user or Cra asked for it).
+- (void)browser:(CraBrowser *)browser didChangePictureInPicture:(BOOL)active;
@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.
+/// Embedded (Alloy) hosting: a plain NSView that owns the Chromium view. Put
+/// it in your hierarchy and size it; Chromium follows.
@property (nonatomic, readonly) NSView *containerView;
+/// Chrome-style hosting (see +[CraCEFRuntime setChromeHosting:]): the page
+/// lives in its own frameless Chrome window, delivered through
+/// -browser:didCreateHostWindow:. Attach it as a child window and size it.
+@property (nonatomic, readonly, nullable) NSWindow *hostWindow;
@property (nonatomic, readonly, copy) NSString *currentURL;
@property (nonatomic, readonly, copy) NSString *currentTitle;
@property (nonatomic, readonly) BOOL isLoading;
@@ -96,6 +106,14 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
- (void)findText:(NSString *)text forward:(BOOL)forward matchCase:(BOOL)matchCase findNext:(BOOL)findNext;
- (void)stopFinding:(BOOL)clearSelection;
- (void)setAudioMuted:(BOOL)muted;
+/// Pops the page's video out into Chromium's floating Picture in Picture
+/// window. Manual requests toggle (a second call brings the video back).
+/// `automatic` is the "leaving a video tab" case: only a playing video of some
+/// size qualifies, and nothing happens when there is none.
+- (void)requestPictureInPictureAutomatic:(BOOL)automatic;
+- (void)exitPictureInPicture;
+/// YES while a video of this page is in the Picture in Picture window.
+@property (nonatomic, readonly) BOOL isInPictureInPicture;
- (void)print;
- (void)viewSource;
- (void)executeJavaScript:(NSString *)script;
@@ -106,6 +124,12 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
@interface CraCEFRuntime : NSObject
/// Call once, after NSApplication exists, before creating browsers.
+/// Experiment: a Chrome-style (extension-capable) Views window; the handler gets its NSWindow.
++ (void)spikeChromeWindowWithURL:(NSString *)url handler:(void (^)(NSWindow *))handler;
+/// Host pages as Chrome-style windows (Chrome extensions, Chrome's docked
+/// DevTools) instead of embedded Alloy views. Set before any browser exists.
++ (void)setChromeHosting:(BOOL)enabled;
++ (BOOL)chromeHosting;
+ (BOOL)initializeWithCachePath:(NSString *)cachePath
userAgentProduct:(NSString *)product
logPath:(NSString *)logPath
diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.md
index 9180cc6..d86d043 100644
--- a/docs/arc-reverse-engineering.md
+++ b/docs/arc-reverse-engineering.md
@@ -193,3 +193,210 @@ the main toolbar; that button and `InspectorFrontendHost.closeWindow()` reach th
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.
+
+### Developer Mode, shortcuts, extensions (24 Oct, evening)
+
+Arc's View ▸ Developer submenu (read via Accessibility): View Source ⌥⌘U, Developer Tools
+⌥⌘I, Inspect Elements ⌥⌘C, JavaScript Console ⌥⌘J, "Turn off Developer Mode for this
+site" ⌃D. ⇧⌘D is Hide Toolbar and ⌘D is Pin/Unpin Tab. Developer Mode is per site and
+swaps the toolbar: default = nav buttons left, centred friendly URL (host bright, path dim)
+behind a link glyph, sidebar toggle right; developer = lock + full monospace URL left,
+copy/capture/DevTools/source icons right, nav buttons in the sidebar's title row. Cra
+stores the hosts in `AppSettings.developerHosts`.
+
+Extensions: CEF 154 has no extension API for Alloy-style browsers. A spike
+(`cra://debug?chromeSpike=<url>`) proved the alternative: a Chrome-style Views window
+(`CefWindow` + `CefBrowserView`, `GetChromeToolbarType = CEF_CTT_NONE`, frameless, runtime
+style CHROME) attached as a child window over the content area loads unpacked extensions
+from `~/Library/Application Support/Cra/Extensions/*` via `--load-extension` (an MV3
+content script rendered its banner). Chrome style also docks DevTools natively. Moving the
+page browsers to that hosting is the route to extensions; one Chrome-style window per tab.
+
+## Split View (Arc 1.170.0, 24 Oct 2026, evening)
+
+Method: REA CLI 6.4.0 `inspect-macho` (Evidence ev_84b238…, arm64 SHA-256 25af5f4e…) and `demangle-swift`
+(ev_026c6350…); REA's `inspect-native-dispatch-metadata` refuses the 80 MB executable (64 MiB budget). The
+model below comes from parsing the arm64 slice's Swift reflection metadata (`__swift5_types` /
+`__swift5_fieldmd` / `__swift5_proto`, nominal types with their stored properties and enum cases) and
+`otool -oV` Objective-C class data (selectors, ivars), plus the user's own
+~/Library/Application Support/Arc/StorableSidebar.json (21 split items) and StorableWindows.json.
+No decompiler, so property names and types are observed; the algorithms are inferred from them.
+
+### Where it lives
+- [O] Everything is in Arc's native Swift shell, not in Chromium. ArcCore (Chromium) only carries upstream
+ Chrome's own `tabs.createSplit` / `splitViewId` extension API and "Cannot create split view with
+ non-adjacent tabs" strings; the Arc UI never references them.
+- [O] Generic engine: `ARCUI.SplitViewController: NSViewController` (module ARCUI, file
+ ARCUI/SplitViewController.swift) with `SplitViewControllerLayout` (pure layout types) and
+ `SplitViewContentPaneView`. It is NOT built on NSSplitView: no Arc class implements any
+ `splitView:…` delegate selector (the NSSplitViewDelegate selectors in the binary are protocol metadata
+ only). The one NSSplitView subclass, `WebContentViewControllerSplitView` (private to
+ WindowContentViewController, overrides mouseDown/mouseUp/viewDidEndLiveResize, `onDidEndLiveResize`),
+ is a per-pane inner split, not the pane layout. [I]
+- [O] Arc-specific glue: `Arc.WindowContentsContainerViewController: XiblessViewController<NSView>`
+ conforms to `SplitViewControllerDelegate`, owns one lazy `splitViewController`, a
+ `LayoutConstraintsMap<SplitViewConstraintType>` (leading, trailing, top, bottom, minHeight) and a lazy
+ `splitViewTopConstraint`. Each pane is an `Arc.WindowContentViewController` (conforms to
+ `SplitViewContentPaneWithInsets`); an empty/drop pane is `SplitViewContentPlaceholderView` (NSView with
+ `contentInsets`, a `BorderView` with `borderColor`, also `SplitViewContentPaneWithInsets`).
+- [O] State is TCA (ComposableArchitecture): `Store<WindowState, WindowAction>` with view stores; feature
+ modules WindowContents (`SplitViewState`, `SplitViewLayoutCache`, `WindowSplitViewLayout`,
+ `WindowContentPresentationDisposition`), SharedWindowFeature (`WindowAction.SplitViewAction`),
+ BaseModels (`SidebarSplitViewData`, `SplitViewPaneMenuOperation`), SidebarUI (`SplitViewCellState`).
+
+### Data model
+- [O] Sidebar: a split is a sidebar item like a folder. `SidebarItemData.splitView(SidebarSplitViewData)`
+ with `itemWidthFactors: [Identifier<SidebarItem>: CGFloat]`, `layoutOrientation: horizontal|vertical`,
+ `timeLastActiveAt: Date?`, `customInfo: { iconType: SidebarCustomIcon }?` (user icon, used together with
+ the item `title` when renamed), `focusItemID: Identifier<SidebarItem>?`. The tabs are the item's
+ `childrenIds` (order = pane order, left→right / top→bottom). JSON on this Mac:
+ `{"data":{"splitView":{"itemWidthFactors":[<id>,0.3835,<id>,0.6165],"layoutOrientation":"horizontal",
+ "focusItemID":<id>,"timeLastActiveAt":…,"customInfo":null}},"childrenIds":[…],"parentID":<container>,…}`.
+ All 21 local splits: 2 children, horizontal, parent = a space's pinned/unpinned container (not inside
+ folders here), title/customInfo never set. Untouched splits store a single factor `[firstChild, 0.5]`;
+ after a drag both factors are stored and sum to 1.0. One zombie split with 0 children exists; the
+ binary logs "Noticed zombie split view (without any children)" (`ZombieSplitSeenLocation`:
+ rawUpdate/appliedChange/publishedValue) and repairs it on sync. [I] Missing factors = equal share of
+ the remainder.
+- [O] Window: `WindowContents.State { windowContents: [WindowContentID: WindowContent], splitViewState,
+ modalWindowContentV2State, windowContentSidebarItemMap: BidirectionalMap<WindowContentID,
+ Identifier<SidebarItem>> }`. `SplitViewState { windowContentIDs: OrderedSet<WindowContentID>,
+ layoutOrientation, interactionState, focusedContentID }`; only `windowContentIDs` + `focusedContentID`
+ are Codable (StorableWindows.json `splitViewState`), orientation and widths are rebuilt from the
+ sidebar item. `InteractionState { activePaneEditStyles: Set<.dragAndDrop>, proposedWindowContentDropTarget:
+ WindowContentID?, isResizingPanes }`. Legacy `SplitViewState_Legacy { windowContentIDs }`.
+- [O] Per-window width cache: `WindowSplitViewLayout { paneWidths: [CGFloat] }` kept by
+ `SplitViewLayoutCache { storeLayoutForWindowID, layoutForWindowID }` (a TCA DependencyKey) and
+ handed to the view as `restorableSplitViewLayout`; `SplitViewWindowContentContext { numPanes,
+ restorablePaneWidths: [CGFloat]?, splitViewLayoutOrientation }` is what the container passes to
+ `SplitViewController`.
+- [O] Container view state (`WindowContentsContainerViewController.ViewState`): `splitViewWindowContentIDs:
+ OrderedSet<WindowContentID>`, `focusedContentID`, `splitViewLayoutOrientation`, `restorableSplitViewLayout`,
+ `canDragOntoSplit`, `isDraggingToCreateSplitView`, `shouldShowInteractivePaneInsertionHandle`,
+ `contentInsets`, `contentCornerRadius`, `hiddenScrimEdges`, `sidebarPresentation`.
+
+### The layout engine (ARCUI.SplitViewController)
+- [O] Properties: `draggerHandleWidth`, `draggerHandleHitTargetOutset`, `minimumPaneWidth`,
+ `layoutOrientation`, `displayInteractivePaneInsertionDraggerHandle`, `allowInteractivePaneInsertion`,
+ `verticalLayoutOrientationFromDragAllowed`, `shouldDisplayDraggerPaneForSecondaryAxis`,
+ `isDragDropHapticFeedbackEnabled`, weak `delegate`, `contentPanes: OrderedDictionary<Identifier<ContentPane>,
+ ContentPane>`, `paneResizeState?`, `dragDestinationState?`, `dragSourceState?`,
+ `dragInfoSubject: PassthroughSubject<NSDraggingInfo, Never>`, lazy `minimumWidthConstraint`.
+- [O] `SplitViewControllerLayout.ContentPane { id, view: NSView & SplitViewContentPane, trailingDraggerHandle,
+ bottomDraggerHandle: DraggerHandle { view: NSView & SplitViewControllerDraggerHandleType }, widthFactor: CGFloat,
+ resizeStyle: flexible|fixed, displayState: collapsed|expanded, inFlightTransition: StateTransition?,
+ content: .dropRegion(NSView) | .viewController(SplitViewContentPaneContentViewController) }`.
+ `StateTransition { identifier: UUID, targetState, style: .animated(removePaneOnCompletion: Bool) | .immediate,
+ draggerHandleWidth: CGFloat? }`. `ContentPanePair { leading, trailing? }`.
+- [O] `SplitViewControllerLayout.Context { contentPanes, containerSize, backingScaleFactor, minimumPaneWidth,
+ draggerHandleWidth, displayInteractivePaneInsertionDraggerHandle, shouldDisplayDraggerPaneForSecondaryAxis,
+ layoutOrientation, yAxisOriginAtTop }` → frames are a pure function of the context (pixel-snapped via
+ backingScaleFactor). [I] Each pane gets `widthFactor × (container − handles)` along the main axis, clamped to
+ `minimumPaneWidth`; every pane carries its own trailing (horizontal) and bottom (vertical) handle view, the
+ last one hidden or used as the "insert a pane here" handle when `displayInteractivePaneInsertionDraggerHandle`.
+- [O] Resize: `PaneResizeState { initialClickLocationInDragHandle: CGPoint, canSnapToCenter, isCenterSnapped }`
+ driven by `handleDraggerPanGesture:` (NSPanGestureRecognizer) and `handleDraggerDoubleClickGesture:`
+ (double-click a handle = reset to equal widths, [I]). Dragging snaps to the 50/50 centre when allowed.
+ Pane add/remove animates via `StateTransition` (collapsed ↔ expanded, remove on completion).
+- [O] Panes are hosted in `SplitViewContentPaneView: NSView { contentView, contentConstraints:
+ LayoutConstraintsMap<NSLayoutConstraint.Attribute>, lockContentWidth: Bool, lockedContentAlignment:
+ leading|center|trailing, userInteractionEnabled }` (overrides hitTest). [I] While a handle is being
+ dragged the web content keeps its old width and is pinned to one edge instead of relayouting Chromium on
+ every mouse move; `userInteractionEnabled=false` blocks the page from eating the drag.
+ `WindowContentViewController` adds `ContentResizeMode { intrinsic, throttle, locked }`,
+ `pendingResizeFrames`, `resizeTimer`, `lockedContentSize`, `contentResizeThrottleSubscription`; the
+ container has `isAnimatingResize` and `ContentSizeThrottleFlags` (OptionSet).
+- [O] Handles: Arc's `SplitViewDraggerHandleView: FlippedView` (vertical divider: lazy `handle` NSView pill,
+ `backgroundView: WindowBackgroundContainerView?` so the space theme shows through the gap, `isHighlighted`,
+ `draggableArea: NSTrackingArea`, `draggableRegion: CGRect`, `resetCursorRects`, mouseEntered/Exited,
+ `contentAppearance`) with `ViewState { displayBackgroundView, windowBackgroundConfiguration,
+ contentOverBackgroundAppearance, isHandleVisible, metalWindowBackgroundRenderingEnabled }`;
+ `SplitViewBottomDraggerHandleView` for vertical layouts adds `handle: .dragger | .scrimLoader` and
+ `isContentBelowLoading` (the handle doubles as a loading scrim). ARCUI ships a plain
+ `SplitViewControllerDefaultDraggerHandleView`.
+
+### Drag and drop (how a split is created with the mouse)
+- [O] `SplitViewController` is both `NSDraggingSource` and `NSDraggingDestination` (draggingEntered/Updated/
+ Exited/Ended, prepareForDragOperation, performDragOperation, wantsPeriodicDraggingUpdates,
+ updateDraggingItemsForDrag, draggingSession:…). `DragSourceState { contentPaneID, initialIndex,
+ initialWidthFactor, contentPaneSnapshot: NSImage?, contentPaneSize }` = reordering a pane by dragging its
+ toolbar (snapshot image as drag preview). `DragDestinationState { operation: NSDragOperation,
+ isDraggingInView, proposedTarget: DropTarget?, isDraggingContentPane }`.
+- [O] `DropTarget = .replaceContent(index) | .insertContent(index)`; `ProposedDropTargetInfo { target,
+ dropRegionInsertionIndex: Int?, existingDropRegion: ContentPane?, layoutOrientation }`. [I] Hovering near an
+ edge inserts a temporary `.dropRegion` pane (placeholder view, animated open) at that index; hovering over
+ the middle of a pane proposes replacing it; `verticalLayoutOrientationFromDragAllowed` lets a drop on the
+ top/bottom edge flip the layout to vertical.
+- [O] What can be dropped (`WindowContentsContainerViewController.SplitViewDragItem`): `.sidebarItem(id)`
+ or `.url(URL)`. Actions: `onDropSidebarItem(itemID, target, layoutOrientation, maybeMoveDecision)`,
+ `onDropURL(url, target, layoutOrientation)`, `onDidUpdateSplitViewProposedDropTarget(WindowContentID?)`,
+ `onDidBegin/EndSplitViewInteractivePaneEditingWith(.dragAndDrop)`.
+- [O] Sidebar side: dragging a tab over another tab's left/right half (`SidebarDropTargetRegion = left|right`,
+ `TabSplitViewPosition = left|right`) shows `SplitDragPreviewView` (title, favicon, "tab info" and "empty"
+ background containers) after `splitDropTargetDelaySatisfied`; dropping makes a split item. Flags:
+ `drag-to-combine-tabs-into-split-enabled`, `sidebar-drag-to-split-preview-ui-enabled`, `win-drag-to-split-enabled`.
+ Onboarding copy: "Drag a tab from your sidebar into the middle of the screen to create a Split View."
+
+### Commands, menus, entry points
+- [O] `WindowAction.SplitViewAction`: `addPanel(index: InsertionLocation, showCommandBar: Bool)`,
+ `movePanel(from:to:)`, `onDropSidebarItem`, `onDropURL`, `onDidBeginWindowContentsSplitViewPaneResize`,
+ `onDidEndWindowContentsSplitViewPaneResize(WindowSplitViewLayout)`, `onDidUpdateSplitViewProposedDropTarget`,
+ `onPaneCreated(source)`, `onPaneClosed`, `onDidRestoreSplitViewState`, `containerDelegate(…)`,
+ `panelAction(ContentToolbarAction)`. Container delegate: `onDidAddItemsToContainer`,
+ `onDidMoveItemsWithinContainer`, `onDidRemoveItemsFromContainers(itemIDs)`, `onDidAdjustLayoutOrientation`.
+- [O] Where a new pane goes: `WindowContentPresentationDisposition.splitView(SplitViewTarget)` with
+ `.paneAtIndex(Int) | .newPane(InsertionLocation) | .pane(WindowContentID) | .replaceAllPanes |
+ .firstEmptyOrNewPane`; `InsertionLocation = .index(Int) | .after(id) | .before(id) | .last | .afterFocusedPane`.
+- [O] Pane menu (`SplitViewPaneMenuOperation`, each `.enabled|.disabled`): moveLeft, moveRight, addPaneLeft,
+ addPaneRight, addPaneTop, addPaneBottom, separate, copyLink, flipLayoutOrientation. Toolbar menu items
+ (`ContentPanelSplitViewMenuItemType`): move/add/separate/copyLink × horizontal/vertical, flipToVertical,
+ flipToHorizontal. Sidebar context menu on a split: `childItem(id, .separateFromSplitView)`, `separateAllItems`,
+ `addPanel`, `flipLayoutOrientation`. Toolbar hover actions: separate, close, addHorizontal, addVertical,
+ move, copyLink (`split-view-actions-hover-button-enabled`).
+- [O] Menu strings: "Add Vertical Split View", "New Bottom Split", "Add Bottom Split", "Convert to
+ Horizontal/Vertical Split View", "Flip to horizontal/vertical split view", "Close Split View Pane", "Separate Tab
+ from Split", "Remove Tab from Split View", "Open in Split View", "Add to Split View", "Share Split View",
+ "Multitask with Split View", "Switch to next/previous Split View", "Jumps to the first…fourth Split View page".
+ Type-travel candidates: AddLeft/Right/Top/BottomSplit, ConvertToHorizontal/VerticalSplitView,
+ NewVerticalSplitViewPane. Key bindings (see above): Add Split View ⌃⇧=, Close Split Pane ⌃⇧−.
+- [O] Entry sources tracked (`SplitViewEnteredSource`): plusButton, windowContent, dragAndDrop, menu,
+ contextMenu, alternateClick (option-click a tab), typeTravel, tabCreation, easel, navigationBar, tabHoverMenu.
+ Option-click on a split child's close button un-splits (`option-click-split-tab-close-button-to-unsplit-enabled`).
+- [O] Limits: errors `splitViewMaximumPanesExceeded`, `splitViewTargetOutOfRange`,
+ `unableToInsertSplitViewContainer`, `missingSplitViewContainer`; `ModalParentSplitState { parentIsSplitCompatible,
+ numberOfPanels, maximumNumberOfPanels, layoutOrientation }`. [I] Max is 4 panes (shortcuts stop at "fourth").
+ Toolbar `shouldShowSplitViewClose` only in a split; `maximizeCurrentSplitViewPane:` exists (notification token).
+
+### Sidebar cell
+- [O] `SplitViewCellView: SelectableCellView<SplitViewCellState>` with `SplitViewCellState { sidebarItemID,
+ isCurrentItem, isContentVisible, isKeyDraggedItem, isHighlighted, isMultiSelected, shouldDim, canResetTab,
+ layoutStyle: .childItems(OrderedDictionary<id, ChildItemState>) | .customInfo(CustomInfo), colorPalette,
+ closeItemShortcut, lastUpdatedLocally, hasLeadingRecordingIndicator, dropTargetRegion?, closeButtonConfiguration,
+ closeButtonAction, shouldPerformUserAttentionAnimation }`. `ChildItemState { itemID, iconType: FaviconType?,
+ title, isGroupSelected, isRecording, closeButtonConfiguration, optionClickSplitTabCloseButtonToUnsplitEnabled,
+ newSplitSeparationMechanismsEnabled }`. `CustomInfo { title, isEditingTitle, icon: .childItemCount(Int) |
+ .customIcon(SidebarCustomIcon) }`.
+- [O] Views: `SplitViewCellChildrenContainerView` (one `SplitViewCellChildItemView` per tab, `separatorLayers:
+ [CALayer]` between them, `isGroupHovered`, `InsetSpec { defaultInset, extendedInset }`), each child with
+ favicon + title + its own close button and recording dot; renamed splits show `SplitViewCellCustomInfoView`
+ (icon or item-count badge `SplitViewCellItemCountIconView`, editable title, hover subtitle). Icons:
+ icon-split-add-left/right/top/bottom, icon-split-horizontal/vertical, icon-split-move-*, icon-separate-from-split,
+ icon-split-share-*, icon-split-x; colour asset SplitViewLeftBackground.
+
+### Plan for Cra (design, not observation)
+1. Model: add `ItemData.split(SplitData)` to SidebarModel with `widthFactors: [UUID: Double]`,
+ `orientation`, `focusTabID`; children = the pane tabs (reuse `childrenIds`/`parentID` like folders). Store
+ per-window `splitState { paneTabIDs, focusedTabID }` in WindowPrefs; rebuild widths from the item.
+2. Engine: a `SplitPaneLayout` value type (panes with widthFactor, min width, handle width, orientation,
+ pixel snap) → frames; a `SplitContainerView` in ShellView's `webContainer` that owns one pane view and one
+ handle view per visible tab. Cra's CEF browsers are child windows positioned by
+ `MainWindowController.positionPageWindows`, so each pane needs its own screen rect: change
+ `BrowserManager.show` to a set of visible tabs and `onWebFrame` to deliver per-tab rects.
+3. Resize: pan on the handle updates factors; during the drag freeze each page window's size (Cra already
+ has `frozenWebBounds`) and only move it, resize once on mouse-up (Arc's lockContentWidth/throttle);
+ double-click = equal widths; snap at 50/50.
+4. Creation: ⌃⇧= adds an empty pane (placeholder with dashed border + command bar); drag a sidebar tab onto
+ the content card: edges insert, centre replaces; option-click a tab adds it as a pane; context menu
+ "Open in Split View"; "Separate", "Flip orientation", "Close pane".
+5. Sidebar: a grouped row showing each pane's favicon+title with hairline separators, group selection
+ highlight, per-child close, rename → icon/count badge.
diff --git a/docs/release.md b/docs/release.md
new file mode 100644
index 0000000..8adb81f
--- /dev/null
+++ b/docs/release.md
@@ -0,0 +1,81 @@
+# Releasing Cra
+
+Goal: a build that installs like any other Mac app. Download the DMG, drag Cra to
+Applications, open it. No right-click, no warnings. That needs three things on top of
+the plain build: a Developer ID signature with the hardened runtime, Apple's
+notarization ticket stapled to the app and the DMG, and a packaged download.
+Everything is scripted; the only manual part is obtaining the certificate once.
+
+## One-time setup
+
+1. **Apple Developer Program** membership for the account that will sign.
+2. **Developer ID Application certificate.** In Xcode → Settings → Accounts → Manage
+ Certificates, add "Developer ID Application". Export it from Keychain Access as a
+ `.p12` with a password. Note the identity string, for example
+ `Developer ID Application: Victor Kildahl (ABCDE12345)`:
+ `security find-identity -v -p codesigning`.
+3. **Notarization credentials.** Create an app-specific password at appleid.apple.com.
+ Locally you can store it once: `xcrun notarytool store-credentials cra --apple-id
+ [email protected] --team-id ABCDE12345` and then set `NOTARY_KEYCHAIN_PROFILE=cra`.
+4. **GitHub secrets** on `VictorKildahl/cra` (Settings → Secrets and variables → Actions):
+
+ | Secret | Value |
+ |---|---|
+ | `MACOS_CERTIFICATE_P12` | `base64 -i DeveloperID.p12 \| pbcopy` |
+ | `MACOS_CERTIFICATE_PASSWORD` | the `.p12` password |
+ | `MACOS_SIGN_IDENTITY` | the identity string from step 2 |
+ | `APPLE_ID` | the Apple ID email |
+ | `APPLE_TEAM_ID` | the 10-character team id |
+ | `APPLE_APP_PASSWORD` | the app-specific password |
+
+Until these exist the Release workflow still runs: it publishes an ad-hoc build as a
+pre-release with a note about right-clicking to open.
+
+## Cutting a release
+
+```sh
+# 1. Add the release to the website's src/content/releases.ts and bump CRA_VERSION defaults if needed.
+# 2. Tag and push. The Release workflow builds, signs, notarizes, packages and publishes.
+git tag v0.1.0
+git push origin v0.1.0
+```
+
+Artifacts land on the GitHub release: `Cra-0.1.0.dmg`, `Cra-0.1.0.zip`, `SHA256SUMS.txt`.
+The website's download button points at `releases/latest`.
+
+## Locally
+
+```sh
+CRA_VERSION=0.1.0 \
+CRA_SIGN_IDENTITY="Developer ID Application: Victor Kildahl (ABCDE12345)" \
+NOTARY_KEYCHAIN_PROFILE=cra \
+scripts/release.sh
+```
+
+`scripts/release.sh` runs `build.sh` (sign, innermost first, with the CEF entitlements),
+notarizes and staples the app, runs `package.sh` (zip, DMG with an Applications link,
+checksums), then notarizes and staples the DMG and checks it with `spctl`.
+Without `CRA_SIGN_IDENTITY` it produces an ad-hoc build and skips notarization.
+
+## What the signing covers
+
+Order matters because each signature seals what is inside it:
+
+1. every `.dylib` in `Chromium Embedded Framework.framework/Libraries`
+2. the framework itself
+3. the five helper apps, each with `resources/CraHelper.entitlements`
+4. `Cra.app` with `resources/Cra.entitlements`
+
+The entitlements are the hardened-runtime exceptions Chromium needs (JIT, unsigned
+executable memory, library validation off, dyld environment variables), plus camera,
+microphone and location so sites can ask for them.
+
+## Later
+
+- **Updates in the app.** Add Sparkle 2 with an appcast generated by the release
+ workflow (`generate_appcast` over `build/dist`), so users get new versions without
+ visiting the site.
+- **Homebrew.** A cask (`brew install --cask cra`) pointing at the DMG and
+ `SHA256SUMS.txt`.
+- **Intel.** The CEF fetch pins `macosarm64`; a universal build needs both CEF
+ distributions and `lipo`.
diff --git a/resources/Cra.entitlements b/resources/Cra.entitlements
new file mode 100644
index 0000000..e75f349
--- /dev/null
+++ b/resources/Cra.entitlements
@@ -0,0 +1,24 @@
+<?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>
+ <!-- Hardened-runtime exceptions Chromium Embedded Framework needs (same set as CEF's cefclient). -->
+ <key>com.apple.security.cs.allow-jit</key>
+ <true/>
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
+ <true/>
+ <key>com.apple.security.cs.disable-library-validation</key>
+ <true/>
+ <key>com.apple.security.cs.allow-dyld-environment-variables</key>
+ <true/>
+ <!-- Sites may ask for these; the Info.plist carries the usage strings. -->
+ <key>com.apple.security.device.audio-input</key>
+ <true/>
+ <key>com.apple.security.device.camera</key>
+ <true/>
+ <key>com.apple.security.personal-information.location</key>
+ <true/>
+ <key>com.apple.security.automation.apple-events</key>
+ <true/>
+</dict>
+</plist>
diff --git a/resources/CraHelper.entitlements b/resources/CraHelper.entitlements
new file mode 100644
index 0000000..8df5c94
--- /dev/null
+++ b/resources/CraHelper.entitlements
@@ -0,0 +1,19 @@
+<?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>
+ <!-- Chromium subprocesses (renderer, GPU, plugin, alerts) run JIT-compiled code. -->
+ <key>com.apple.security.cs.allow-jit</key>
+ <true/>
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
+ <true/>
+ <key>com.apple.security.cs.disable-library-validation</key>
+ <true/>
+ <key>com.apple.security.cs.allow-dyld-environment-variables</key>
+ <true/>
+ <key>com.apple.security.device.audio-input</key>
+ <true/>
+ <key>com.apple.security.device.camera</key>
+ <true/>
+</dict>
+</plist>
diff --git a/scripts/build.sh b/scripts/build.sh
index 84fc546..944181d 100755
--- a/scripts/build.sh
+++ b/scripts/build.sh
@@ -1,7 +1,9 @@
#!/bin/bash
# Builds Cra.app into build/Cra.app.
-# scripts/build.sh release build
+# scripts/build.sh release build, ad-hoc signed
# scripts/build.sh debug debug build
+# CRA_SIGN_IDENTITY="Developer ID Application: …" scripts/build.sh
+# distributable build (see docs/release.md)
set -euo pipefail
cd "$(dirname "$0")/.."
ROOT="$PWD"
@@ -45,12 +47,29 @@ for entry in "|" " (Alerts)|.alerts" " (GPU)|.gpu" " (Plugin)|.plugin" " (Render
echo -n "APPL????" > "$HELPER/Contents/PkgInfo"
done
-# Ad-hoc signatures, innermost first.
+# Code signing, innermost first. Ad-hoc by default; set CRA_SIGN_IDENTITY to a
+# "Developer ID Application: …" identity for a distributable build with the
+# hardened runtime, timestamps and the CEF entitlements. scripts/release.sh
+# then notarizes the result.
+IDENTITY="${CRA_SIGN_IDENTITY:--}"
+sign() { # sign <path> [entitlements]
+ local target="$1" ent="${2:-}"
+ if [ "$IDENTITY" = "-" ]; then
+ codesign --force --sign - "$target"
+ else
+ local args=(--force --sign "$IDENTITY" --options runtime --timestamp)
+ [ -n "$ent" ] && args+=(--entitlements "$ent")
+ codesign "${args[@]}" "$target"
+ fi
+}
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"
+find "$FW/Libraries" -name '*.dylib' -print0 2>/dev/null | while IFS= read -r -d '' lib; do sign "$lib"; done
+sign "$FW"
+for h in "$APP"/Contents/Frameworks/*.app; do sign "$h" "$ROOT/resources/CraHelper.entitlements"; done
+sign "$APP" "$ROOT/resources/Cra.entitlements"
+if [ "$IDENTITY" != "-" ]; then
+ codesign --verify --deep --strict --verbose=2 "$APP"
+fi
LSREGISTER=/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister
mkdir -p "$FINAL_APP"
diff --git a/scripts/notarize.sh b/scripts/notarize.sh
new file mode 100755
index 0000000..bc57e1c
--- /dev/null
+++ b/scripts/notarize.sh
@@ -0,0 +1,27 @@
+#!/bin/bash
+# Submits a file to Apple's notary service, waits, and staples the ticket.
+# scripts/notarize.sh <file.zip|file.dmg> [path/to/Cra.app to staple]
+# Credentials, either:
+# NOTARY_KEYCHAIN_PROFILE a profile stored with `xcrun notarytool store-credentials`
+# or
+# APPLE_ID, APPLE_TEAM_ID, APPLE_APP_PASSWORD (an app-specific password)
+set -euo pipefail
+FILE="$1"
+STAPLE_APP="${2:-}"
+if [ -n "${NOTARY_KEYCHAIN_PROFILE:-}" ]; then
+ AUTH=(--keychain-profile "$NOTARY_KEYCHAIN_PROFILE")
+elif [ -n "${APPLE_ID:-}" ] && [ -n "${APPLE_TEAM_ID:-}" ] && [ -n "${APPLE_APP_PASSWORD:-}" ]; then
+ AUTH=(--apple-id "$APPLE_ID" --team-id "$APPLE_TEAM_ID" --password "$APPLE_APP_PASSWORD")
+else
+ echo "No notarization credentials in the environment; skipping." >&2
+ exit 0
+fi
+echo "Notarizing $(basename "$FILE")…"
+xcrun notarytool submit "$FILE" "${AUTH[@]}" --wait --timeout 30m
+case "$FILE" in
+ *.dmg) xcrun stapler staple "$FILE" ;;
+esac
+if [ -n "$STAPLE_APP" ]; then
+ xcrun stapler staple "$STAPLE_APP"
+fi
+echo "Notarized."
diff --git a/scripts/package.sh b/scripts/package.sh
new file mode 100755
index 0000000..ff29573
--- /dev/null
+++ b/scripts/package.sh
@@ -0,0 +1,32 @@
+#!/bin/bash
+# Packages build/Cra.app into build/dist/: a zip, a DMG with an Applications
+# shortcut, and SHA-256 checksums. Signs the DMG when CRA_SIGN_IDENTITY is set.
+# scripts/package.sh [path/to/Cra.app]
+set -euo pipefail
+cd "$(dirname "$0")/.."
+APP="${1:-build/Cra.app}"
+[ -d "$APP" ] || { echo "No app at $APP. Run scripts/build.sh first." >&2; exit 1; }
+VERSION="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$APP/Contents/Info.plist")"
+IDENTITY="${CRA_SIGN_IDENTITY:--}"
+DIST="build/dist"
+rm -rf "$DIST" && mkdir -p "$DIST"
+
+ZIP="$DIST/Cra-$VERSION.zip"
+DMG="$DIST/Cra-$VERSION.dmg"
+
+# Zip: ditto keeps resource forks and symlinks, which codesign requires.
+ditto -c -k --keepParent "$APP" "$ZIP"
+
+# DMG: stage app + Applications link, build a compressed read-only image.
+STAGE="$(mktemp -d /tmp/cra-dmg.XXXXXX)"
+cp -R "$APP" "$STAGE/"
+ln -s /Applications "$STAGE/Applications"
+hdiutil create -quiet -volname "Cra" -srcfolder "$STAGE" -ov -format UDZO -fs HFS+ "$DMG"
+rm -rf "$STAGE"
+if [ "$IDENTITY" != "-" ]; then
+ codesign --force --sign "$IDENTITY" --timestamp "$DMG"
+fi
+
+(cd "$DIST" && shasum -a 256 "$(basename "$ZIP")" "$(basename "$DMG")" > "SHA256SUMS.txt")
+echo "Packaged:"
+ls -la "$DIST"
diff --git a/scripts/release.sh b/scripts/release.sh
new file mode 100755
index 0000000..fcd55b8
--- /dev/null
+++ b/scripts/release.sh
@@ -0,0 +1,33 @@
+#!/bin/bash
+# Full distributable build: build, sign, notarize, package, notarize the DMG.
+# CRA_VERSION=0.1.0 CRA_SIGN_IDENTITY="Developer ID Application: …" scripts/release.sh
+# Without CRA_SIGN_IDENTITY it still produces an ad-hoc build and packages, so
+# the pipeline can be exercised before certificates exist.
+set -euo pipefail
+cd "$(dirname "$0")/.."
+export CRA_VERSION="${CRA_VERSION:-0.1.0}"
+IDENTITY="${CRA_SIGN_IDENTITY:--}"
+
+scripts/build.sh release
+APP="build/Cra.app"
+
+if [ "$IDENTITY" != "-" ]; then
+ # Notarize the app first (as a zip), staple it, then package the stapled app.
+ TMPZIP="$(mktemp -d /tmp/cra-notarize.XXXXXX)/Cra.zip"
+ ditto -c -k --keepParent "$APP" "$TMPZIP"
+ scripts/notarize.sh "$TMPZIP" "$APP"
+ rm -rf "$(dirname "$TMPZIP")"
+fi
+
+scripts/package.sh "$APP"
+
+if [ "$IDENTITY" != "-" ]; then
+ scripts/notarize.sh "build/dist/Cra-$CRA_VERSION.dmg"
+ # Re-zip the stapled app so the zip download carries the ticket too.
+ ditto -c -k --keepParent "$APP" "build/dist/Cra-$CRA_VERSION.zip"
+ (cd build/dist && shasum -a 256 "Cra-$CRA_VERSION.zip" "Cra-$CRA_VERSION.dmg" > SHA256SUMS.txt)
+ spctl --assess --type execute --verbose=2 "$APP" && echo "Gatekeeper accepts $APP"
+else
+ echo "Ad-hoc build: not notarized. Set CRA_SIGN_IDENTITY and notary credentials for a distributable build." >&2
+fi
+echo "Release artifacts in build/dist"