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.

Cra 0.1.16: smoother tab switching, sidebar and window resizing

Victora1c6c33ea668
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index 6712294..0c33caf 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -45,6 +45,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
NSApp.setActivationPolicy(.regular)
installURLEventHandler()
CraCEFRuntime.setChromeHosting(store.settings.chromeEngine)
+ CraCEFRuntime.setOwnContextMenus(EmbeddedPages.isEnabled)
startContentBlocking()
SoftwareUpdater.shared.start(app: self)
buildMenus()
@@ -475,6 +476,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
var dict: [String: String] = [:]
for item in comps?.queryItems ?? [] { if let v = item.value { dict[item.name] = v } }
if let js = dict["devtoolsjs"] { main.debugRunInDevTools(js) }
+ if dict["embedDump"] != nil { NSLog("%@", main.embeddedPagesDump()); return }
if let id = dict["extensionAction"] { main.runExtensionAction(id); return }
if let f = dict["floatingSidebar"] { if f == "1" { main.floatingSidebar?.show() } else { main.floatingSidebar?.hide(animated: true) }; return }
if let method = dict["bcdp"] {
@@ -515,6 +517,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
}
CraTuning.shared.apply(dict)
main.refresh()
+ main.shell.refreshLift()
if let w = main.window {
let v = main.shell.vibrancy
NSLog("Cra debug: opaque=%d bg=%@ key=%d main=%d vibHidden=%d state=%ld material=%ld blend=%ld appearance=%@ shellLayerOpaque=%d contentViewIsShell=%d",
@@ -580,6 +583,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
let data = h.readDataToEndOfFile()
self.commandFileOffset = size
for line in String(decoding: data, as: UTF8.self).split(separator: "\n") {
+ HitchMonitor.mark(String(line))
if let u = URL(string: line.trimmingCharacters(in: .whitespaces)) { self.handleInternalURL(u) }
}
}
diff --git a/Sources/Cra/App/main.swift b/Sources/Cra/App/main.swift
index 1b3ddd1..c81a0a4 100644
--- a/Sources/Cra/App/main.swift
+++ b/Sources/Cra/App/main.swift
@@ -54,9 +54,12 @@ MainActor.assumeIsolated {
exit(1)
}
+ ChromiumBluetoothCache.install()
+
// Belt and braces: Chromium's run loop drives NSApplication and should call
// applicationDidFinishLaunching, but bootstrapping is idempotent either way.
DispatchQueue.main.async { delegate.bootstrapIfNeeded() }
+ HitchMonitor.startIfRequested()
CraCEFRuntime.runMessageLoop()
delegate.applicationWillShutdown()
CraCEFRuntime.shutdown()
diff --git a/Sources/Cra/Services/ChromiumBluetoothCache.swift b/Sources/Cra/Services/ChromiumBluetoothCache.swift
new file mode 100644
index 0000000..716460e
--- /dev/null
+++ b/Sources/Cra/Services/ChromiumBluetoothCache.swift
@@ -0,0 +1,48 @@
+import Foundation
+import ObjectiveC
+
+/// Chromium's Bluetooth adapter, created once a page makes a WebAuthn request (passkeys on a
+/// phone go over Bluetooth), polls the paired devices every 500 ms on the main thread, which
+/// is also where Cra draws. Each `-[IOBluetoothDevice isPaired]` there is a synchronous XPC
+/// round trip that fetches the whole paired list: ~23 ms of every second went to it, a frame
+/// or two dropped twice a second while scrolling. Pairings change rarely; both answers are
+/// cached for a few seconds.
+enum ChromiumBluetoothCache {
+ private static let lifetime: TimeInterval = 10
+ private static let lock = NSLock()
+ nonisolated(unsafe) private static var pairedDevices: (value: AnyObject?, at: Date)?
+ nonisolated(unsafe) private static var isPaired: [String: (value: Bool, at: Date)] = [:]
+
+ private typealias ObjectIMP = @convention(c) (AnyObject, Selector) -> AnyObject?
+ private typealias BoolIMP = @convention(c) (AnyObject, Selector) -> Bool
+
+ /// After Chromium is loaded (it links IOBluetooth).
+ static func install() {
+ guard let cls = NSClassFromString("IOBluetoothDevice") else { return }
+ if let method = class_getClassMethod(cls, NSSelectorFromString("pairedDevices")) {
+ let sel = method_getName(method)
+ let original = unsafeBitCast(method_getImplementation(method), to: ObjectIMP.self)
+ let block: @convention(block) (AnyObject) -> AnyObject? = { obj in
+ if let hit = lock.withLock({ pairedDevices }), Date().timeIntervalSince(hit.at) < lifetime { return hit.value }
+ let value = original(obj, sel)
+ lock.withLock { pairedDevices = (value, Date()) }
+ return value
+ }
+ method_setImplementation(method, imp_implementationWithBlock(block))
+ }
+ if let method = class_getInstanceMethod(cls, NSSelectorFromString("isPaired")) {
+ let sel = method_getName(method)
+ let original = unsafeBitCast(method_getImplementation(method), to: BoolIMP.self)
+ let addressSel = NSSelectorFromString("addressString")
+ let block: @convention(block) (AnyObject) -> Bool = { obj in
+ guard obj.responds(to: addressSel),
+ let address = obj.perform(addressSel)?.takeUnretainedValue() as? String else { return original(obj, sel) }
+ if let hit = lock.withLock({ isPaired[address] }), Date().timeIntervalSince(hit.at) < lifetime { return hit.value }
+ let value = original(obj, sel)
+ lock.withLock { isPaired[address] = (value, Date()) }
+ return value
+ }
+ method_setImplementation(method, imp_implementationWithBlock(block))
+ }
+ }
+}
diff --git a/Sources/Cra/Services/HitchMonitor.swift b/Sources/Cra/Services/HitchMonitor.swift
new file mode 100644
index 0000000..764ae32
--- /dev/null
+++ b/Sources/Cra/Services/HitchMonitor.swift
@@ -0,0 +1,41 @@
+import Foundation
+import QuartzCore
+
+/// Testing aid: with CRA_HITCH_LOG=<path> set, every main-thread stall of 8 ms or
+/// more is appended to that file, with the actions that ran through CRA_COMMAND_FILE
+/// as markers between them. The main thread is also Chromium's browser UI thread,
+/// so a stall here delays input, scrolling and page-window moves as well as Cra's UI.
+enum HitchMonitor {
+ private static let lock = NSLock()
+ nonisolated(unsafe) private static var handle: FileHandle?
+
+ static func startIfRequested() {
+ guard let path = ProcessInfo.processInfo.environment["CRA_HITCH_LOG"], !path.isEmpty else { return }
+ FileManager.default.createFile(atPath: path, contents: nil)
+ handle = FileHandle(forWritingAtPath: path)
+ let thread = Thread {
+ let done = DispatchSemaphore(value: 0)
+ while true {
+ let start = CACurrentMediaTime()
+ DispatchQueue.main.async { done.signal() }
+ done.wait()
+ let ms = (CACurrentMediaTime() - start) * 1000
+ if ms >= 8 { write(String(format: "stall %.1f", ms)) }
+ // Each ping wakes the run loop (and Chromium's observers on it): not too often.
+ usleep(4000)
+ }
+ }
+ thread.name = "HitchMonitor"
+ thread.qualityOfService = .userInteractive
+ thread.start()
+ }
+
+ static func mark(_ label: String) { write("mark \(label)") }
+
+ private static func write(_ line: String) {
+ lock.lock()
+ defer { lock.unlock() }
+ guard let handle else { return }
+ handle.write(String(format: "%.3f %@\n", CACurrentMediaTime(), line).data(using: .utf8)!)
+ }
+}
diff --git a/Sources/Cra/Services/ItemTable.swift b/Sources/Cra/Services/ItemTable.swift
new file mode 100644
index 0000000..b651bff
--- /dev/null
+++ b/Sources/Cra/Services/ItemTable.swift
@@ -0,0 +1,57 @@
+import Foundation
+import Observation
+
+/// One sidebar item's change counter. A view that read the item depends on this, not on
+/// every item.
+@MainActor @Observable
+final class ItemSignal {
+ var version = 0
+}
+
+/// The sidebar's items, observed one by one. As a single `[UUID: SidebarItem]` property, any
+/// write (a tab switch marks the tab active, a page reports its title) re-rendered every list
+/// and row in every space. Now a view re-renders when an item it read changed; a walk over
+/// all items (`all`, `values`) still depends on every change.
+@MainActor @Observable
+final class ItemTable {
+ @ObservationIgnored private var storage: [UUID: SidebarItem] = [:]
+ @ObservationIgnored private var signals: [UUID: ItemSignal] = [:]
+ /// Bumped on every change: what a walk over all items observes.
+ private var version = 0
+
+ subscript(id: UUID) -> SidebarItem? {
+ get {
+ observe(id)
+ return storage[id]
+ }
+ set {
+ guard storage[id] != newValue else { return }
+ storage[id] = newValue
+ notify(id)
+ }
+ }
+
+ var all: [UUID: SidebarItem] {
+ _ = version
+ return storage
+ }
+
+ var values: Dictionary<UUID, SidebarItem>.Values { all.values }
+
+ /// Depend on `id` without reading it (state kept elsewhere, keyed by the item: expansion,
+ /// selection).
+ func observe(_ id: UUID) { _ = signal(id).version }
+
+ /// What reads `id` is out of date.
+ func notify(_ id: UUID) {
+ signal(id).version &+= 1
+ version &+= 1
+ }
+
+ private func signal(_ id: UUID) -> ItemSignal {
+ if let s = signals[id] { return s }
+ let s = ItemSignal()
+ signals[id] = s
+ return s
+ }
+}
diff --git a/Sources/Cra/Services/Persistence.swift b/Sources/Cra/Services/Persistence.swift
index 4b43ec0..5821fb4 100644
--- a/Sources/Cra/Services/Persistence.swift
+++ b/Sources/Cra/Services/Persistence.swift
@@ -39,6 +39,11 @@ enum AppPaths {
static func file(_ name: String) -> URL { supportDir.appendingPathComponent(name) }
}
+/// Where every JSONStore encodes and writes, one file at a time and in call order. Off the
+/// main thread, which is also Chromium's UI thread: encoding a 2000-entry archive.json
+/// took ~30 ms there, two to four dropped frames after every tab switch.
+private let persistenceQueue = DispatchQueue(label: "dk.kildahl.cra.persistence", qos: .utility)
+
/// One JSON file, loaded once, saved with a short debounce. Writes are atomic
/// and the previous version is kept as `<name>.bak`, which is what Arc does
/// with its timestamped Storable*.json copies, minus the pile-up.
@@ -69,14 +74,19 @@ final class JSONStore<T: Codable> {
func save(_ value: T, delay: TimeInterval = 0.4) {
pending?.cancel()
- let item = DispatchWorkItem { [weak self] in self?.saveNow(value) }
+ let item = DispatchWorkItem { [weak self] in self?.write(value) }
pending = item
- DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: item)
+ persistenceQueue.asyncAfter(deadline: .now() + delay, execute: item)
}
+ /// Writes before returning (quit, launch-time bookkeeping), after any write in flight.
func saveNow(_ value: T) {
pending?.cancel()
pending = nil
+ persistenceQueue.sync { write(value) }
+ }
+
+ private func write(_ value: T) {
guard let data = try? encoder.encode(value) else { return }
let fm = FileManager.default
let bak = url.appendingPathExtension("bak")
diff --git a/Sources/Cra/Services/SidebarStore.swift b/Sources/Cra/Services/SidebarStore.swift
index 1b5d0ad..aeab83c 100644
--- a/Sources/Cra/Services/SidebarStore.swift
+++ b/Sources/Cra/Services/SidebarStore.swift
@@ -13,9 +13,17 @@ final class SidebarStore {
private(set) var spaceOrder: [UUID] = []
/// Profiles besides Default, in the order they were made.
private(set) var profiles: [BrowserProfile] = []
- private(set) var items: [UUID: SidebarItem] = [:]
- private(set) var archive: [ArchivedItem] = []
- var prefs = WindowPrefs() { didSet { prefsStore.save(prefs.withoutIncognito) } }
+ /// Observed item by item (ItemTable): a view re-renders when an item it read changes.
+ let items = ItemTable()
+ private(set) var archive: [ArchivedItem] = [] { didSet { archiveChanged = true } }
+ /// archive.json is by far the largest file; it is written only when the archive changed.
+ @ObservationIgnored private var archiveChanged = false
+ var prefs = WindowPrefs() {
+ didSet {
+ prefsStore.save(prefs.withoutIncognito)
+ notifyItemReaders(of: oldValue)
+ }
+ }
var settings = AppSettings() { didSet { settingsStore.save(settings) } }
private(set) var history: [String: HistoryEntry] = [:]
private(set) var ranking = RankingData()
@@ -49,6 +57,7 @@ final class SidebarStore {
for s in doc.spaces where !spaceOrder.contains(s.id) { spaceOrder.append(s.id) }
for it in doc.items { items[it.id] = it }
archive = archiveFile.load(or: { [] })
+ archiveChanged = false
prefs = prefsStore.load(or: { WindowPrefs() })
settings = settingsStore.load(or: { AppSettings() })
for h in historyFile.load(or: { [] }) { history[h.url] = h }
@@ -90,11 +99,11 @@ final class SidebarStore {
for it in doc.items { items[it.id] = it }
}
// Drop children references that do not resolve and orphans.
- for (id, var it) in items {
+ for (id, var it) in items.all {
it.children = it.children.filter { items[$0] != nil && items[$0]?.parentID == id }
items[id] = it
}
- for (id, it) in items where it.container == nil {
+ for (id, it) in items.all where it.container == nil {
if let p = it.parentID, let parent = items[p], parent.children.contains(id) { continue }
// Orphan: put it in the first space's today list rather than losing it.
if let space = spaceOrder.first.flatMap({ spaces[$0] }) {
@@ -146,7 +155,10 @@ final class SidebarStore {
func save() {
sidebarFile.save(document)
- archiveFile.save(archive)
+ if archiveChanged {
+ archiveChanged = false
+ archiveFile.save(archive)
+ }
}
func saveAll() {
@@ -412,9 +424,15 @@ final class SidebarStore {
}
// A live folder's tab keeps the pull request's title (Arc shows that, not the page's).
if let title, !(t.liveItemURL.map { t.url.hasPrefix($0) } ?? false) { t.savedTitle = title }
+ // Pages report titles and addresses over and over while they load, and every write to
+ // `items` re-renders the sidebar's lists: only real changes are written.
+ guard t != it.tab else { return }
+ let wasEmpty = it.isEmptyTab
it.data = .tab(t)
items[id] = it
- revision &+= 1
+ // The window's layout (refresh) only depends on a tab becoming or ceasing to be an
+ // empty pane; the rows and the toolbar observe the tab themselves.
+ if it.isEmptyTab != wasEmpty { revision &+= 1 }
sidebarFile.save(SidebarDocument(version: 1, spaceOrder: spaceOrder, spaces: orderedSpaces,
items: Array(items.values), profiles: profiles), delay: 2)
}
@@ -929,13 +947,57 @@ final class SidebarStore {
touch()
}
- func isExpanded(_ id: UUID) -> Bool { prefs.expandedFolders.contains(id) }
+ // Rows read their own expansion, collapse and selection through these. They depend on
+ // the item's signal, not on `prefs`, which changes on every tab switch and window move;
+ // `notifyItemReaders` signals the items whose state actually changed.
+
+ func isExpanded(_ id: UUID) -> Bool {
+ items.observe(id)
+ return _prefs.expandedFolders.contains(id)
+ }
+
+ /// Whether `id` is the open tab of the window's focused space, or of `space`.
+ func isSelected(_ id: UUID, inSpace space: UUID? = nil, window: UUID?) -> Bool {
+ items.observe(id)
+ let w = untrackedWindow(window)
+ if let space { return w.selectedTabPerSpace[space] == id }
+ return Self.openTab(in: w, firstSpace: spaceOrder.first) == id
+ }
+
+ private func untrackedWindow(_ id: UUID?) -> WindowSession {
+ let windows = _prefs.windows
+ return windows.first { $0.id == (id ?? activeWindowID) } ?? windows.first { $0.id == activeWindowID } ?? windows[0]
+ }
+
+ private static func openTab(in w: WindowSession, firstSpace: UUID?) -> UUID? {
+ (w.focusedSpaceID ?? firstSpace).flatMap { w.selectedTabPerSpace[$0] }
+ }
+
+ private func notifyItemReaders(of old: WindowPrefs) {
+ for id in old.expandedFolders.symmetricDifference(prefs.expandedFolders) { items.notify(id) }
+ for id in old.collapsedPinnedSpaces.symmetricDifference(prefs.collapsedPinnedSpaces) { items.notify(id) }
+ let first = spaceOrder.first
+ for w in prefs.windows {
+ let was = old.windows.first { $0.id == w.id }
+ var changed: Set<UUID?> = []
+ let before = was.flatMap { Self.openTab(in: $0, firstSpace: first) }, now = Self.openTab(in: w, firstSpace: first)
+ if before != now { changed.formUnion([before, now]) }
+ let oldPicks = was?.selectedTabPerSpace ?? [:]
+ for space in Set(oldPicks.keys).union(w.selectedTabPerSpace.keys) where oldPicks[space] != w.selectedTabPerSpace[space] {
+ changed.formUnion([oldPicks[space], w.selectedTabPerSpace[space]])
+ }
+ for case let id? in changed { items.notify(id) }
+ }
+ }
func setExpanded(_ id: UUID, _ expanded: Bool) {
if expanded { prefs.expandedFolders.insert(id) } else { prefs.expandedFolders.remove(id) }
}
/// Arc's spacesWithCollapsedPinnedSections: clicking the space name hides its pinned tabs.
- func isPinnedCollapsed(_ spaceID: UUID) -> Bool { prefs.collapsedPinnedSpaces.contains(spaceID) }
+ func isPinnedCollapsed(_ spaceID: UUID) -> Bool {
+ items.observe(spaceID)
+ return _prefs.collapsedPinnedSpaces.contains(spaceID)
+ }
func togglePinnedCollapsed(_ spaceID: UUID) {
if prefs.collapsedPinnedSpaces.remove(spaceID) == nil { prefs.collapsedPinnedSpaces.insert(spaceID) }
}
@@ -945,8 +1007,20 @@ final class SidebarStore {
var liveFolders: [SidebarItem] { items.values.filter(\.isLiveFolder) }
/// The space's live folder for a source (Dia: one Pull Requests folder per space).
+ /// Walks only the space's own lists, so a view that asks depends on those items alone.
func liveFolder(_ source: LiveFolderSource, inSpace sid: UUID) -> SidebarItem? {
- liveFolders.first { $0.liveFolder?.source == source && spaceID(ofItem: $0.id) == sid }
+ guard let space = spaces[sid] else { return nil }
+ func find(under id: UUID) -> SidebarItem? {
+ for c in children(of: id) where c.isFolder || c.isSplit {
+ if c.liveFolder?.source == source { return c }
+ if let found = find(under: c.id) { return found }
+ }
+ return nil
+ }
+ for root in [space.favoritesContainerID, space.pinnedContainerID, space.todayContainerID] {
+ if let found = find(under: root) { return found }
+ }
+ return nil
}
/// Arc's "Pull Requests" folder at the top of the space's pinned tabs, open.
diff --git a/Sources/Cra/UI/ShellView.swift b/Sources/Cra/UI/ShellView.swift
index 8c9d8ce..bb1f042 100644
--- a/Sources/Cra/UI/ShellView.swift
+++ b/Sources/Cra/UI/ShellView.swift
@@ -48,7 +48,7 @@ final class ShellView: NSView {
/// Reports each pane's page area (window coordinates) so Chrome-style page windows follow it.
var onPaneFrames: (([UUID: NSRect]) -> Void)?
/// Animated transitions (sidebar, pane add/remove): target page areas + duration, so page windows animate alongside.
- var onAnimatePaneFrames: (([UUID: NSRect], TimeInterval) -> Void)?
+ var onAnimatePaneFrames: (([UUID: NSRect], TimeInterval, CAMediaTimingFunction) -> Void)?
/// The user dragged a divider and let go: new width factors per pane.
var onPaneResizeEnded: (([UUID: CGFloat]) -> Void)?
var onPaneResizeBegan: (() -> Void)?
@@ -314,7 +314,7 @@ final class ShellView: NSView {
}
animatingPanes = true
let webTargets = paneWebFrames(target)
- onAnimatePaneFrames?(webTargets, SplitPaneLayout.Constants.transitionDuration)
+ onAnimatePaneFrames?(webTargets, SplitPaneLayout.Constants.transitionDuration, SplitPaneLayout.Constants.transitionTiming)
NSAnimationContext.runAnimationGroup { ctx in
ctx.duration = SplitPaneLayout.Constants.transitionDuration
ctx.timingFunction = SplitPaneLayout.Constants.transitionTiming
@@ -615,13 +615,14 @@ final class ShellView: NSView {
}
layoutContentChildren()
animatingFrames = true
- onAnimatePaneFrames?(webTargets, duration)
+ // Fast start, soft landing: feels immediate without a visible snap.
+ // Fitted to Arc 1.170's ⌘S hide at 60 fps: 66 / 87 / 96 / 99 % of the travel after
+ // frames 1–4 (card edge 568 → 204 → 90 → 42 → 24 → 20 px).
+ let timing = CAMediaTimingFunction(controlPoints: 0.15, 0.7, 0.3, 1)
+ onAnimatePaneFrames?(webTargets, duration, timing)
NSAnimationContext.runAnimationGroup { ctx in
ctx.duration = duration
- // Fast start, soft landing: feels immediate without a visible snap.
- // Fitted to Arc 1.170's ⌘S hide at 60 fps: 66 / 87 / 96 / 99 % of the travel after
- // frames 1–4 (card edge 568 → 204 → 90 → 42 → 24 → 20 px).
- ctx.timingFunction = CAMediaTimingFunction(controlPoints: 0.15, 0.7, 0.3, 1)
+ ctx.timingFunction = timing
ctx.allowsImplicitAnimation = true
if !sidebarDetached { sidebarHost.animator().frame = target.sidebar }
contentContainer.animator().frame = target.content
diff --git a/Sources/Cra/UI/Sidebar/FavoritesGrid.swift b/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
index 5f8a10f..8982e70 100644
--- a/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
+++ b/Sources/Cra/UI/Sidebar/FavoritesGrid.swift
@@ -64,7 +64,7 @@ struct FavoriteCell: View {
@State private var hover = false
@State private var targeted = false
- private var selected: Bool { store.selectedTabID(in: space.id, window: ui.windowID) == item.id }
+ private var selected: Bool { store.isSelected(item.id, inSpace: space.id, window: ui.windowID) }
private var tileColor: String? { item.tab?.tileColor }
private var tileIsDark: Bool { tileColor.flatMap(HexColor.luminance).map { $0 < 0.5 } ?? palette.isDark }
diff --git a/Sources/Cra/UI/Sidebar/SidebarItemView.swift b/Sources/Cra/UI/Sidebar/SidebarItemView.swift
index b7db375..41f2363 100644
--- a/Sources/Cra/UI/Sidebar/SidebarItemView.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarItemView.swift
@@ -72,7 +72,7 @@ struct TabRow: View {
@AppStorage("didShowRenameHint") private var didShowRenameHint = false
private var tab: TabData { item.tab! }
- private var selected: Bool { store.selectedTabID(window: ui.windowID) == item.id }
+ private var selected: Bool { store.isSelected(item.id, window: ui.windowID) }
/// While tabs are ⌘/⇧-picked the highlight follows the picks, not the open tab.
private var highlighted: Bool { ui.multiSelection.isEmpty ? selected : ui.multiSelection.contains(item.id) }
/// Close acts on every picked tab when this row is one of them.
@@ -214,7 +214,7 @@ struct TabRow: View {
.padding(8)
.background(RoundedRectangle(cornerRadius: 8).fill(.regularMaterial))
}
- .contextMenu { contextMenu }
+ .contextMenu { TabRowMenu(item: item, pinned: pinned, navigatedAway: navigatedAway, closeGroup: closeGroup, close: closeTabs) }
// Arc's row tip is the tab's title by the pointer; the close buttons' own tips win over it.
// Like Arc (didShowRenameHint), "Double-click to rename" rides along once.
.arcTooltip(editing ? "" : item.displayTitle, followsCursor: true,
@@ -238,13 +238,28 @@ struct TabRow: View {
ui.multiSelection.subtract(ids)
}
}
+}
- @ViewBuilder
- private var contextMenu: some View {
+/// A tab row's context menu. Its own view: what it reads from the store (folders, spaces,
+/// favorites) would otherwise make every row's body depend on all of it, and every row
+/// re-rendered on each store change (a tab switch, a page title).
+private struct TabRowMenu: View {
+ let item: SidebarItem
+ let pinned: Bool
+ let navigatedAway: Bool
+ let closeGroup: [UUID]
+ let close: ([UUID]) -> Void
+ @Environment(SidebarStore.self) private var store
+ @Environment(SidebarUIState.self) private var ui
+ @Environment(\.sidebarActions) private var actions
+
+ private var tab: TabData { item.tab! }
+
+ var body: some View {
if closeGroup.count > 1 {
folderMenu(ui.group(for: item.id, in: store))
Divider()
- Button("Close \(closeGroup.count) Tabs") { closeTabs(closeGroup) }
+ Button("Close \(closeGroup.count) Tabs") { close(closeGroup) }
Button("Deselect All") { ui.clearPicks() }
} else {
singleTabMenu
@@ -306,7 +321,9 @@ struct TabRow: View {
folderMenu([item.id])
Divider()
if pinned {
- if selected || loaded { Button("Close and Keep Pinned") { actions.closeTab(item.id) } }
+ if store.isSelected(item.id, window: ui.windowID) || ui.loadedTabIDs.contains(item.id) {
+ Button("Close and Keep Pinned") { actions.closeTab(item.id) }
+ }
Button("Archive Tab") { store.archiveTab(item.id, reason: .manual) }
} else {
Button("Archive") { actions.closeTab(item.id) }
diff --git a/Sources/Cra/UI/Sidebar/SidebarRootView.swift b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
index 0a59d0a..51e74cb 100644
--- a/Sources/Cra/UI/Sidebar/SidebarRootView.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
@@ -321,7 +321,7 @@ struct SpaceSectionView: View {
.background(DragAutoscroller.Anchor(scroller: autoscroller))
.contentShape(Rectangle())
// Right-click on empty list space; rows have their own menus.
- .contextMenu { listMenu }
+ .contextMenu { SpaceListMenu(space: space) }
.onDrop(of: [.craSidebarItem], delegate: SidebarListDropDelegate(space: space, store: store, ui: ui, autoscroller: autoscroller))
// Safety net: a drag that ended without an exit callback leaves no preview behind.
.onContinuousHover { _ in if ui.listDrop != nil, NSEvent.pressedMouseButtons == 0 { ui.listDrop = nil } }
@@ -344,19 +344,6 @@ struct SpaceSectionView: View {
private static let scrollSpace = "spaceSectionScroll"
- @ViewBuilder
- private var listMenu: some View {
- Button("New Tab") { actions.openCommandBar(.newTab) }
- Button("New Folder") { actions.performAction("newFolder") }
- Button("New GitHub Live Folder") { actions.performAction("newGitHubLiveFolder") }
- .disabled(store.liveFolder(.github, inSpace: space.id) != nil)
- Divider()
- if !store.children(of: space.todayContainerID).isEmpty {
- Button("Clear Today") { store.clearToday(space.id) }
- }
- Button("Edit Space…") { actions.editSpace(space) }
- }
-
@ViewBuilder
private var dropLine: some View {
if let line = ui.listDrop?.line {
@@ -542,3 +529,23 @@ struct NewTabRow: View {
.onHover { hover = $0 }
}
}
+
+/// The space list's context menu. Its own view: finding the live folder walks every item,
+/// which would make the whole list re-render on any change to any item.
+private struct SpaceListMenu: View {
+ let space: Space
+ @Environment(SidebarStore.self) private var store
+ @Environment(\.sidebarActions) private var actions
+
+ var body: some View {
+ Button("New Tab") { actions.openCommandBar(.newTab) }
+ Button("New Folder") { actions.performAction("newFolder") }
+ Button("New GitHub Live Folder") { actions.performAction("newGitHubLiveFolder") }
+ .disabled(store.liveFolder(.github, inSpace: space.id) != nil)
+ Divider()
+ if !store.children(of: space.todayContainerID).isEmpty {
+ Button("Clear Today") { store.clearToday(space.id) }
+ }
+ Button("Edit Space…") { actions.editSpace(space) }
+ }
+}
diff --git a/Sources/Cra/UI/SplitView/PaneCardView.swift b/Sources/Cra/UI/SplitView/PaneCardView.swift
index d9f8c70..9a5afa6 100644
--- a/Sources/Cra/UI/SplitView/PaneCardView.swift
+++ b/Sources/Cra/UI/SplitView/PaneCardView.swift
@@ -8,6 +8,8 @@ import SwiftUI
final class PaneCardView: NSView {
let tabID: UUID
let toolbarHost: NSHostingView<AnyView>
+ /// The theme the toolbar's root view was made with: it is rebuilt only when that changes.
+ var toolbarTheme: SpaceTheme?
/// Where the Chromium view lives (or where the page window is positioned).
let webArea = NSView()
/// Hairline under the toolbar when the pane has no page (Arc draws it on the tinted card).
diff --git a/Sources/Cra/UI/SplitView/SplitDraggerHandleView.swift b/Sources/Cra/UI/SplitView/SplitDraggerHandleView.swift
index 6bf62dd..8d82b04 100644
--- a/Sources/Cra/UI/SplitView/SplitDraggerHandleView.swift
+++ b/Sources/Cra/UI/SplitView/SplitDraggerHandleView.swift
@@ -93,7 +93,9 @@ final class SplitDraggerHandleView: NSView {
override func mouseDown(with event: NSEvent) {
if event.clickCount == 2 { onDoubleClick?(); return }
- dragStart = convert(event.locationInWindow, from: nil)
+ // Window coordinates: the handle itself moves with the divider while it is dragged,
+ // and in its own coordinates half the pointer's travel cancelled out.
+ dragStart = event.locationInWindow
dragging = true
refreshPill()
onDragBegan?()
@@ -101,7 +103,7 @@ final class SplitDraggerHandleView: NSView {
override func mouseDragged(with event: NSEvent) {
guard let start = dragStart else { return }
- let p = convert(event.locationInWindow, from: nil)
+ let p = event.locationInWindow
// Vertical layouts stack downwards; AppKit's y grows upwards.
let delta = orientation == .horizontal ? p.x - start.x : start.y - p.y
onDrag?(delta)
diff --git a/Sources/Cra/UI/SplitView/SplitRow.swift b/Sources/Cra/UI/SplitView/SplitRow.swift
index 9d046fd..4b1ba5d 100644
--- a/Sources/Cra/UI/SplitView/SplitRow.swift
+++ b/Sources/Cra/UI/SplitView/SplitRow.swift
@@ -14,7 +14,7 @@ struct SplitRow: View {
@State private var hover = false
private var children: [SidebarItem] { store.children(of: item.id).filter { $0.isTab } }
- private var selected: Bool { store.selectedTabID(window: ui.windowID).map { id in children.contains { $0.id == id } } ?? false }
+ private var selected: Bool { children.contains { store.isSelected($0.id, window: ui.windowID) } }
enum Metrics {
static let separatorInset: CGFloat = 9
@@ -26,7 +26,7 @@ struct SplitRow: View {
if i > 0 {
Rectangle().fill(palette.separator).frame(width: 1).padding(.vertical, Metrics.separatorInset)
}
- SplitChildCell(item: child, palette: palette, groupHovered: hover, groupSelected: selected, focused: store.selectedTabID(window: ui.windowID) == child.id)
+ SplitChildCell(item: child, palette: palette, groupHovered: hover, groupSelected: selected, focused: store.isSelected(child.id, window: ui.windowID))
}
}
.padding(.leading, CGFloat(depth) * CraMetrics.indent)
diff --git a/Sources/Cra/UI/Windows/EmbeddedPages.swift b/Sources/Cra/UI/Windows/EmbeddedPages.swift
new file mode 100644
index 0000000..e74c8d8
--- /dev/null
+++ b/Sources/Cra/UI/Windows/EmbeddedPages.swift
@@ -0,0 +1,83 @@
+import AppKit
+import ObjectiveC
+
+/// Experimental: Chromium's page view lives in the pane card instead of its own child window,
+/// the way Arc and Dia host pages. One window and one Core Animation tree, so the page moves,
+/// resizes and animates with the card, and clicks and keys reach it without making another
+/// window key.
+///
+/// CEF 156 only makes Chrome-style browsers (extensions, Chrome's DevTools) inside its own
+/// window, so that window stays: empty, click-through, never key, laid over the card as
+/// before so Chromium's menus, popups and layout still have the right screen position. Its
+/// page view (WebContentsViewCocoa) moves into the card's web area.
+///
+/// On with `defaults write dk.kildahl.cra embedPages -bool YES` or CRA_EMBED_PAGES=1.
+enum EmbeddedPages {
+ static let isEnabled = ProcessInfo.processInfo.environment["CRA_EMBED_PAGES"] == "1"
+ || UserDefaults.standard.bool(forKey: "embedPages")
+
+ /// Chrome windows whose page moved out: they must never become key or main, or keys
+ /// would go to a window with nothing in it (Chromium activates its window on focus).
+ private static let hosts = NSHashTable<NSWindow>.weakObjects()
+ private static var patched = false
+
+ static func markHost(_ window: NSWindow) {
+ patch(window)
+ hosts.add(window)
+ // Its views moved out and it is clear and borderless, so it shows nothing. It keeps
+ // alpha 1: Chrome pops page context menus up from it, and an alpha 0 window gets none.
+ window.ignoresMouseEvents = true
+ }
+
+ /// The page went back into its window (DevTools docked in it).
+ static func unmarkHost(_ window: NSWindow) {
+ guard hosts.contains(window) else { return }
+ hosts.remove(window)
+ window.ignoresMouseEvents = false
+ }
+
+ static func isHost(_ window: NSWindow?) -> Bool { window.map { hosts.contains($0) } ?? false }
+
+ /// What moves, by Chrome window, wherever the views are now (any window's card, or none
+ /// while the tab is hidden), so a tab moving to another Cra window still finds its page.
+ /// Chromium draws the page with the window's compositor, whose layers live in
+ /// ViewsCompositorSuperview; WebContentsViewCocoa on top of it only takes input. Both move,
+ /// in that order.
+ private static let pages = NSMapTable<NSWindow, NSArray>.weakToStrongObjects()
+
+ static func pageViews(of window: NSWindow) -> [NSView]? {
+ if let views = pages.object(forKey: window) as? [NSView] { return views }
+ guard let cv = window.contentView, let page = webContentsView(in: cv),
+ let compositor = find("ViewsCompositorSuperview", in: cv) else { return nil }
+ let views = [compositor, page]
+ pages.setObject(views as NSArray, forKey: window)
+ return views
+ }
+
+ static func webContentsView(in root: NSView) -> NSView? { find("WebContentsViewCocoa", in: root) }
+ static func renderView(in root: NSView) -> NSView? { find("RenderWidgetHostViewCocoa", in: root) }
+
+ private static func find(_ className: String, in root: NSView) -> NSView? {
+ if NSStringFromClass(type(of: root)) == className { return root }
+ for v in root.subviews { if let found = find(className, in: v) { return found } }
+ return nil
+ }
+
+ private typealias BoolIMP = @convention(c) (AnyObject, Selector) -> Bool
+
+ private static func patch(_ window: NSWindow) {
+ guard !patched else { return }
+ patched = true
+ let cls: AnyClass = type(of: window)
+ for name in ["canBecomeKeyWindow", "canBecomeMainWindow"] {
+ let sel = NSSelectorFromString(name)
+ guard let method = class_getInstanceMethod(cls, sel) else { continue }
+ let original = unsafeBitCast(method_getImplementation(method), to: BoolIMP.self)
+ let block: @convention(block) (AnyObject) -> Bool = { obj in
+ if let w = obj as? NSWindow, MainActor.assumeIsolated({ hosts.contains(w) }) { return false }
+ return original(obj, sel)
+ }
+ method_setImplementation(method, imp_implementationWithBlock(block))
+ }
+ }
+}
diff --git a/Sources/Cra/UI/Windows/LittleWindowController.swift b/Sources/Cra/UI/Windows/LittleWindowController.swift
index a23bb85..5e85781 100644
--- a/Sources/Cra/UI/Windows/LittleWindowController.swift
+++ b/Sources/Cra/UI/Windows/LittleWindowController.swift
@@ -694,7 +694,14 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @preco
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, handleKeyEvent event: NSEvent) -> Bool {
+ // Escape leaves the page's element fullscreen, as in the main window.
+ if pageFullscreen, event.keyCode == 53, event.modifierFlags.intersection([.command, .shift, .option, .control]).isEmpty {
+ browser.exitFullscreen()
+ return true
+ }
+ return 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) }
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index 21332a6..37344d5 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -35,6 +35,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
/// The tab whose page (a video) is in element fullscreen.
private var contentFullscreenTab: UUID?
private var lastSidebarVisible = true
+ /// The theme the background and placeholder root views were made with.
+ private var shownTheme: SpaceTheme?
private var lastSidebarWidth: CGFloat = 0
private var commandBarOpenedAt = Date.distantPast
private var commandObserving = false
@@ -174,7 +176,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
refresh()
shell.onDevToolsFrame = { [weak self] rect in self?.positionDevToolsWindow(rect) }
shell.onPaneFrames = { [weak self] frames in self?.positionPageWindows(frames) }
- shell.onAnimatePaneFrames = { [weak self] frames, d in self?.animatePageWindows(to: frames, duration: d) }
+ shell.onAnimatePaneFrames = { [weak self] frames, d, timing in self?.animatePageWindows(to: frames, duration: d, timing: timing) }
NotificationCenter.default.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in
Task { @MainActor in self?.shell.windowActive = true; self?.sidebarUI.appActive = true }
}
@@ -279,18 +281,25 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
guard !isTornDown else { return }
let space = focusedSpace
let palette = space.theme.palette
- shell.backgroundHost.rootView = SpaceBackground(palette: palette, pager: SpacePager(store: store, ui: sidebarUI))
- shell.placeholderHost.rootView = AnyView(EmptyContentView(space: space))
- shell.isDarkTheme = palette.isDark
- window?.appearance = NSAppearance(named: palette.isDark ? .darkAqua : .aqua)
- // Vibrant themes see through to the desktop like Arc; others are opaque.
- shell.vibrancy.isHidden = !palette.vibrant
- shell.vibrancyLift.isHidden = !palette.vibrant
- shell.vibrantDark = palette.isDark
- shell.vibrantLight = palette.vibrant && !palette.isDark
- shell.refreshLift()
- window?.isOpaque = !palette.vibrant
- window?.backgroundColor = palette.vibrant ? .clear : NSColor(palette.gradientColors.first ?? .gray)
+ // refresh runs on every store change (each page title, each window move). A new root
+ // view rebuilds its whole SwiftUI tree, and a new window appearance or background redraws
+ // every view, so all of these follow the theme only when it changes. What the root
+ // views show beyond the palette they observe themselves.
+ if shownTheme != space.theme {
+ shownTheme = space.theme
+ shell.backgroundHost.rootView = SpaceBackground(palette: palette, pager: SpacePager(store: store, ui: sidebarUI))
+ shell.placeholderHost.rootView = AnyView(EmptyContentView(space: space))
+ shell.isDarkTheme = palette.isDark
+ window?.appearance = NSAppearance(named: palette.isDark ? .darkAqua : .aqua)
+ // Vibrant themes see through to the desktop like Arc; others are opaque.
+ shell.vibrancy.isHidden = !palette.vibrant
+ shell.vibrancyLift.isHidden = !palette.vibrant
+ shell.vibrantDark = palette.isDark
+ shell.vibrantLight = palette.vibrant && !palette.isDark
+ shell.refreshLift()
+ window?.isOpaque = !palette.vibrant
+ window?.backgroundColor = palette.vibrant ? .clear : NSColor(palette.gradientColors.first ?? .gray)
+ }
browsers.pruneMissingTabs()
let selected = selectedTabID
@@ -299,7 +308,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
let split = selected.flatMap { store.splitContaining($0) }
let factors = SplitPaneLayout.normalizedFactors(ids: panes, stored: split?.split?.widthFactors ?? [:])
let empty = Set(panes.filter { store.item($0)?.isEmptyTab == true })
- shell.showToolbar = store.settings.showToolbar
+ if shell.showToolbar != store.settings.showToolbar { shell.showToolbar = store.settings.showToolbar }
shell.setPanes(panes, factors: factors, orientation: split?.split?.orientation ?? .horizontal, focused: selected, empty: empty, animated: true)
// A page is on screen in one window at a time. Arc keeps the tab selected in every window
// that has it open: the window in use holds the page, the others show a blurred snapshot
@@ -308,7 +317,10 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
let live = panes.filter { !elsewhere.contains($0) }
let liveFocus = selected.flatMap { elsewhere.contains($0) ? nil : $0 }
for c in shell.paneCards {
- c.toolbarHost.rootView = shell.makeToolbar?(c.tabID == ShellView.noTabID ? nil : c.tabID) ?? AnyView(EmptyView())
+ if c.toolbarTheme != space.theme {
+ c.toolbarTheme = space.theme
+ c.toolbarHost.rootView = shell.makeToolbar?(c.tabID == ShellView.noTabID ? nil : c.tabID) ?? AnyView(EmptyView())
+ }
c.showsElsewhere = elsewhere.contains(c.tabID)
c.elsewhereSnapshot = c.showsElsewhere ? app.runtime(for: c.tabID)?.snapshot : nil
}
@@ -349,16 +361,21 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
return showing.first.map { $0.id != windowID } ?? false
}
+ /// Runs on every page event (progress, title, favicon). An @Observable property notifies
+ /// on every assignment, equal or not, and every sidebar row reads some of these, so each
+ /// one is assigned only when it changed.
private func syncSidebarUI() {
- sidebarUI.loadedTabIDs = Set(app.mainWindows.flatMap { $0.browsers.runtimes.keys })
+ let loaded = Set(app.mainWindows.flatMap { $0.browsers.runtimes.keys })
+ if loaded != sidebarUI.loadedTabIDs { sidebarUI.loadedTabIDs = loaded }
let capturing = Set(app.mainWindows.flatMap { $0.browsers.runtimes.filter { $0.value.browser.isCapturingMedia }.keys })
if capturing != sidebarUI.capturingTabIDs { sidebarUI.capturingTabIDs = capturing }
let b = browsers.visibleRuntime?.browser
- sidebarUI.canGoBack = b?.canGoBack ?? false
- sidebarUI.canGoForward = b?.canGoForward ?? false
- sidebarUI.isLoading = b?.isLoading ?? false
- sidebarUI.pageThemeColor = browsers.visibleRuntime?.themeColor ?? ""
- for (id, rt) in browsers.runtimes { sidebarUI.progress[id] = rt.progress }
+ if sidebarUI.canGoBack != (b?.canGoBack ?? false) { sidebarUI.canGoBack = b?.canGoBack ?? false }
+ if sidebarUI.canGoForward != (b?.canGoForward ?? false) { sidebarUI.canGoForward = b?.canGoForward ?? false }
+ if sidebarUI.isLoading != (b?.isLoading ?? false) { sidebarUI.isLoading = b?.isLoading ?? false }
+ let themeColor = browsers.visibleRuntime?.themeColor ?? ""
+ if sidebarUI.pageThemeColor != themeColor { sidebarUI.pageThemeColor = themeColor }
+ for (id, rt) in browsers.runtimes where sidebarUI.progress[id] != rt.progress { sidebarUI.progress[id] = rt.progress }
var nav: [UUID: TabNavState] = [:]
for id in browsers.visibleTabIDs {
guard let rt = browsers.runtime(for: id) else { continue }
@@ -651,6 +668,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
/// Attaches the visible tabs' Chrome windows over their pane areas, hides the others.
func browserManagerPageWindowsChanged(focus: Bool) {
guard let window else { return }
+ // A focus still waiting for its page to embed is stale once pages change without one.
+ if !focus { embedFocusTab = nil }
ensureOverlayPanel()
let visibleIDs = Set(browsers.visibleTabIDs)
let focused = browsers.visibleRuntime?.hostWindow
@@ -660,8 +679,15 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// NSView ancestor), so hidden tabs stayed "visible": background tabs autoplayed video
// and ran at full speed. A hidden content view makes the tab hidden like Chrome's
// background tabs: media waits until the tab is first shown.
- w.contentView?.isHidden = !visibleIDs.contains(id)
- if !visibleIDs.contains(id) { if w.isVisible { w.orderOut(nil) }; continue }
+ if !visibleIDs.contains(id) {
+ w.contentView?.isHidden = true
+ // An embedded page leaves the window with its card, so Chromium sees it hidden.
+ if EmbeddedPages.isHost(w), let views = EmbeddedPages.pageViews(of: w) {
+ for v in views where v.superview !== w.contentView { v.removeFromSuperview() }
+ }
+ if w.isVisible { w.orderOut(nil) }
+ continue
+ }
if w.parent !== window {
// Borderless: a titled window gets macOS's rounded corners on all four sides,
// which shows under the toolbar and where the page meets DevTools.
@@ -685,13 +711,21 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
window.addChildWindow(w, ordered: .above)
}
+ // Hidden pages are not kept in step with the panes, so size this one before it shows.
positionPageWindows(lastPaneFrames)
+ w.contentView?.isHidden = false
+ embedPage(id, from: w)
w.orderFront(nil)
- if focus, w === focused {
+ if focus, w === focused, EmbeddedPages.isEnabled, browsers.visibleDevToolsWindow == nil {
+ // Focus goes to the page inside this window; one not embedded yet takes it when it is.
+ embedFocusTab = id
+ focusEmbeddedPage(id)
+ } else if focus, w === focused {
w.makeKey()
devToolsLog("page win \(w.windowNumber) makeKey -> isKey=\(w.isKeyWindow) canBecomeKey=\(w.canBecomeKey) style \(w.styleMask.rawValue)")
}
}
+ releaseUnfocusedEmbeddedPage()
if let dev = browsers.visibleDevToolsWindow, dev.parent === window {
raisePageWindows(above: dev)
} else {
@@ -699,6 +733,71 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
}
+ /// Moves the page's view from its Chrome window into its card (EmbeddedPages). With
+ /// DevTools open the page goes back: Chrome's docked frontend lays it out in its window.
+ private func embedPage(_ id: UUID, from w: NSWindow) {
+ guard EmbeddedPages.isEnabled else { return }
+ guard let views = EmbeddedPages.pageViews(of: w) else { return }
+ let target: NSView
+ if browsers.visibleDevToolsWindow != nil, let cv = w.contentView {
+ EmbeddedPages.unmarkHost(w)
+ target = cv
+ } else if let card = shell.paneCards.first(where: { $0.tabID == id }) {
+ EmbeddedPages.markHost(w)
+ target = card.webArea
+ } else {
+ return
+ }
+ // Compositor first, the page's input view above it.
+ if views.contains(where: { $0.superview !== target }) {
+ for v in views { target.addSubview(v) }
+ }
+ let bounds = shell.paneCards.first { $0.webArea === target }?.frozenWebBounds ?? target.bounds
+ for v in views where v.frame != bounds { v.frame = bounds }
+ if embedFocusTab == id { focusEmbeddedPage(id) }
+ }
+
+ /// `cra://debug?embedDump=1`: where every page view is, for EmbeddedPages work.
+ func embeddedPagesDump() -> String {
+ func tree(_ v: NSView, _ depth: Int) -> String {
+ var s = String(repeating: " ", count: depth) + "\(type(of: v)) \(v.frame) hidden=\(v.isHidden) layer=\(v.layer.map { "\(type(of: $0)) \($0.bounds) hidden=\($0.isHidden) sub=\($0.sublayers?.count ?? 0)" } ?? "nil")\n"
+ if depth < 4 { for sub in v.subviews { s += tree(sub, depth + 1) } }
+ return s
+ }
+ var out = "embedded pages (enabled=\(EmbeddedPages.isEnabled)) key=\(window?.isKeyWindow ?? false) fr=\(String(describing: window?.firstResponder))\n"
+ for c in shell.paneCards { out += "card \(c.tabID.uuidString.prefix(8)) \(c.frame)\n" + tree(c.webArea, 1) }
+ for (id, rt) in browsers.runtimes {
+ guard let w = rt.hostWindow else { continue }
+ out += "host \(id.uuidString.prefix(8)) win \(w.windowNumber) alpha=\(w.alphaValue) visible=\(w.isVisible) host=\(EmbeddedPages.isHost(w)) frame \(w.frame)\n"
+ if let cv = w.contentView { out += tree(cv, 1) }
+ }
+ return out
+ }
+
+ /// An embedded page stays this window's first responder after its pane loses focus (an empty
+ /// split pane opened beside it). When the window became key again (the command bar closing)
+ /// the page reported focus, which selects its pane, and the URL meant for the empty pane
+ /// opened as a new tab. A page window never had that: it was a window of its own.
+ private func releaseUnfocusedEmbeddedPage() {
+ guard EmbeddedPages.isEnabled, let window, let responder = window.firstResponder as? NSView,
+ NSStringFromClass(type(of: responder)) == "RenderWidgetHostViewCocoa" else { return }
+ let focused = browsers.visibleTabID.flatMap { browsers.runtime(for: $0)?.hostWindow }.flatMap(EmbeddedPages.pageViews(of:)) ?? []
+ if !focused.contains(where: { responder.isDescendant(of: $0) }) { window.makeFirstResponder(nil) }
+ }
+
+ /// The tab whose embedded page should take keyboard focus once it is in its card.
+ private var embedFocusTab: UUID?
+
+ private func focusEmbeddedPage(_ id: UUID) {
+ guard let window, let host = browsers.runtime(for: id)?.hostWindow,
+ let view = EmbeddedPages.pageViews(of: host)?.last, view.window === window else { return }
+ embedFocusTab = nil
+ // Never from a panel that has the keys (the command bar filling a split pane, the find bar).
+ if let key = NSApp.keyWindow, key !== window, !EmbeddedPages.isHost(key), key.parent === window { return }
+ window.makeKey()
+ if let render = EmbeddedPages.renderView(in: view) { window.makeFirstResponder(render) }
+ }
+
/// Diagnostic log shared with the bridge: `defaults write dk.kildahl.cra devToolsLog -bool YES`.
private static let devToolsLogEnabled = UserDefaults.standard.bool(forKey: "devToolsLog")
private func devToolsLog(_ message: @autoclosure () -> String) {
@@ -709,20 +808,25 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
else { try? line.write(toFile: path, atomically: true, encoding: .utf8) }
}
- /// Every visible page window follows its pane; hidden tabs park on the focused rect.
+ /// Every visible page window follows its pane. Hidden tabs are left where they are and
+ /// sized when they show (browserManagerPageWindowsChanged): each resize makes Chromium lay
+ /// the page out synchronously, ~5 ms a window, which once ran for every loaded tab on
+ /// every sidebar toggle and every step of a window resize.
private func positionPageWindows(_ frames: [UUID: NSRect]) {
guard let window, !frames.isEmpty else { return }
lastPaneFrames = frames
let focusRect = (browsers.visibleTabID.flatMap { frames[$0] }) ?? frames.values.first!
let focusPage = browsers.visibleTabID.map { pageRect(forBody: focusRect, tab: $0) } ?? focusRect
let live = pageWindowsFollowLive || shell.devToolsFrontendDocked
- for (id, rt) in browsers.runtimes {
- guard let w = rt.hostWindow else { continue }
+ for id in browsers.visibleTabIDs {
+ guard let w = browsers.runtime(for: id)?.hostWindow else { continue }
let body = frames[id] ?? focusRect
let page = pageRect(forBody: body, tab: id)
let target = window.convertToScreen(page)
if w.frame != target { w.setFrame(target, display: live) }
updatePageCorners(w, page: page, body: body)
+ // A switch can show the page before its card exists; the card is laid out by now.
+ embedPage(id, from: w)
if shell.devToolsFrontendDocked, w.isVisible {
devToolsLog("page win \(w.windowNumber) '\(w.title)' tab \(id.uuidString.prefix(8)) visible=\(browsers.visibleTabIDs.contains(id)) body \(body) page \(page) style \(w.styleMask.rawValue) parent \(w.parent?.windowNumber ?? -1)")
}
@@ -735,20 +839,35 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
layoutToastPanel()
}
- private func animatePageWindows(to frames: [UUID: NSRect], duration: TimeInterval) {
+ /// Pages follow their cards without Chromium laying them out on every frame (an animated
+ /// window frame resized the page at each step, a synchronous layout each time, and the
+ /// page trailed its card). Each page takes its final frame at once; one that grows is
+ /// revealed from its old edges by a mask animated in step with the card. One that shrinks
+ /// needs nothing: its card, painted in the page's colour, slides under the gap.
+ private func animatePageWindows(to frames: [UUID: NSRect], duration: TimeInterval, timing: CAMediaTimingFunction) {
guard let window, !frames.isEmpty else { return }
lastPaneFrames = frames
let focusRect = (browsers.visibleTabID.flatMap { frames[$0] }) ?? frames.values.first!
let focusPage = browsers.visibleTabID.map { pageRect(forBody: focusRect, tab: $0) } ?? focusRect
+ for id in browsers.visibleTabIDs {
+ guard let w = browsers.runtime(for: id)?.hostWindow, let body = frames[id] else { continue }
+ let page = pageRect(forBody: body, tab: id)
+ let target = window.convertToScreen(page)
+ let from = w.frame
+ CATransaction.begin()
+ if from != target {
+ w.setFrame(target, display: true)
+ fillContentView(w)
+ }
+ updatePageCorners(w, page: page, body: body)
+ if w.isVisible, !EmbeddedPages.isHost(w), let cv = w.contentView {
+ revealPage(cv, from: from, to: target, duration: duration, timing: timing)
+ }
+ CATransaction.commit()
+ }
NSAnimationContext.runAnimationGroup { ctx in
ctx.duration = duration
- ctx.timingFunction = CAMediaTimingFunction(controlPoints: 0.2, 0.85, 0.25, 1)
- for id in browsers.visibleTabIDs {
- guard let w = browsers.runtime(for: id)?.hostWindow, let body = frames[id] else { continue }
- let page = pageRect(forBody: body, tab: id)
- w.animator().setFrame(window.convertToScreen(page), display: true)
- updatePageCorners(w, page: page, body: body)
- }
+ ctx.timingFunction = timing
if shell.devToolsFrontendDocked, let dev = browsers.visibleDevToolsWindow, dev.parent === window,
let focusID = browsers.visibleTabID, let body = frames[focusID] {
dev.animator().setFrame(window.convertToScreen(body), display: true)
@@ -759,6 +878,42 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
}
+ /// Masks a page that just grew from `from` to `to` (screen rects) down to the part it
+ /// covered before, then opens the mask to the full page over the card's animation.
+ private func revealPage(_ view: NSView, from: NSRect, to: NSRect, duration: TimeInterval, timing: CAMediaTimingFunction) {
+ guard duration > 0, let layer = view.layer else { return }
+ let shown = from.intersection(to)
+ guard !shown.isEmpty, shown.width < to.width - 0.5 || shown.height < to.height - 0.5 else { return }
+ let start = NSRect(x: shown.minX - to.minX, y: view.isFlipped ? to.maxY - shown.maxY : shown.minY - to.minY,
+ width: shown.width, height: shown.height)
+ let end = view.bounds
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ let mask = CALayer()
+ mask.backgroundColor = NSColor.black.cgColor
+ // The moving edge is the card's edge, rounded like it.
+ mask.cornerRadius = layer.cornerRadius
+ mask.cornerCurve = .continuous
+ mask.maskedCorners = layer.maskedCorners
+ mask.frame = end
+ layer.mask = mask
+ CATransaction.setCompletionBlock { [weak layer, weak mask] in
+ if let layer, let mask, layer.mask === mask { layer.mask = nil }
+ }
+ let bounds = CABasicAnimation(keyPath: "bounds")
+ bounds.fromValue = NSValue(rect: NSRect(origin: .zero, size: start.size))
+ bounds.toValue = NSValue(rect: NSRect(origin: .zero, size: end.size))
+ let position = CABasicAnimation(keyPath: "position")
+ position.fromValue = NSValue(point: NSPoint(x: start.midX, y: start.midY))
+ position.toValue = NSValue(point: NSPoint(x: end.midX, y: end.midY))
+ let group = CAAnimationGroup()
+ group.animations = [bounds, position]
+ group.duration = duration
+ group.timingFunction = timing
+ mask.add(group, forKey: "reveal")
+ CATransaction.commit()
+ }
+
/// Where a page goes inside its pane body: the whole body, or, with Chrome's docked
/// frontend, the placeholder the frontend reported. The placeholder keeps its offsets
/// from the body's edges while the body is still resizing, so the page follows at
@@ -832,10 +987,14 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
let selfDock = visible != nil && browsers.visibleRuntime?.hostWindow != nil
let docked = browsers.visibleTabID.flatMap { browsers.devToolsDockedState[$0] } ?? true
devToolsLog("devToolsChanged visible=\(visible?.windowNumber ?? -1) selfDock=\(selfDock) docked=\(docked) visibleTabs=\(browsers.visibleTabIDs.map { $0.uuidString.prefix(8) }) overlay=\(overlayPanel?.windowNumber ?? -1)")
- shell.devToolsFrontendDocked = selfDock
- shell.devToolsVisible = visible != nil && (docked || !selfDock)
- shell.needsLayout = true
- shell.layoutSubtreeIfNeeded()
+ // This runs on every tab switch; the shell is laid out again only when the dock changed.
+ let devToolsVisible = visible != nil && (docked || !selfDock)
+ if visible != nil || shell.devToolsFrontendDocked != selfDock || shell.devToolsVisible != devToolsVisible {
+ shell.devToolsFrontendDocked = selfDock
+ shell.devToolsVisible = devToolsVisible
+ shell.needsLayout = true
+ shell.layoutSubtreeIfNeeded()
+ }
guard let w = visible else {
if shell.frontendPageRect != nil { shell.frontendPageRect = nil }
positionPageWindows(lastPaneFrames)
@@ -978,7 +1137,16 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
}
- func browserManagerHandleKey(_ event: NSEvent) -> Bool { app.handleReservedKey(event) }
+ func browserManagerHandleKey(_ event: NSEvent) -> Bool {
+ // Chrome: Escape leaves a page's element fullscreen, before the page sees the key.
+ // Chrome's own handling never got it here: the video stayed fullscreen.
+ if event.keyCode == 53, event.modifierFlags.intersection([.command, .shift, .option, .control]).isEmpty,
+ let id = contentFullscreenTab, let browser = browsers.runtime(for: id)?.browser {
+ browser.exitFullscreen()
+ return true
+ }
+ return app.handleReservedKey(event)
+ }
func browserManagerHandleUnhandledKey(_ event: NSEvent) -> Bool { app.handleUnhandledKey(event) }
/// A hidden page asked for focus: the Picture in Picture window's "back to tab" button.
func browserManagerFocusedBrowser(_ tabID: UUID) {
@@ -1717,6 +1885,17 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
/// Back in this window: pages that moved to another window come back (Arc's untargeted
/// reparenting). After AppDelegate has made this the active window.
+ /// This window shows the tab's blurred stand-in while another window holds its page.
+ func isShowingElsewhere(_ tabID: UUID) -> Bool {
+ !isTornDown && shell.paneCards.contains { $0.tabID == tabID && $0.showsElsewhere }
+ }
+
+ /// A page handed over by a window that is closing.
+ func takePage(_ rt: TabRuntime) {
+ browsers.adopt(rt.browser, for: rt.tabID)
+ refresh()
+ }
+
private func reclaimPages() {
guard shell.paneCards.contains(where: \.showsElsewhere) else { return }
DispatchQueue.main.async { [weak self] in self?.refresh() }
@@ -1744,10 +1923,18 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
shell.needsLayout = true
}
+ /// The frame lives in the store's observed prefs, which every sidebar row reads (selection):
+ /// it is stored once a resize or move settles, not on every step of it.
private func saveFrame() {
- guard let window, !window.styleMask.contains(.fullScreen) else { return }
- store.updateWindow(windowID) { $0.frame = NSStringFromRect(window.frame) }
+ frameSaveWork?.cancel()
+ let work = DispatchWorkItem { [weak self] in
+ guard let self, let window = self.window, !window.styleMask.contains(.fullScreen) else { return }
+ self.store.updateWindow(self.windowID) { $0.frame = NSStringFromRect(window.frame) }
+ }
+ frameSaveWork = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: work)
}
+ private var frameSaveWork: DispatchWorkItem?
func windowShouldClose(_ sender: NSWindow) -> Bool {
if sender === window { commandBar.close() }
@@ -1765,6 +1952,13 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
func tearDown() {
isTornDown = true
dismissTransientUI()
+ // A page another window shows behind its blurred stand-in moves there with its history
+ // and state; closed with this window, that window loaded it again from scratch.
+ for id in Array(browsers.runtimes.keys) {
+ guard let other = app.mainWindows.first(where: { $0 !== self && $0.isShowingElsewhere(id) }),
+ let rt = browsers.release(id) else { continue }
+ other.takePage(rt)
+ }
browsers.closeAll()
for monitor in [scrollMonitor, childClickMonitor, middleClickMonitor].compactMap({ $0 }) { NSEvent.removeMonitor(monitor) }
scrollMonitor = nil
diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mm
index bf25364..cd552de 100644
--- a/Sources/CraCEF/CraCEF.mm
+++ b/Sources/CraCEF/CraCEF.mm
@@ -71,6 +71,58 @@ static CefString CefStringFromNS(NSString* s) {
return CefString(std::string(s.UTF8String ?: ""));
}
+/// Page context menus shown by Cra (RunContextMenu) instead of Chrome.
+static BOOL g_ownContextMenus = NO;
+
+/// The command picked from a context menu Cra shows; -1 while none is.
+@interface CraMenuPick : NSObject
+@property (nonatomic) int commandID;
+- (void)choose:(NSMenuItem*)item;
+@end
+
+@implementation CraMenuPick
+- (instancetype)init {
+ if ((self = [super init])) _commandID = -1;
+ return self;
+}
+- (void)choose:(NSMenuItem*)item { self.commandID = (int)item.tag; }
+@end
+
+/// Chrome's labels mark mnemonics with "&" ("&&" is a literal ampersand).
+static NSString* CraMenuLabel(CefRefPtr<CefMenuModel> model, size_t i) {
+ NSString* s = NSStringFromCef(model->GetLabelAt(i));
+ s = [s stringByReplacingOccurrencesOfString:@"&&" withString:@"\u0001"];
+ s = [s stringByReplacingOccurrencesOfString:@"&" withString:@""];
+ return [s stringByReplacingOccurrencesOfString:@"\u0001" withString:@"&"];
+}
+
+static NSMenu* CraMenuFromModel(CefRefPtr<CefMenuModel> model, CraMenuPick* pick) {
+ NSMenu* menu = [[NSMenu alloc] initWithTitle:@""];
+ menu.autoenablesItems = NO;
+ for (size_t i = 0; i < model->GetCount(); i++) {
+ cef_menu_item_type_t type = model->GetTypeAt(i);
+ if (type == MENUITEMTYPE_SEPARATOR) {
+ if (menu.numberOfItems > 0 && !menu.itemArray.lastObject.isSeparatorItem) [menu addItem:[NSMenuItem separatorItem]];
+ continue;
+ }
+ if (type == MENUITEMTYPE_NONE) continue;
+ NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:CraMenuLabel(model, i) action:nil keyEquivalent:@""];
+ if (type == MENUITEMTYPE_SUBMENU) {
+ item.submenu = CraMenuFromModel(model->GetSubMenuAt(i), pick);
+ } else {
+ item.action = @selector(choose:);
+ item.target = pick;
+ item.tag = model->GetCommandIdAt(i);
+ if (model->IsCheckedAt(i)) item.state = NSControlStateValueOn;
+ }
+ item.enabled = model->IsEnabledAt(i);
+ item.hidden = !model->IsVisibleAt(i);
+ [menu addItem:item];
+ }
+ while (menu.itemArray.lastObject.isSeparatorItem) [menu removeItem:menu.itemArray.lastObject];
+ return menu;
+}
+
enum CraMenuCommand {
kMenuOpenLinkInNewTab = MENU_ID_USER_FIRST + 1,
kMenuOpenLinkInBackgroundTab,
@@ -1076,6 +1128,25 @@ public:
// Context menu --------------------------------------------------------
+ // Embedded pages (EmbeddedPages.swift): Chrome shows the menu through the views widget that
+ // owns the page's view, found through the view's window, which is now Cra's: it showed
+ // nothing. Cra shows the menu itself and hands the pick back.
+ bool RunContextMenu(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,
+ CefRefPtr<CefContextMenuParams> params, CefRefPtr<CefMenuModel> model,
+ CefRefPtr<CefRunContextMenuCallback> callback) override {
+ if (!g_ownContextMenus || model->GetCount() == 0) return false;
+ CraMenuPick* pick = [CraMenuPick new];
+ NSMenu* menu = CraMenuFromModel(model, pick);
+ NSPoint at = [NSEvent mouseLocation];
+ CefRefPtr<CefRunContextMenuCallback> done = callback;
+ dispatch_async(dispatch_get_main_queue(), ^{
+ [menu popUpMenuPositioningItem:nil atLocation:at inView:nil];
+ if (pick.commandID >= 0) done->Continue(pick.commandID, EVENTFLAG_NONE);
+ else done->Cancel();
+ });
+ return true;
+ }
+
void OnBeforeContextMenu(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame,
CefRefPtr<CefContextMenuParams> params, CefRefPtr<CefMenuModel> model) override {
size_t index = 0;
@@ -1424,7 +1495,10 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {
}
- (void)createNow {
- if (_isClosed || _browser) return;
+ // Closing pages at quit changes the sidebar, and the window's refresh then asked for a
+ // page Chromium could no longer make: Cra crashed at quit in CreateBrowserView or
+ // CreateTopLevelWindow.
+ if (_isClosed || _browser || g_quitting) return;
if (!_isIncognito && !ProfileReady(_profilePath, self)) return;
if (g_chromeHosting) {
CefBrowserSettings settings;
@@ -1822,6 +1896,7 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {
@implementation CraCEFRuntime
+ (void)setChromeHosting:(BOOL)enabled { g_chromeHosting = enabled; }
++ (void)setOwnContextMenus:(BOOL)enabled { g_ownContextMenus = enabled; }
+ (BOOL)chromeHosting { return g_chromeHosting; }
+ (void)setContentBlockingEnabled:(BOOL)enabled { cra_blocker::Enabled().store(enabled); }
diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.h
index 952457f..46306a1 100644
--- a/Sources/CraCEF/include/CraCEF.h
+++ b/Sources/CraCEF/include/CraCEF.h
@@ -176,6 +176,8 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
/// DevTools) instead of embedded Alloy views. Set before any browser exists.
+ (void)setChromeHosting:(BOOL)enabled;
+ (BOOL)chromeHosting;
+/// Page context menus are shown by Cra, not Chrome (pages embedded in their cards).
++ (void)setOwnContextMenus:(BOOL)enabled;
/// Third-party ad and tracker blocking: subresource and subframe requests whose host
/// (or a parent domain) is on the blocked list are cancelled when they are third-party
/// to the tab's top-level page. Main-frame navigations always load. Takes effect for
diff --git a/docs/development.md b/docs/development.md
index f8ba81a..0942a82 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -48,6 +48,17 @@ build next to your daily Cra with its own data folder and a command file:
Every line appended to `CRA_COMMAND_FILE` is handled like a `cra://` URL, including the
scripting hosts below.
+To measure smoothness, add `CRA_HITCH_LOG=/tmp/cra-hitch.log`: every main-thread stall of
+8 ms or more is logged (`<seconds> stall <ms>`), with each command-file line as a
+`mark` between them. The main thread is also Chromium's browser UI thread, so a stall
+there delays input and scrolling too. Compare builds by running the same command
+script against each.
+
+`CRA_EMBED_PAGES=1` (or `defaults write dk.kildahl.cra embedPages -bool YES`) turns on the
+experimental page embedding in `EmbeddedPages.swift`: Chromium's page view moves from its
+Chrome window into the pane card, like Arc and Dia, and the Chrome window stays behind
+invisible and click-through. Pages go back into their window while DevTools is open.
+
## Scripting hooks
Cra registers the `cra://` scheme so it can be driven from a shell: