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.17: pages embedded in the window, smoother sidebar and command bar

Victor3aae97c3a428
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index 0c33caf..345d82b 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -73,7 +73,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
}
LiveFolderManager.shared.start(store: store)
// A restart into an update while the user was away leaves the front app alone.
- if !SoftwareUpdater.shared.launchedByAutoUpdate { NSApp.activate(ignoringOtherApps: true) }
+ if HitchMonitor.background {
+ // Measured behind whatever is in front; still on screen, so pages keep drawing.
+ for w in mainWindows { w.window?.orderBack(nil) }
+ } else if !SoftwareUpdater.shared.launchedByAutoUpdate {
+ NSApp.activate(ignoringOtherApps: true)
+ }
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in self?.installURLEventHandler() }
// Extension welcome pages and chrome.tabs.create land in Cra, not in a Chrome window.
// --load-extension extensions count as freshly installed on every launch, so their
@@ -422,13 +427,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
let comps = URLComponents(url: u, resolvingAgainstBaseURL: false)
func q(_ name: String) -> String? { comps?.queryItems?.first { $0.name == name }?.value }
// Actions keep their target: a key Little Window stays key (perform routes to it).
- if u.host != "action" || keyLittleWindow == nil {
+ // A background test instance (CRA_TEST_BACKGROUND) never comes to the front.
+ if (u.host != "action" || keyLittleWindow == nil) && !HitchMonitor.background {
main.showWindow(nil)
NSApp.activate(ignoringOtherApps: true)
}
switch u.host {
case "commandbar":
- main.openCommandBar(q("mode") == "edit" ? .editURL : .newTab)
+ // With the bar already open a new query is the next keystroke, not a new session.
+ if !(main.commandBar.isOpen && q("query") != nil) { main.openCommandBar(q("mode") == "edit" ? .editURL : .newTab) }
if let text = q("query") { main.commandBar.setQuery(text) }
case "action":
perform(String(u.path.dropFirst()))
@@ -623,9 +630,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
/// Keys the page let through (CEF OnKeyEvent). Anything we know runs here;
/// returning false lets CEF pass the key on to the menu bar (⌘Q, ⌘H…).
func handleUnhandledKey(_ event: NSEvent) -> Bool {
- guard let action = bindings.action(for: event) else { return false }
- perform(action.id)
- return true
+ if let action = bindings.action(for: event) {
+ perform(action.id)
+ return true
+ }
+ // Chromium hands a ⌘-key the page left alone back to the menu bar through its own
+ // window's command dispatcher (⌘C, ⌘V, ⌘A, ⌘Z exist only as Edit menu items). An
+ // embedded page sits in Cra's window, which has none: the key was dropped.
+ if event.modifierFlags.contains(.command), let key = NSApp.keyWindow,
+ !key.responds(to: NSSelectorFromString("commandDispatcher")) {
+ return NSApp.mainMenu?.performKeyEquivalent(with: event) ?? false
+ }
+ return false
}
func perform(_ id: String) {
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index 430c505..3ef8793 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -196,6 +196,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
}
visibleTabIDs = shown
visibleTabID = focused.flatMap { newSet.contains($0) ? $0 : nil } ?? shown.first
+ if wasVisible != Set(shown) { HitchMonitor.mark("page-shown") }
if focus, let f = visibleTabID, let rt = runtimes[f] { rt.browser.setFocused(true) }
for id in shown where !wasVisible.contains(id) { scheduleSnapshot(id) }
syncDevToolsVisibility()
diff --git a/Sources/Cra/Services/HitchMonitor.swift b/Sources/Cra/Services/HitchMonitor.swift
index 764ae32..7e97b20 100644
--- a/Sources/Cra/Services/HitchMonitor.swift
+++ b/Sources/Cra/Services/HitchMonitor.swift
@@ -1,7 +1,7 @@
import Foundation
import QuartzCore
-/// Testing aid: with CRA_HITCH_LOG=<path> set, every main-thread stall of 8 ms or
+/// Testing aids. 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.
@@ -9,7 +9,16 @@ enum HitchMonitor {
private static let lock = NSLock()
nonisolated(unsafe) private static var handle: FileHandle?
+ /// CRA_TEST_BACKGROUND=1: a test instance measured behind other apps. Scripted commands
+ /// don't bring it to the front, and App Nap doesn't slow it down.
+ static let background = ProcessInfo.processInfo.environment["CRA_TEST_BACKGROUND"] == "1"
+ nonisolated(unsafe) private static var activity: NSObjectProtocol?
+
static func startIfRequested() {
+ if background {
+ activity = ProcessInfo.processInfo.beginActivity(options: [.userInitiated, .latencyCritical, .idleSystemSleepDisabled],
+ reason: "Background test instance")
+ }
guard let path = ProcessInfo.processInfo.environment["CRA_HITCH_LOG"], !path.isEmpty else { return }
FileManager.default.createFile(atPath: path, contents: nil)
handle = FileHandle(forWritingAtPath: path)
diff --git a/Sources/Cra/Services/SuggestionEngine.swift b/Sources/Cra/Services/SuggestionEngine.swift
index 023f3c9..81173f0 100644
--- a/Sources/Cra/Services/SuggestionEngine.swift
+++ b/Sources/Cra/Services/SuggestionEngine.swift
@@ -74,7 +74,7 @@ final class SuggestionEngine {
// Incognito: the window's own tabs, search and commands; nothing from the normal profile.
if !incognito {
items.append(contentsOf: archiveSuggestions(q))
- items.append(contentsOf: historySuggestions(q, openURLs: Set(store.profileTabs(window: nil).compactMap { $0.tab?.url })))
+ items.append(contentsOf: historySuggestions(q, openURLs: searchIndex.openURLs))
items.append(contentsOf: topDomainSuggestions(q))
}
items.append(contentsOf: commandSuggestions(q, currentTabID: currentTabID))
@@ -102,6 +102,51 @@ final class SuggestionEngine {
return result
}
+ // MARK: Search index
+
+ /// What scoring needs from a title and a URL. Worked out per keystroke for every tab,
+ /// archived tab and history entry (a URL parse each) it held up typing in the command bar.
+ struct Searchable {
+ let title: String
+ let words: [Substring]
+ let url: String
+ let host: String
+ let bareHost: String
+
+ init(title: String, url: String) {
+ self.title = title.lowercased()
+ words = self.title.split(whereSeparator: { !$0.isLetter && !$0.isNumber })
+ self.url = SuggestionEngine.humanURL(url).lowercased()
+ host = (URL(string: url)?.host ?? "").lowercased()
+ bareHost = host.hasPrefix("www.") ? String(host.dropFirst(4)) : host
+ }
+ }
+
+ private struct SearchIndex {
+ var tabs: [(SidebarItem, Searchable)] = []
+ var archive: [(ArchivedItem, Searchable)] = []
+ var history: [(HistoryEntry, Searchable)] = []
+ var openURLs: Set<String> = []
+ }
+
+ private var index: SearchIndex?
+
+ /// Built on the first keystroke after the command bar opens, kept until it closes.
+ private var searchIndex: SearchIndex {
+ if let index { return index }
+ var i = SearchIndex()
+ let tabs = store.profileTabs(window: nil)
+ i.tabs = tabs.compactMap { tab in tab.tab.map { (tab, Searchable(title: tab.displayTitle, url: $0.url)) } }
+ i.openURLs = Set(tabs.compactMap { $0.tab?.url })
+ i.archive = store.archive.prefix(400).compactMap { e in e.item.tab.map { (e, Searchable(title: e.item.displayTitle, url: $0.url)) } }
+ i.history = store.history.values.map { ($0, Searchable(title: $0.title, url: $0.url)) }
+ index = i
+ return i
+ }
+
+ /// The command bar opened or closed: what it searches may have changed since.
+ func resetIndex() { index = nil }
+
// MARK: Typed text
static func looksLikeURL(_ s: String) -> Bool {
@@ -141,9 +186,9 @@ final class SuggestionEngine {
private func tabSuggestions(_ q: String, excluding current: UUID?) -> [Suggestion] {
var out: [Suggestion] = []
- for tab in store.profileTabs(window: nil) where tab.id != current {
+ for (tab, key) in searchIndex.tabs where tab.id != current {
guard let t = tab.tab else { continue }
- var score = textScore(q, title: tab.displayTitle, url: t.url)
+ var score = Self.score(q, key)
if let custom = tab.title?.lowercased(), custom.hasPrefix(q) { score += 40 }
if score < 30 { continue }
score += recencyBoost(t.timeLastActiveAt)
@@ -161,9 +206,9 @@ final class SuggestionEngine {
private func archiveSuggestions(_ q: String) -> [Suggestion] {
var out: [Suggestion] = []
- for entry in store.archive.prefix(400) {
+ for (entry, key) in searchIndex.archive {
guard let t = entry.item.tab else { continue }
- var score = textScore(q, title: entry.item.displayTitle, url: t.url) * 0.85
+ var score = Self.score(q, key) * 0.85
if score < 30 { continue }
score += recencyBoost(entry.archivedAt) * 0.5
let spaceName = entry.sourceSpaceID.flatMap { store.space($0)?.title } ?? ""
@@ -176,8 +221,8 @@ final class SuggestionEngine {
private func historySuggestions(_ q: String, openURLs: Set<String>) -> [Suggestion] {
var out: [Suggestion] = []
- for h in store.history.values where !openURLs.contains(h.url) {
- var score = textScore(q, title: h.title, url: h.url) * 0.8
+ for (h, key) in searchIndex.history where !openURLs.contains(h.url) {
+ var score = Self.score(q, key) * 0.8
if score < 30 { continue }
score += min(Double(h.visitCount), 20) * 1.5 + recencyBoost(h.lastVisit) * 0.6
out.append(Suggestion(id: "hist:\(h.url)", kind: .history, title: h.title.isEmpty ? Self.humanURL(h.url) : h.title,
@@ -269,10 +314,11 @@ final class SuggestionEngine {
/// 0...100 from how well the query matches a title and a URL.
func textScore(_ q: String, title: String, url: String) -> Double {
- let t = title.lowercased()
- let u = Self.humanURL(url).lowercased()
- let host = (URL(string: url)?.host ?? "").lowercased()
- let bareHost = host.hasPrefix("www.") ? String(host.dropFirst(4)) : host
+ Self.score(q, Searchable(title: title, url: url))
+ }
+
+ private static func score(_ q: String, _ key: Searchable) -> Double {
+ let t = key.title, u = key.url, host = key.host, bareHost = key.bareHost
var score = 0.0
let tokens = q.split(separator: " ").map(String.init)
if tokens.count > 1 {
@@ -283,7 +329,7 @@ final class SuggestionEngine {
return score
}
if t.hasPrefix(q) { score = 100 }
- else if t.split(whereSeparator: { !$0.isLetter && !$0.isNumber }).contains(where: { $0.hasPrefix(q) }) { score = 85 }
+ else if key.words.contains(where: { $0.hasPrefix(q) }) { score = 85 }
else if t.contains(q) { score = 65 }
else if let f = fuzzy(q, in: t) { score = 25 + 25 * f }
if bareHost.hasPrefix(q) || host.hasPrefix(q) { score = max(score, 95) }
@@ -293,7 +339,7 @@ final class SuggestionEngine {
}
/// Subsequence match quality (0...1) or nil when not a subsequence.
- private func fuzzy(_ q: String, in text: String) -> Double? {
+ private static func fuzzy(_ q: String, in text: String) -> Double? {
guard q.count >= 3 else { return nil }
var it = text.makeIterator()
var matched = 0
@@ -355,7 +401,7 @@ final class SuggestionEngine {
// MARK: Formatting
- static func humanURL(_ url: String) -> String {
+ nonisolated static func humanURL(_ url: String) -> String {
var s = url
for p in ["https://www.", "http://www.", "https://", "http://"] where s.hasPrefix(p) { s = String(s.dropFirst(p.count)); break }
if s.hasSuffix("/") { s.removeLast() }
@@ -363,10 +409,14 @@ final class SuggestionEngine {
return s
}
- static func relative(_ date: Date) -> String {
+ private static let relativeFormatter: RelativeDateTimeFormatter = {
let f = RelativeDateTimeFormatter()
f.unitsStyle = .short
- return f.localizedString(for: date, relativeTo: Date())
+ return f
+ }()
+
+ static func relative(_ date: Date) -> String {
+ relativeFormatter.localizedString(for: date, relativeTo: Date())
}
}
diff --git a/Sources/Cra/UI/ArcTooltip.swift b/Sources/Cra/UI/ArcTooltip.swift
index e8ad0bb..6f0d2fe 100644
--- a/Sources/Cra/UI/ArcTooltip.swift
+++ b/Sources/Cra/UI/ArcTooltip.swift
@@ -15,8 +15,8 @@ final class ArcTooltipController {
static let warmWindow: TimeInterval = 0.5
private var panel: LittleTooltipPanel?
- private weak var shownFor: ArcTooltipAnchorView?
- private weak var pendingFor: ArcTooltipAnchorView?
+ private weak var shownFor: (any ArcTooltipTarget)?
+ private weak var pendingFor: (any ArcTooltipTarget)?
private var timer: Timer?
private var lastHiddenAt = Date.distantPast
private var clickMonitor: Any?
@@ -25,7 +25,7 @@ final class ArcTooltipController {
/// innermost (smallest) one owns the tip (Arc: TooltipController.enteredViewStack).
private var hovered: [WeakAnchor] = []
- private struct WeakAnchor { weak var view: ArcTooltipAnchorView? }
+ private struct WeakAnchor { weak var view: (any ArcTooltipTarget)? }
private init() {
clickMonitor = NSEvent.addLocalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown, .keyDown]) { [weak self] e in
@@ -39,11 +39,11 @@ final class ArcTooltipController {
}
}
- func mouseMoved(in view: ArcTooltipAnchorView) {
+ func mouseMoved(in view: any ArcTooltipTarget) {
if !hovered.contains(where: { $0.view === view }) { hovered.append(WeakAnchor(view: view)) }
let mouse = NSEvent.mouseLocation
hovered.removeAll { a in
- guard let v = a.view, v.window != nil else { return true }
+ guard let v = a.view, v.hostWindow != nil else { return true }
return !v.screenFrame.contains(mouse)
}
guard let target = hovered.compactMap(\.view).min(by: { $0.screenFrame.width * $0.screenFrame.height < $1.screenFrame.width * $1.screenFrame.height }),
@@ -56,7 +56,7 @@ final class ArcTooltipController {
startTip(for: target)
}
- private func startTip(for view: ArcTooltipAnchorView) {
+ private func startTip(for view: any ArcTooltipTarget) {
if panel != nil || Date().timeIntervalSince(lastHiddenAt) < Self.warmWindow {
show(for: view)
return
@@ -72,12 +72,12 @@ final class ArcTooltipController {
}
}
- func mouseExited(_ view: ArcTooltipAnchorView) {
+ func mouseExited(_ view: any ArcTooltipTarget) {
hovered.removeAll { $0.view === view || $0.view == nil }
if pendingFor === view { cancelPending() }
if shownFor === view { hide() }
// Leaving a close button for the rest of its row hands the tip back to the row.
- if let outer = hovered.last?.view, outer.window != nil { mouseMoved(in: outer) }
+ if let outer = hovered.last?.view, outer.hostWindow != nil { mouseMoved(in: outer) }
}
/// A click or key press: the next tip waits for the pointer to rest again, so a row that
@@ -94,9 +94,9 @@ final class ArcTooltipController {
pendingFor = nil
}
- private func show(for view: ArcTooltipAnchorView) {
+ private func show(for view: any ArcTooltipTarget) {
cancelPending()
- guard let window = view.window, !view.text.isEmpty else { return }
+ guard let window = view.hostWindow, !view.text.isEmpty else { return }
removePanel()
let p = LittleTooltipPanel()
let option = NSEvent.modifierFlags.contains(.option) ? view.optionText : nil
@@ -146,8 +146,21 @@ final class ArcTooltipController {
}
}
-/// Tracks the pointer over a control without taking its clicks.
-final class ArcTooltipAnchorView: NSView {
+/// What a tip belongs to: an AppKit control's anchor view, or a SwiftUI view's hover.
+@MainActor
+protocol ArcTooltipTarget: AnyObject {
+ var text: String { get }
+ var keys: [String] { get }
+ var followsCursor: Bool { get }
+ var subtitle: String? { get }
+ var optionText: String? { get }
+ var onShow: (() -> Void)? { get }
+ var screenFrame: NSRect { get }
+ var hostWindow: NSWindow? { get }
+}
+
+/// Tracks the pointer over an AppKit control without taking its clicks.
+final class ArcTooltipAnchorView: NSView, ArcTooltipTarget {
var text = ""
var keys: [String] = []
var followsCursor = false
@@ -158,6 +171,7 @@ final class ArcTooltipAnchorView: NSView {
var onShow: (() -> Void)?
var screenFrame: NSRect { window?.convertToScreen(convert(bounds, to: nil)) ?? .zero }
+ var hostWindow: NSWindow? { window }
/// For AppKit controls: an anchor filling `control`.
static func attach(to control: NSView, help: String) -> ArcTooltipAnchorView {
@@ -189,21 +203,70 @@ final class ArcTooltipAnchorView: NSView {
}
}
-private struct ArcTooltipAnchor: NSViewRepresentable {
+/// A SwiftUI view's tip, fed by its hover. No AppKit view per tip: the sidebar has hundreds of
+/// rows and buttons across its spaces, and an anchor view in each one had SwiftUI move every
+/// one of them, AppKit redo their tracking areas and rebuild its key view loop on every frame
+/// of a space swipe or sidebar scroll.
+@MainActor
+private final class ArcTooltipSource: ArcTooltipTarget {
+ var text = ""
+ var keys: [String] = []
+ var followsCursor = false
+ var subtitle: String?
+ var optionText: String?
+ var onShow: (() -> Void)?
+ var size = CGSize.zero
+ /// The view's frame on screen, worked out from the last hover: the pointer's screen
+ /// position and its position in the view.
+ private(set) var screenFrame = NSRect.zero
+ private(set) weak var hostWindow: NSWindow?
+
+ /// Called on every pointer move. The window under the pointer is a window server query,
+ /// so it is looked up once per visit (`entered`), not per move.
+ func hovered(at local: CGPoint, entered: Bool) {
+ let mouse = NSEvent.mouseLocation
+ // SwiftUI's local y grows downwards, the screen's upwards.
+ screenFrame = NSRect(x: mouse.x - local.x, y: mouse.y + local.y - size.height, width: size.width, height: size.height)
+ if entered || hostWindow == nil {
+ hostWindow = NSApp.window(withWindowNumber: NSWindow.windowNumber(at: mouse, belowWindowWithWindowNumber: 0))
+ }
+ }
+
+ /// Between the pointer arriving and leaving.
+ var isHovered = false
+}
+
+private struct ArcTooltipModifier: ViewModifier {
let text: String
let keys: [String]
let followsCursor: Bool
let subtitle: String?
let optionText: String?
let onShow: (() -> Void)?
- func makeNSView(context: Context) -> ArcTooltipAnchorView { ArcTooltipAnchorView() }
- func updateNSView(_ v: ArcTooltipAnchorView, context: Context) {
- v.text = text
- v.keys = keys
- v.followsCursor = followsCursor
- v.subtitle = subtitle
- v.optionText = optionText
- v.onShow = onShow
+ @State private var source = ArcTooltipSource()
+
+ func body(content: Content) -> some View {
+ content
+ .onGeometryChange(for: CGSize.self) { $0.size } action: { source.size = $0 }
+ .onContinuousHover(coordinateSpace: .local) { phase in
+ switch phase {
+ case .active(let location):
+ source.text = text
+ source.keys = keys
+ source.followsCursor = followsCursor
+ source.subtitle = subtitle
+ source.optionText = optionText
+ source.onShow = onShow
+ source.hovered(at: location, entered: !source.isHovered)
+ source.isHovered = true
+ ArcTooltipController.shared.mouseMoved(in: source)
+ case .ended:
+ source.isHovered = false
+ ArcTooltipController.shared.mouseExited(source)
+ }
+ }
+ // Row buttons vanish when the row loses hover; their tip goes with them.
+ .onDisappear { ArcTooltipController.shared.mouseExited(source) }
}
}
@@ -213,7 +276,7 @@ extension View {
func arcTooltip(_ help: String, followsCursor: Bool = false, subtitle: String? = nil,
optionHelp: String? = nil, onShow: (() -> Void)? = nil) -> some View {
let (text, keys) = ArcTooltipLabel.split(help)
- return background(ArcTooltipAnchor(text: text, keys: keys, followsCursor: followsCursor, subtitle: subtitle,
+ return modifier(ArcTooltipModifier(text: text, keys: keys, followsCursor: followsCursor, subtitle: subtitle,
optionText: optionHelp, onShow: onShow))
}
}
diff --git a/Sources/Cra/UI/CommandBar/CommandBarController.swift b/Sources/Cra/UI/CommandBar/CommandBarController.swift
index 0fdb3ea..7f9c3f4 100644
--- a/Sources/Cra/UI/CommandBar/CommandBarController.swift
+++ b/Sources/Cra/UI/CommandBar/CommandBarController.swift
@@ -45,6 +45,7 @@ final class CommandBarController {
}
func open(mode: CommandBarMode, prefill: String?) {
+ engine.resetIndex()
self.mode = mode
query = prefill ?? ""
fieldText = query
@@ -123,6 +124,7 @@ final class CommandBarController {
func close() {
guard isOpen else { return }
isOpen = false
+ engine.resetIndex()
onClose()
}
}
diff --git a/Sources/Cra/UI/ShellView.swift b/Sources/Cra/UI/ShellView.swift
index bb1f042..a3fcbcc 100644
--- a/Sources/Cra/UI/ShellView.swift
+++ b/Sources/Cra/UI/ShellView.swift
@@ -255,6 +255,18 @@ final class ShellView: NSView {
return
}
+ // One pane before and after, a plain tab switch: the card follows the tab.
+ if paneCards.count == 1, shownIDs.count == 1, let card = paneCards.first,
+ (card.tabID == ShellView.noTabID) == (shownIDs[0] == ShellView.noTabID) {
+ let id = shownIDs[0]
+ card.retarget(to: id, toolbar: makeToolbar?(id == ShellView.noTabID ? nil : id) ?? AnyView(EmptyView()))
+ card.pageColor = pageColors[id]
+ card.toolbarColor = toolbarColors[id]
+ card.hasPage = id != ShellView.noTabID && !empty.contains(id)
+ needsLayout = true
+ return
+ }
+
let oldFrames = Dictionary(uniqueKeysWithValues: paneCards.map { ($0.tabID, $0.frame) })
var cards: [PaneCardView] = []
for id in shownIDs {
diff --git a/Sources/Cra/UI/Sidebar/SidebarRootView.swift b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
index 51e74cb..27aa0f4 100644
--- a/Sources/Cra/UI/Sidebar/SidebarRootView.swift
+++ b/Sources/Cra/UI/Sidebar/SidebarRootView.swift
@@ -35,21 +35,22 @@ struct SidebarRootView: View {
GeometryReader { g in
let spaces = store.pagedSpaces(window: ui.windowID)
let index = CGFloat(spaces.firstIndex { $0.id == space.id } ?? 0)
- HStack(alignment: .top, spacing: 0) {
- ForEach(spaces) { s in
- // Arc 1.170 keeps favorites and the space header fixed; only the
- // space's tab list scrolls (SpaceSectionView owns that scroll view).
- // Favorites belong to the space, so they page with it.
- VStack(spacing: 0) {
- FavoritesGrid(space: s, palette: s.theme.palette)
- .padding(.horizontal, 8)
- SpaceSectionView(space: s, palette: s.theme.palette)
+ SpacePagerStrip(index: index, width: g.size.width) {
+ HStack(alignment: .top, spacing: 0) {
+ ForEach(spaces) { s in
+ // Arc 1.170 keeps favorites and the space header fixed; only the
+ // space's tab list scrolls (SpaceSectionView owns that scroll view).
+ // Favorites belong to the space, so they page with it.
+ VStack(spacing: 0) {
+ FavoritesGrid(space: s, palette: s.theme.palette)
+ .padding(.horizontal, 8)
+ SpaceSectionView(space: s, palette: s.theme.palette)
+ }
+ .foregroundStyle(s.theme.palette.textPrimary)
+ .frame(width: g.size.width, height: g.size.height, alignment: .top)
}
- .foregroundStyle(s.theme.palette.textPrimary)
- .frame(width: g.size.width, height: g.size.height, alignment: .top)
}
}
- .offset(x: -(index + ui.spaceSwipe) * g.size.width)
}
.frame(maxHeight: .infinity, alignment: .top)
.clipped()
@@ -296,15 +297,15 @@ struct SpaceSectionView: View {
@Environment(SidebarUIState.self) private var ui
@Environment(\.sidebarActions) private var actions
@State private var hoverDivider = false
- @State private var rowsFrame = CGRect.zero
+ /// Arc 1.170 draws a full-width 1pt hairline (~5% black over the light theme) at an edge of
+ /// the list only while rows are hidden past it, fading over ~0.25s. Only whether rows hide
+ /// past each edge is kept, not the rows' frame: that changed on every frame of a scroll and
+ /// re-ran this whole list's body each time.
+ @State private var scrolledUnderTop = false
+ @State private var rowsBelowBottom = false
@State private var viewportHeight: CGFloat = 0
@State private var autoscroller = DragAutoscroller()
- /// Arc 1.170 draws a full-width 1pt hairline (~5% black over the light theme) at an edge of
- /// the list only while rows are hidden past it, fading over ~0.25s.
- private var scrolledUnderTop: Bool { rowsFrame.minY < -0.5 }
- private var rowsBelowBottom: Bool { rowsFrame.maxY > viewportHeight + 0.5 }
-
var body: some View {
VStack(alignment: .leading, spacing: 0) {
SpaceHeader(space: space, palette: palette)
@@ -314,7 +315,8 @@ struct SpaceSectionView: View {
ScrollView(.vertical, showsIndicators: false) {
rows
.padding(.top, 3)
- .onGeometryChange(for: CGRect.self) { $0.frame(in: .named(Self.scrollSpace)) } action: { rowsFrame = $0 }
+ .onGeometryChange(for: Bool.self) { $0.frame(in: .named(Self.scrollSpace)).minY < -0.5 } action: { scrolledUnderTop = $0 }
+ .onGeometryChange(for: Bool.self) { [viewportHeight] in $0.frame(in: .named(Self.scrollSpace)).maxY > viewportHeight + 0.5 } action: { rowsBelowBottom = $0 }
// Arc leaves ~121pt of empty list after the last row at full scroll.
.padding(.bottom, 121)
.overlay(alignment: .topLeading) { dropLine }
@@ -549,3 +551,42 @@ private struct SpaceListMenu: View {
Button("Edit Space…") { actions.editSpace(space) }
}
}
+
+/// The strip of space lists. It moves as a render effect, never by layout: a layout offset
+/// moved the geometry of every row in every space on every frame, re-ran hover for the rows
+/// sliding under a resting pointer and had SwiftUI rebuild its key view loop (~1 s of main
+/// thread over six swipes). The page index places the strip at once; what is left to travel,
+/// a live swipe or the spring after a space change, is the render offset. The strip takes no
+/// clicks or hovers under the fingers. Only this view reads the swipe; the caller builds the lists.
+private struct SpacePagerStrip<Content: View>: View {
+ let index: CGFloat
+ let width: CGFloat
+ @ViewBuilder let content: Content
+ @Environment(SidebarUIState.self) private var ui
+ /// Pages still to travel after a space change by click or shortcut; springs to 0.
+ @State private var shift: CGFloat = 0
+
+ var body: some View {
+ let x = -(ui.spaceSwipe + shift) * width
+ content
+ .offset(x: -index * width)
+ .animation(nil, value: index)
+ .visualEffect { view, _ in view.offset(x: x) }
+ // Off only under the fingers: ignoring clicks for the whole spring made the sidebar
+ // feel unresponsive right after a space change.
+ .allowsHitTesting(ui.spaceSwipe == 0 && shift == 0)
+ .onChange(of: index) { old, new in
+ // A swipe re-bases itself (MainWindowController.endSpaceSwipe).
+ guard !ui.spaceSettling else { return }
+ var instant = Transaction()
+ instant.disablesAnimations = true
+ withTransaction(instant) { shift = old - new }
+ let generation = ui.beginSpaceSettle()
+ withAnimation(ui.spaceSettleAnimation, completionCriteria: .logicallyComplete) {
+ shift = 0
+ } completion: {
+ ui.endSpaceSettle(generation)
+ }
+ }
+ }
+}
diff --git a/Sources/Cra/UI/SidebarUIState.swift b/Sources/Cra/UI/SidebarUIState.swift
index fb63f13..8db0ad7 100644
--- a/Sources/Cra/UI/SidebarUIState.swift
+++ b/Sources/Cra/UI/SidebarUIState.swift
@@ -69,6 +69,27 @@ final class SidebarUIState {
var spaceSwipe: CGFloat = 0
/// Release velocity for the settle spring, relative to the distance left to travel.
var spaceSettleVelocity: Double = 0
+ /// The strip is springing onto its page (after a swipe or a space change); it takes no
+ /// clicks or hovers until then.
+ var spaceSettling = false
+ @ObservationIgnored private var settleGeneration = 0
+
+ /// Returns the settle's number for `endSpaceSettle`.
+ func beginSpaceSettle() -> Int {
+ spaceSettling = true
+ settleGeneration &+= 1
+ let generation = settleGeneration
+ // A spring cut short may never report back: don't leave the strip ignoring clicks.
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in self?.endSpaceSettle(generation) }
+ return generation
+ }
+
+ /// An earlier settle ending late leaves a newer one alone.
+ func endSpaceSettle(_ generation: Int) {
+ guard generation == settleGeneration, spaceSettling else { return }
+ spaceSettling = false
+ HitchMonitor.mark("swipe-settled")
+ }
/// Dia settles pages with a zero-bounce spring that picks up the release speed.
var spaceSettleAnimation: Animation {
.interpolatingSpring(duration: 0.4, bounce: 0, initialVelocity: spaceSettleVelocity)
diff --git a/Sources/Cra/UI/SplitView/PaneCardView.swift b/Sources/Cra/UI/SplitView/PaneCardView.swift
index 9a5afa6..6051acc 100644
--- a/Sources/Cra/UI/SplitView/PaneCardView.swift
+++ b/Sources/Cra/UI/SplitView/PaneCardView.swift
@@ -6,7 +6,7 @@ import SwiftUI
/// A pane without a page (Arc's "Search or Enter URL…" pane) is a translucent
/// tinted card with nothing but the toolbar.
final class PaneCardView: NSView {
- let tabID: UUID
+ private(set) var 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?
@@ -49,6 +49,17 @@ final class PaneCardView: NSView {
var showsElsewhere = false { didSet { elsewhereView.isHidden = !showsElsewhere } }
private let elsewhereView = NSView()
+ /// The card shows another tab now (a tab switch with one pane before and after). Building
+ /// a new card made a new SwiftUI toolbar host on every switch.
+ func retarget(to id: UUID, toolbar: AnyView) {
+ tabID = id
+ toolbarHost.rootView = toolbar
+ frozenWebBounds = nil
+ showsElsewhere = false
+ elsewhereSnapshot = nil
+ needsLayout = true
+ }
+
init(tabID: UUID, toolbar: AnyView) {
self.tabID = tabID
toolbarHost = NSHostingView(rootView: toolbar)
diff --git a/Sources/Cra/UI/Windows/EmbeddedPages.swift b/Sources/Cra/UI/Windows/EmbeddedPages.swift
index e74c8d8..4502027 100644
--- a/Sources/Cra/UI/Windows/EmbeddedPages.swift
+++ b/Sources/Cra/UI/Windows/EmbeddedPages.swift
@@ -11,10 +11,13 @@ import ObjectiveC
/// 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.
+/// On by default. Off with `defaults write dk.kildahl.cra embedPages -bool NO` or
+/// CRA_EMBED_PAGES=0 (pages then stay in their own child windows, as before 0.1.17).
enum EmbeddedPages {
- static let isEnabled = ProcessInfo.processInfo.environment["CRA_EMBED_PAGES"] == "1"
- || UserDefaults.standard.bool(forKey: "embedPages")
+ static let isEnabled: Bool = {
+ if let env = ProcessInfo.processInfo.environment["CRA_EMBED_PAGES"] { return env != "0" }
+ return UserDefaults.standard.object(forKey: "embedPages") as? Bool ?? true
+ }()
/// 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).
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index 37344d5..04e0e1f 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -652,7 +652,12 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
var panels: [NSPanel?] = [overlayPanel]
if !overlay.toasts.isEmpty { panels.append(toastPanel) }
if overlay.findVisible { panels.append(findPanel) }
- for case let panel? in panels {
+ let wanted = panels.compactMap { $0 }
+ // Already the last children, in order, and showing: re-adding each one rebuilt the
+ // window's ordering group, a window server round trip, on every tab switch.
+ let children = window.childWindows ?? []
+ if children.suffix(wanted.count).elementsEqual(wanted, by: ===), wanted.allSatisfy(\.isVisible) { return }
+ for panel in wanted {
window.removeChildWindow(panel)
window.addChildWindow(panel, ordered: .above)
panel.orderFront(nil)
@@ -715,7 +720,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
positionPageWindows(lastPaneFrames)
w.contentView?.isHidden = false
embedPage(id, from: w)
- w.orderFront(nil)
+ // Ordering a window that is already showing is a window server round trip too.
+ if !w.isVisible { w.orderFront(nil) }
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
@@ -1403,6 +1409,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
return event
}
self.swipeAxis = .horizontal
+ HitchMonitor.mark("swipe-begin")
self.beginSpaceSwipe()
self.trackSpaceSwipe(by: self.swipeX, at: event.timestamp)
return nil
@@ -1450,6 +1457,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
}
private func endSpaceSwipe() {
+ HitchMonitor.mark("swipe-lift")
let width = max(1, shell.sidebarWidth)
let pages = sidebarUI.spaceSwipe
let span = (swipeSamples.last?.time ?? 0) - (swipeSamples.first?.time ?? 0)
@@ -1462,9 +1470,22 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
if !(0..<store.spaceOrder.count).contains(index + step) { step = 0 }
let remaining = CGFloat(step) - pages
sidebarUI.spaceSettleVelocity = abs(remaining) > 0.001 ? Double(max(-4, min(12, velocity / remaining))) : 0
- withAnimation(sidebarUI.spaceSettleAnimation) {
+ // The new space becomes the strip's page at once, with the swipe re-based so nothing moves,
+ // and only the swipe springs home. It moves the strip as a render effect; animating the
+ // page change moved every row's layout on every frame of the settle.
+ let generation = sidebarUI.beginSpaceSettle()
+ if step != 0 {
+ var instant = Transaction()
+ instant.disablesAnimations = true
+ withTransaction(instant) {
+ sidebarUI.spaceSwipe = pages - CGFloat(step)
+ store.focusSpace(store.spaceOrder[index + step], window: windowID)
+ }
+ }
+ withAnimation(sidebarUI.spaceSettleAnimation, completionCriteria: .logicallyComplete) {
sidebarUI.spaceSwipe = 0
- if step != 0 { store.focusSpace(store.spaceOrder[index + step], window: windowID) }
+ } completion: { [weak self] in
+ self?.sidebarUI.endSpaceSettle(generation)
}
// Clicks and shortcuts that switch spaces later start from rest.
DispatchQueue.main.async { [weak self] in self?.sidebarUI.spaceSettleVelocity = 0 }
@@ -1662,7 +1683,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
positionCommandPanel()
if commandPanel.parent == nil { window.addChildWindow(commandPanel, ordered: .above) }
commandBarOpenedAt = Date()
- NSApp.activate(ignoringOtherApps: true)
+ if !HitchMonitor.background { NSApp.activate(ignoringOtherApps: true) }
// Key immediately (typing never waits); CommandBarView fades itself in.
commandPanel.makeKeyAndOrderFront(nil)
observeCommandBar()
diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mm
index cd552de..3b65944 100644
--- a/Sources/CraCEF/CraCEF.mm
+++ b/Sources/CraCEF/CraCEF.mm
@@ -2098,6 +2098,15 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {
- (BOOL)isHandlingSendEvent { return _handlingSendEvent; }
- (void)setHandlingSendEvent:(BOOL)handlingSendEvent { _handlingSendEvent = handlingSendEvent; }
+// A Chromium page view, wherever it lives: in its own window, or embedded in a Cra
+// window's pane (EmbeddedPages.swift), where sendEvent's other two checks miss it.
+static BOOL CraIsInPageView(NSView* v) {
+ for (NSView* p = v; p; p = p.superview) {
+ if ([NSStringFromClass([p class]) isEqualToString:@"WebContentsViewCocoa"]) return YES;
+ }
+ return NO;
+}
+
// Chrome's rule: when a web view has focus, ⌘-shortcuts go to the page
// first and only reach the menu bar if the page leaves them alone (so ⌘F in
// Google Docs or ⌘← in a text field keep working). Reserved shortcuts are
@@ -2118,7 +2127,7 @@ static void MarkProfileExitedCleanly(NSString* profileDir) {
if ([fr isKindOfClass:[NSView class]]) {
NSView* v = (NSView*)fr;
for (CraBrowser* b in [g_allBrowsers allObjects]) {
- if ([v isDescendantOf:b.containerView] || (b.hostWindow && key == b.hostWindow)) {
+ if ([v isDescendantOf:b.containerView] || (b.hostWindow && key == b.hostWindow) || CraIsInPageView(v)) {
if (!_forwardedKeyEvents) _forwardedKeyEvents = [NSHashTable weakObjectsHashTable];
[_forwardedKeyEvents addObject:event];
[key sendEvent:event];
diff --git a/docs/development.md b/docs/development.md
index 0942a82..b236108 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -54,10 +54,11 @@ To measure smoothness, add `CRA_HITCH_LOG=/tmp/cra-hitch.log`: every main-thread
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.
+Pages are embedded in their pane cards (`EmbeddedPages.swift`): Chromium's page views move
+from their Chrome window into the card, like Arc and Dia, and the Chrome window stays behind
+empty, click-through and never key. Pages go back into their window while DevTools is open.
+`CRA_EMBED_PAGES=0` (or `defaults write dk.kildahl.cra embedPages -bool NO`) keeps pages in
+their own child windows, the hosting before 0.1.17, for comparing the two.
## Scripting hooks