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.

Command bar follows the space's theme, open dark folders hide the back panel, PiP throws into corners, a split of a pinned video tab sleeps it

Victor5c1ae540619a
diff --git a/Packages/CraCore/Sources/CraCore/PictureInPictureThrow.swift b/Packages/CraCore/Sources/CraCore/PictureInPictureThrow.swift
new file mode 100644
index 0000000..ee8d7b5
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/PictureInPictureThrow.swift
@@ -0,0 +1,125 @@
+import CoreGraphics
+import Foundation
+
+/// A two-finger swipe on the Picture in Picture window (Arc: the window follows the fingers and
+/// is thrown into a corner of the screen when they lift). Arc keeps the window either at a frame
+/// the user dragged it to (`absolute`) or in one of the screen's four corners (`screen`), which is
+/// where a swipe leaves it. Points, frames and velocities are AppKit screen coordinates: origin at
+/// the bottom left, y going up.
+public struct PictureInPictureThrow: Sendable {
+ public enum Corner: String, Sendable, Equatable, CaseIterable {
+ case topLeft, topRight, bottomLeft, bottomRight
+ }
+
+ /// How far back the fingers' last moves count toward the throw's speed.
+ public static let sampleWindow: Double = 0.08
+ /// How far a throw carries per point/s of speed: UIKit's normal deceleration (0.998 a
+ /// millisecond) comes to rest after v · 0.998 / (1 − 0.998) / 1000 = v · 0.499 s.
+ public static let projection: CGFloat = 0.998 / (1 - 0.998) / 1000
+
+ public private(set) var frame: CGRect
+ /// False while the fingers only rest on the window: lifting them then throws nothing.
+ public private(set) var hasMoved = false
+ private let start: Double
+ private var samples: [(time: Double, dx: CGFloat, dy: CGFloat)] = []
+
+ /// The fingers touched down on a window at `frame` at `time` (seconds, any clock).
+ public init(frame: CGRect, at time: Double) {
+ self.frame = frame
+ start = time
+ }
+
+ /// The fingers moved the window by `dx, dy` at `time`; returns where it is now.
+ public mutating func move(dx: CGFloat, dy: CGFloat, at time: Double) -> CGRect {
+ frame = frame.offsetBy(dx: dx, dy: dy)
+ if dx != 0 || dy != 0 { hasMoved = true }
+ samples.append((time, dx, dy))
+ samples.removeAll { $0.time < time - 2 * Self.sampleWindow }
+ return frame
+ }
+
+ /// The window's speed when the fingers lift at `time`: how far it went in the moves of the
+ /// last `sampleWindow`, over the time since the move before them. Fingers that rested before
+ /// lifting throw nothing.
+ public func velocity(at time: Double) -> CGVector {
+ guard let first = samples.firstIndex(where: { $0.time >= time - Self.sampleWindow }) else { return .zero }
+ let recent = samples[first...]
+ let since = first > 0 ? samples[first - 1].time : start
+ let span = max(1.0 / 240, time - since)
+ return CGVector(dx: recent.reduce(0) { $0 + $1.dx } / span, dy: recent.reduce(0) { $0 + $1.dy } / span)
+ }
+
+ /// Where the window's centre would come to rest if it slid on with `velocity`.
+ public static func restingCentre(of frame: CGRect, velocity: CGVector) -> CGPoint {
+ CGPoint(x: frame.midX + velocity.dx * projection, y: frame.midY + velocity.dy * projection)
+ }
+
+ /// The corner of `visible` (a screen's visible frame) nearest to where the window would
+ /// come to rest.
+ public static func corner(for frame: CGRect, velocity: CGVector, in visible: CGRect) -> Corner {
+ let c = restingCentre(of: frame, velocity: velocity)
+ switch (c.x < visible.midX, c.y < visible.midY) {
+ case (true, false): return .topLeft
+ case (false, false): return .topRight
+ case (true, true): return .bottomLeft
+ case (false, true): return .bottomRight
+ }
+ }
+
+ /// A window of `size` in `corner` of `visible`, `margin` in from both edges (Arc: 10 pt,
+ /// the same as its first placement in the top right).
+ public static func frame(in corner: Corner, size: CGSize, visible: CGRect, margin: CGFloat) -> CGRect {
+ let left = corner == .topLeft || corner == .bottomLeft
+ let top = corner == .topLeft || corner == .topRight
+ let x = left ? visible.minX + margin : visible.maxX - margin - size.width
+ let y = top ? visible.maxY - margin - size.height : visible.minY + margin
+ return CGRect(x: x.rounded(), y: y.rounded(), width: size.width, height: size.height)
+ }
+}
+
+/// The window's flight into its corner: a critically damped spring on its origin that starts
+/// at the fingers' speed, so the throw carries on without a jolt and lands without bouncing off
+/// the screen's edge.
+public struct PictureInPictureFlight: Sendable {
+ /// Seconds the spring takes to swing once if undamped (SwiftUI's `response`).
+ public static let response: Double = 0.4
+ public static let dampingRatio: Double = 1
+
+ public private(set) var position: CGPoint
+ public private(set) var velocity: CGVector
+ public let target: CGPoint
+
+ public init(from position: CGPoint, velocity: CGVector, to target: CGPoint) {
+ self.position = position
+ self.velocity = velocity
+ self.target = target
+ }
+
+ /// Within half a point of the corner and slower than 10 pt/s.
+ public var isSettled: Bool {
+ abs(position.x - target.x) < 0.5 && abs(position.y - target.y) < 0.5 && hypot(velocity.dx, velocity.dy) < 10
+ }
+
+ /// Advances by `dt` seconds (sub-stepped, so a dropped frame doesn't overshoot) and returns
+ /// the new origin, the target itself once settled.
+ public mutating func step(_ dt: Double) -> CGPoint {
+ let stiffness = pow(2 * .pi / Self.response, 2)
+ let damping = 4 * .pi * Self.dampingRatio / Self.response
+ var left = max(0, min(dt, 0.1))
+ while left > 0 {
+ let h = min(left, 1.0 / 240)
+ left -= h
+ let ax = -stiffness * (position.x - target.x) - damping * velocity.dx
+ let ay = -stiffness * (position.y - target.y) - damping * velocity.dy
+ velocity.dx += ax * h
+ velocity.dy += ay * h
+ position.x += velocity.dx * h
+ position.y += velocity.dy * h
+ }
+ if isSettled {
+ position = target
+ velocity = .zero
+ }
+ return position
+ }
+}
diff --git a/Packages/CraCore/Sources/CraCore/TabSleepPolicy.swift b/Packages/CraCore/Sources/CraCore/TabSleepPolicy.swift
index 2b0470b..aca481c 100644
--- a/Packages/CraCore/Sources/CraCore/TabSleepPolicy.swift
+++ b/Packages/CraCore/Sources/CraCore/TabSleepPolicy.swift
@@ -5,7 +5,7 @@ import Foundation
/// change the time, turn the clock off, or close pages while macOS reports memory pressure
/// (GitHub #153). The probes in BrowserManager still decide whether a candidate may close.
public struct TabSleepPolicy: Equatable, Sendable {
- public enum Reason: String, Sendable { case timer, memoryPressure }
+ public enum Reason: String, Sendable { case timer, memoryPressure, splitCopy }
/// A page this long out of sight, and silent as long, is a candidate.
public var hiddenFor: TimeInterval
@@ -36,6 +36,9 @@ public struct TabSleepPolicy: Equatable, Sendable {
/// none left in the last 5 minutes, so a tab just left (or just woken) isn't closed again.
public static let memoryPressure = TabSleepPolicy(hiddenFor: 5 * 60, keepsRecentTabs: false, limit: 3, reason: .memoryPressure)
+ /// A pinned tab that a split pane copied (Arc): its page sleeps at once, the copy shows it.
+ public static let splitCopy = TabSleepPolicy(hiddenFor: 0, keepsRecentTabs: false, limit: 1, reason: .splitCopy)
+
/// macOS reports a level for a while after pages close, so a sweep waits this long for the
/// last one to tell before taking more.
public static let pressureSweepInterval: TimeInterval = 90
diff --git a/Packages/CraCore/Tests/CraCoreTests/PictureInPictureThrowTests.swift b/Packages/CraCore/Tests/CraCoreTests/PictureInPictureThrowTests.swift
new file mode 100644
index 0000000..db44ce9
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/PictureInPictureThrowTests.swift
@@ -0,0 +1,87 @@
+import CoreGraphics
+import CraCore
+import Testing
+
+/// A two-finger swipe throws the Picture in Picture window into a corner (Arc, reported on X 4 Nov).
+struct PictureInPictureThrowTests {
+ /// A 1728 × 1084 visible frame (Arc's measurement display) and Arc's 782 × 440 window in the top right.
+ private let visible = CGRect(x: 0, y: 0, width: 1728, height: 1084)
+ private let window = CGRect(x: 936, y: 634, width: 782, height: 440)
+
+ /// 120 Hz moves of `dx, dy` each for `count` frames, the fingers lifting on the last.
+ private func swipe(_ dx: CGFloat, _ dy: CGFloat, frames count: Int) -> (PictureInPictureThrow, Double) {
+ var s = PictureInPictureThrow(frame: window, at: 0)
+ var t = 0.0
+ for _ in 0..<count {
+ t += 1.0 / 120
+ _ = s.move(dx: dx, dy: dy, at: t)
+ }
+ return (s, t)
+ }
+
+ @Test func theWindowFollowsTheFingers() {
+ let (s, _) = swipe(-4, 2, frames: 10)
+ #expect(s.frame == window.offsetBy(dx: -40, dy: 20))
+ }
+
+ @Test func speedComesFromTheLastMoves() {
+ let (s, t) = swipe(-10, 0, frames: 30)
+ let v = s.velocity(at: t)
+ #expect(abs(v.dx + 1200) < 1)
+ #expect(v.dy == 0)
+ // Fingers that rest before lifting throw nothing.
+ #expect(s.velocity(at: t + 0.2) == .zero)
+ }
+
+ /// A short flick from the top right toward the left lands top left; resting in place keeps
+ /// the nearest corner.
+ @Test func aFlickPicksTheCornerItCarriesTo() {
+ let (s, t) = swipe(-12, 0, frames: 6)
+ let v = s.velocity(at: t)
+ #expect(s.frame.midX > visible.midX)
+ #expect(PictureInPictureThrow.corner(for: s.frame, velocity: v, in: visible) == .topLeft)
+ #expect(PictureInPictureThrow.corner(for: s.frame, velocity: .zero, in: visible) == .topRight)
+ let down = PictureInPictureThrow.corner(for: window, velocity: CGVector(dx: 0, dy: -2000), in: visible)
+ #expect(down == .bottomRight)
+ let diagonal = PictureInPictureThrow.corner(for: window, velocity: CGVector(dx: -3000, dy: -2000), in: visible)
+ #expect(diagonal == .bottomLeft)
+ }
+
+ @Test func cornersKeepArcsMargin() {
+ let size = window.size
+ let f = { (c: PictureInPictureThrow.Corner) in PictureInPictureThrow.frame(in: c, size: size, visible: visible, margin: 10) }
+ #expect(f(.topRight) == CGRect(x: 936, y: 634, width: 782, height: 440))
+ #expect(f(.topLeft).origin == CGPoint(x: 10, y: 634))
+ #expect(f(.bottomLeft).origin == CGPoint(x: 10, y: 10))
+ #expect(f(.bottomRight).origin == CGPoint(x: 936, y: 10))
+ // A second screen to the left of the main one.
+ let left = CGRect(x: -1440, y: 100, width: 1440, height: 875)
+ #expect(PictureInPictureThrow.frame(in: .bottomLeft, size: size, visible: left, margin: 10).origin == CGPoint(x: -1430, y: 110))
+ }
+
+ /// The flight starts at the fingers' speed and comes to rest exactly in the corner within a second.
+ @Test func theFlightLandsInTheCorner() {
+ var f = PictureInPictureFlight(from: CGPoint(x: 700, y: 634), velocity: CGVector(dx: -1500, dy: 0), to: CGPoint(x: 10, y: 634))
+ var p = f.position
+ var t = 0.0
+ var furthestLeft = p.x
+ while !f.isSettled && t < 2 {
+ p = f.step(1.0 / 120)
+ furthestLeft = min(furthestLeft, p.x)
+ t += 1.0 / 120
+ }
+ #expect(f.isSettled)
+ #expect(p == CGPoint(x: 10, y: 634))
+ #expect(t < 1)
+ // At most a few points past the corner, never off the screen.
+ #expect(furthestLeft > 0)
+ }
+
+ /// A long stall (the Mac busy for a quarter of a second) doesn't fling the window away.
+ @Test func aDroppedFrameStaysStable() {
+ var f = PictureInPictureFlight(from: CGPoint(x: 900, y: 600), velocity: .zero, to: CGPoint(x: 10, y: 10))
+ let p = f.step(0.25)
+ #expect(p.x >= 10 && p.x <= 900)
+ #expect(p.y >= 10 && p.y <= 600)
+ }
+}
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index efd6cc7..746d509 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -228,8 +228,12 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
let started = Perf.now()
let newSet = Set(tabIDs)
for previous in visibleTabIDs where !newSet.contains(previous) {
- leaveTab(previous)
runtimes[previous]?.hiddenAt = clock.now
+ if tabIDs.contains(where: { !visibleTabIDs.contains($0) && isSplitCopy($0, of: previous) }) {
+ hibernate(previous)
+ } else {
+ leaveTab(previous)
+ }
}
let wasVisible = Set(visibleTabIDs)
var shown: [UUID] = []
@@ -450,11 +454,13 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
let reply = error == nil ? Self.jsonObject(result) : nil
let discarded = reply?["discarded"] as? Bool == true
// Chromium keeps a page whose navigation was about to commit; ask again later.
- if error == nil, !discarded { return self.keepAwake(rt, url, "navigating") }
+ // A split's copy can't wait: the hidden page would play on. It closes instead.
+ if error == nil, !discarded, policy.reason != .splitCopy { return self.keepAwake(rt, url, "navigating") }
self.sleptTabs.insert(id)
Perf.count(.tabSlept, policy.reason.rawValue)
if !rt.browser.isIncognito {
- let why = policy.reason == .memoryPressure ? ", the Mac is short of memory" : ""
+ let why = policy.reason == .memoryPressure ? ", the Mac is short of memory"
+ : policy.reason == .splitCopy ? ", a split shows its copy" : ""
let how = !discarded ? "unloads" : reply?["processEnded"] as? Bool == true ? "discards (its renderer ended)" : "discards"
CraLog.note("tab sleep \(how) \(CraLog.host(url)) (hidden \(Int(self.clock.now.timeIntervalSince(rt.hiddenAt ?? self.clock.now) / 60)) min\(why))")
}
@@ -664,6 +670,23 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
requestPictureInPicture(tabID, automatic: true)
}
+ /// A split pane that stands in for a pinned tab: the Today copy `createSplit` and
+ /// `addToSplit` make of a pinned or favorite tab, which loads the page anew.
+ private func isSplitCopy(_ paneID: UUID, of tabID: UUID) -> Bool {
+ guard let split = store.splitContaining(paneID), !split.children.contains(tabID) else { return false }
+ return store.paneID(for: tabID, in: split) == paneID
+ }
+
+ /// A pinned tab whose page the split's copy now shows (⌥Return in the command bar on a pinned
+ /// YouTube tab): Arc puts the pinned tab to sleep rather than opening its video in Picture in
+ /// Picture, so one video plays, in the split (reported on X, 4 Nov). The page is discarded in
+ /// place like any sleeping tab, and loads again when the pinned tab is selected.
+ private func hibernate(_ tabID: UUID) {
+ guard let rt = runtimes[tabID], !rt.browser.isInPictureInPicture else { return }
+ log(tabID, "sleeps: its split copy shows the page")
+ discard(tabID, rt, rt.browser.currentURL, .splitCopy)
+ }
+
/// The window is out of sight: covered by another app, on another desktop or in the Dock.
private(set) var windowCovered = false
@@ -712,6 +735,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
if let np = nowPlaying, np.pictureInPicture.contains(id) != active {
if active { np.pictureInPicture.insert(id) } else { np.pictureInPicture.remove(id) }
}
+ log(id, active ? "enters Picture in Picture" : "leaves Picture in Picture")
if active {
// The floating window's hover controls act on this tab.
PictureInPictureChrome.shared.actions = PictureInPictureActions(
diff --git a/Sources/Cra/UI/CommandBar/CommandBarView.swift b/Sources/Cra/UI/CommandBar/CommandBarView.swift
index 97bbc3c..d9c09f6 100644
--- a/Sources/Cra/UI/CommandBar/CommandBarView.swift
+++ b/Sources/Cra/UI/CommandBar/CommandBarView.swift
@@ -97,7 +97,13 @@ final class CommandBarView: NSView {
}
}
+ /// Colours turned into CGColors resolve against the current drawing appearance, which is the
+ /// app's (macOS') unless set: a light bar on a dark Mac got white fills and hints.
private func apply() {
+ effectiveAppearance.performAsCurrentDrawingAppearance { applyResolved() }
+ }
+
+ private func applyResolved() {
let c = controller
let items = c.result.items
let dark = self.dark
diff --git a/Sources/Cra/UI/PictureInPicture/PictureInPictureChrome.swift b/Sources/Cra/UI/PictureInPicture/PictureInPictureChrome.swift
index 113385b..cfb812c 100644
--- a/Sources/Cra/UI/PictureInPicture/PictureInPictureChrome.swift
+++ b/Sources/Cra/UI/PictureInPicture/PictureInPictureChrome.swift
@@ -209,7 +209,12 @@ final class PictureInPictureOverlayView: NSView {
BackgroundCursor.allow(false)
}
override func viewWillMove(toWindow newWindow: NSWindow?) {
- if newWindow == nil { BackgroundCursor.allow(false) }
+ if newWindow == nil {
+ BackgroundCursor.allow(false)
+ flightLink?.invalidate()
+ flightLink = nil
+ flight = nil
+ }
}
/// The resize cursor for an edge or corner; AppKit has diagonal ones from macOS 15.
@@ -235,6 +240,7 @@ final class PictureInPictureOverlayView: NSView {
CraLog.note("pip: overlay has no parent window")
return
}
+ land()
gesture = PictureInPictureGesture(mouse: Self.screenLocation(of: event), frame: target.frame)
}
@@ -302,7 +308,78 @@ final class PictureInPictureOverlayView: NSView {
}
override func rightMouseDown(with event: NSEvent) {}
override func otherMouseDown(with event: NSEvent) {}
- override func scrollWheel(with event: NSEvent) {}
+
+ // MARK: Swipe to a corner (Arc)
+
+ private var swipe: PictureInPictureThrow?
+ private var flight: PictureInPictureFlight?
+ private var flightLink: CADisplayLink?
+ private var flightTime: CFTimeInterval = 0
+
+ /// Two fingers on the trackpad (or a Magic Mouse) move the window with them, and when they
+ /// lift it flies on into the corner of the screen it was heading for, as Arc's does. A wheel
+ /// without phases (a plain mouse) moves nothing, and AppKit's own momentum after the lift is
+ /// left out: the flight is the momentum.
+ override func scrollWheel(with event: NSEvent) {
+ guard gesture == nil, let target, event.hasPreciseScrollingDeltas, event.momentumPhase.isEmpty else { return }
+ let t = event.timestamp
+ switch event.phase {
+ case .mayBegin, .began:
+ land()
+ swipe = PictureInPictureThrow(frame: target.frame, at: t)
+ case .changed:
+ if swipe == nil {
+ land()
+ swipe = PictureInPictureThrow(frame: target.frame, at: t)
+ }
+ // The window goes where the fingers go: with natural scrolling the deltas already
+ // follow them, without it they're the other way round.
+ let toFingers: CGFloat = event.isDirectionInvertedFromDevice ? 1 : -1
+ guard let frame = swipe?.move(dx: toFingers * event.scrollingDeltaX, dy: -toFingers * event.scrollingDeltaY, at: t) else { return }
+ target.setFrameOrigin(frame.origin)
+ case .ended, .cancelled:
+ guard let s = swipe else { return }
+ swipe = nil
+ guard s.hasMoved else { return }
+ throwWindow(target, from: s.frame, velocity: event.phase == .ended ? s.velocity(at: t) : .zero)
+ default:
+ break
+ }
+ }
+
+ private func throwWindow(_ target: NSWindow, from frame: NSRect, velocity: CGVector) {
+ let rest = PictureInPictureThrow.restingCentre(of: frame, velocity: velocity)
+ let screen = NSScreen.screens.first { $0.frame.contains(rest) } ?? target.screen ?? NSScreen.main
+ guard let visible = screen?.visibleFrame else { return }
+ let corner = PictureInPictureThrow.corner(for: frame, velocity: velocity, in: visible)
+ let end = PictureInPictureThrow.frame(in: corner, size: frame.size, visible: visible, margin: PictureInPictureChrome.edgeMargin)
+ CraLog.note("pip: swipe to \(corner.rawValue) at \(Int(hypot(velocity.dx, velocity.dy))) pt/s")
+ flight = PictureInPictureFlight(from: frame.origin, velocity: velocity, to: end.origin)
+ flightLink?.invalidate()
+ let link = displayLink(target: self, selector: #selector(flightStep(_:)))
+ link.add(to: .main, forMode: .common)
+ flightLink = link
+ flightTime = 0
+ }
+
+ @objc private func flightStep(_ link: CADisplayLink) {
+ guard let target, var f = flight else { return land() }
+ let dt = flightTime == 0 ? link.targetTimestamp - link.timestamp : link.timestamp - flightTime
+ flightTime = link.timestamp
+ target.setFrameOrigin(f.step(max(dt, 1.0 / 240)))
+ flight = f
+ if f.isSettled { land() }
+ }
+
+ /// Ends a flight where the window is (a new swipe or press catches it mid-air) and keeps the
+ /// spot for the next video.
+ private func land() {
+ guard let link = flightLink else { return }
+ link.invalidate()
+ flightLink = nil
+ flight = nil
+ if let target { PictureInPictureChrome.shared.remember(target.frame) }
+ }
}
/// Lets Cra set the cursor while another app is in front. macOS only takes the frontmost app's
diff --git a/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift b/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift
index f5f3b20..c7df875 100644
--- a/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift
+++ b/Sources/Cra/UI/Sidebar/List/SidebarRowViews.swift
@@ -407,6 +407,13 @@ final class FolderGlyphView: NSView {
private let frontPanel = CAShapeLayer()
private let frontShade = CAGradientLayer()
private let frontShadeMask = CAShapeLayer()
+ /// The back panel shows only outside the front one. Light themes fill both opaquely, so the
+ /// front hides the back's outline anyway; dark themes fill them with translucent white, and
+ /// without this the open folder showed the back's edges through the front (reported on X,
+ /// 4 Nov). The mask is the front panel's shape cut out of a larger square, turned with the
+ /// front's own transform so it moves with it.
+ private let backHolder = CALayer()
+ private let frontHole = CAShapeLayer()
private let mark = NSImageView()
/// Arc's peeked folder (FolderPeek): three 2 pt dots on a 4 pt pitch in the closed body.
private let dots = CAShapeLayer()
@@ -427,11 +434,16 @@ final class FolderGlyphView: NSView {
back.addSublayer(backShade)
front.addSublayer(frontPanel)
front.addSublayer(frontShade)
- for l in [back, front] as [CALayer] {
+ for l in [back, front, frontHole] as [CALayer] {
// Hinged on the bottom-left corner.
l.anchorPoint = CGPoint(x: 0, y: 1)
- icon.addSublayer(l)
}
+ frontHole.fillRule = .evenOdd
+ frontHole.fillColor = NSColor.black.cgColor
+ backHolder.addSublayer(back)
+ backHolder.mask = frontHole
+ icon.addSublayer(backHolder)
+ icon.addSublayer(front)
layer?.addSublayer(icon)
layer?.addSublayer(dots)
mark.image = GitHubMark.image
@@ -474,6 +486,7 @@ final class FolderGlyphView: NSView {
t = CATransform3DRotate(t, open ? 32 * .pi / 180 : 0, 0, 1, 0)
back.transform = CATransform3DRotate(t, open ? 28 * .pi / 180 : 0, 1, 0, 0)
front.transform = CATransform3DRotate(t, open ? -30 * .pi / 180 : 0, 1, 0, 0)
+ frontHole.transform = front.transform
frontShade.opacity = open ? 1 : 0
backShade.opacity = open ? 1 : 0.2
CATransaction.commit()
@@ -528,6 +541,15 @@ final class FolderGlyphView: NSView {
frontShade.frame = front.bounds
frontShadeMask.frame = front.bounds
frontShadeMask.path = panel
+ // In the holder's space (the icon's), everything but the front panel; the margin keeps the
+ // turned square over the whole glyph.
+ backHolder.frame = CGRect(x: 0, y: 0, width: w, height: h)
+ frontHole.bounds = front.bounds
+ frontHole.position = front.position
+ let hole = CGMutablePath()
+ hole.addRect(front.bounds.insetBy(dx: -w, dy: -h))
+ hole.addPath(panel)
+ frontHole.path = hole
// In the front panel, on whole points so each dot is two pixels square at 1x.
dots.frame = bounds
let dotPath = CGMutablePath()
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index 5b70a45..796f1b6 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -350,6 +350,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
shell.placeholderHost.layer?.backgroundColor = (palette.isDark ? NSColor.white.withAlphaComponent(0.04) : NSColor.black.withAlphaComponent(0.03)).cgColor
shell.isDarkTheme = palette.isDark
window?.appearance = NSAppearance(named: palette.isDark ? .darkAqua : .aqua)
+ commandPanel?.appearance = window?.appearance
// Vibrant themes see through to the desktop like Arc; others are opaque.
shell.vibrancy.isHidden = !palette.vibrant
shell.vibrancyLift.isHidden = !palette.vibrant
@@ -2323,7 +2324,9 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
// Always centred in the window, also when opened from the toolbar.
commandBar.attached = false
commandBar.panelWidth = min(CraMetrics.commandBarWidth, window.frame.width - 80)
- commandPanel.appearance = nil
+ // Light or dark with the space's theme, as the window is: a child panel would otherwise
+ // follow macOS, a dark bar over a light space while the Mac runs dark (reported on X).
+ commandPanel.appearance = window.appearance
positionCommandPanel()
if commandPanel.parent == nil { window.addChildWindow(commandPanel, ordered: .above) }
commandBarOpenedAt = Date()
diff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swift
index ae74657..553ea80 100644
--- a/Tests/BrowserManagerLifecycleTests.swift
+++ b/Tests/BrowserManagerLifecycleTests.swift
@@ -96,6 +96,7 @@ enum BrowserManagerLifecycleTests {
nowPlayingCase()
await nowPlayingPictureInPictureCase()
await leaveVideoTabPictureInPictureCase()
+ await splitCopySleepsPinnedTabCase()
await coveredWindowPictureInPictureCase()
pageColoursCase()
extensionPageRetryCase()
@@ -604,6 +605,43 @@ enum BrowserManagerLifecycleTests {
manager.closeAll()
}
+ /// ⌥Return in the command bar (or Add Split View) on a pinned video tab: the split shows a Today
+ /// copy of the page, and the pinned tab goes to sleep instead of opening its video in Picture in
+ /// Picture, so one video plays (Arc; X report, 4 Nov 2026). A plain tab switch still opens it.
+ @MainActor
+ private static func splitCopySleepsPinnedTabCase() async {
+ let store = SidebarStore()
+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())
+ store.settings.autoPictureInPicture = true
+ let pinned = store.createTab(url: "https://example.test/video").id
+ let rp = manager.ensureRuntime(for: pinned)!
+ manager.show(pinned, focus: false)
+ var split = TestItem(id: UUID(), tab: nil, isSplit: true)
+ var copy = store.createTab(url: "https://example.test/video")
+ copy.tab?.activeTabBeforeCreationID = pinned
+ copy.parentID = split.id
+ store.items[copy.id] = copy
+ let empty = store.createTab(url: "").id
+ store.items[empty]?.parentID = split.id
+ split.children = [copy.id, empty]
+ store.items[split.id] = split
+ manager.show([copy.id, empty], focused: empty, focus: false)
+ expect(!rp.browser.replies.contains { $0.method == "Runtime.evaluate" }, "the pinned tab's video doesn't open in Picture in Picture")
+ expect(rp.browser.replies.contains { $0.method == "Cra.discard" }, "the pinned tab the split copied goes to sleep")
+ rp.browser.reply(to: "Cra.discard", with: discardedReply)
+ await drainMainQueue()
+ expect(manager.sleptTabs.contains(pinned), "the pinned tab is asleep, its page loads again when selected")
+
+ // A video tab left for another tab (not its copy) still opens Picture in Picture.
+ let video = store.createTab(url: "https://example.test/video2").id
+ let rv = manager.ensureRuntime(for: video)!
+ manager.show(video, focus: false)
+ manager.show(copy.id, focus: false)
+ expect(rv.browser.replies.contains { $0.method == "Runtime.evaluate" }, "leaving another video tab still asks for Picture in Picture")
+ expect(!rv.browser.replies.contains { $0.method == "Cra.discard" }, "and doesn't put it to sleep")
+ manager.closeAll()
+ }
+
/// A window out of sight and not key (another app or desktop in front) leaves its video tab
/// like a tab switch, as Arc's presentPipForOccludedWindow does, and the video comes back when
/// the window is key again (X report, 1 Nov 2026). Silent pages aren't asked, and a Picture in
diff --git a/Tests/BrowserManagerSupport/AppServices.swift b/Tests/BrowserManagerSupport/AppServices.swift
index a565e18..1bf135f 100644
--- a/Tests/BrowserManagerSupport/AppServices.swift
+++ b/Tests/BrowserManagerSupport/AppServices.swift
@@ -3,13 +3,14 @@ import CraCEF
// Unrelated shell services required to typecheck the complete production manager.
// The tab store deliberately remains observable so stale callbacks can be asserted.
-struct TestTab { var url: String; var savedTitle = ""; var muted = false; var faviconKey: String?; var themeColor: String? }
+struct TestTab { var url: String; var savedTitle = ""; var muted = false; var faviconKey: String?; var themeColor: String?; var activeTabBeforeCreationID: UUID? }
struct TestItem {
let id: UUID
var tab: TestTab?
var parentID: UUID?
var children: [UUID] = []
var isEmptyTab = false
+ var isSplit = false
var isTab: Bool { tab != nil }
}
enum TestRoot { case today }
@@ -22,6 +23,14 @@ enum TestRoot { case today }
func profilePath(item: UUID) -> String? { nil }
func profileDirectoryName(item: UUID) -> String { "Default" }
func spaceID(ofItem: UUID) -> UUID? { nil }
+ func splitContaining(_ id: UUID) -> TestItem? {
+ guard let p = items[id]?.parentID, let parent = items[p], parent.isSplit else { return nil }
+ return parent
+ }
+ func paneID(for tabID: UUID, in split: TestItem) -> UUID? {
+ if split.children.contains(tabID) { return tabID }
+ return split.children.first { items[$0]?.tab?.activeTabBeforeCreationID == tabID }
+ }
func rootContainer(of: UUID) -> TestRoot? { nil }
func updateTab(_ id: UUID, url: String? = nil, title: String? = nil) {
if let url { items[id]?.tab?.url = url }
diff --git a/Tests/Fixtures/Pages/video.html b/Tests/Fixtures/Pages/video.html
new file mode 100644
index 0000000..054f15f
--- /dev/null
+++ b/Tests/Fixtures/Pages/video.html
@@ -0,0 +1,22 @@
+<!doctype html>
+<meta charset="utf-8">
+<title>Video fixture</title>
+<style>body { margin: 0; background: #111; } video { width: 640px; height: 360px; }</style>
+<!-- A playing video with no media file and no network: a canvas drawn 30 times a second, streamed
+ into the element. Muted so it starts on its own; a scenario unmutes it with a user gesture. -->
+<video id="v" muted autoplay playsinline></video>
+<script>
+ const c = Object.assign(document.createElement('canvas'), { width: 640, height: 360 });
+ const g = c.getContext('2d');
+ let n = 0;
+ setInterval(() => {
+ g.fillStyle = `hsl(${(n += 3) % 360} 60% 40%)`;
+ g.fillRect(0, 0, 640, 360);
+ g.fillStyle = '#fff';
+ g.font = '64px system-ui';
+ g.fillText(String(n / 3), 40, 100);
+ }, 33);
+ const v = document.getElementById('v');
+ v.srcObject = c.captureStream(30);
+ v.play();
+</script>
diff --git a/Tests/Scenarios/split-pinned-video.scenario b/Tests/Scenarios/split-pinned-video.scenario
new file mode 100644
index 0000000..e9be59f
--- /dev/null
+++ b/Tests/Scenarios/split-pinned-video.scenario
@@ -0,0 +1,16 @@
+# A pinned tab playing a video, then Add Split View (⌥Return in the command bar takes the same
+# path): the split shows a Today copy of the page and the pinned tab sleeps, as in Arc. Before
+# 4 Nov 2026 the pinned tab's video also opened in Picture in Picture, two videos at once
+# (reported on X).
+cra://open?url=file://${FIXTURES}/Pages/video.html
+expect-log loaded file:
+cra://action/pinTab
+wait 1
+# Auto Picture in Picture asks only for a playing video with sound.
+cra://debug?cdp=Runtime.evaluate&params={"expression":"(v=>(v.muted=false,v.volume=1,v.play().then(()=>'playing:'+v.videoWidth)))(document.querySelector('video'))","awaitPromise":true,"userGesture":true}
+expect-log Cra cdp Runtime.evaluate .*"value":"playing:640"
+cra://action/addSplitView
+expect-log sleeps: its split copy shows the page
+expect-log tab sleep discards.* file:
+wait 2
+reject-log enters Picture in Picture
diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.md
index 802d497..8567ad9 100644
--- a/docs/arc-reverse-engineering.md
+++ b/docs/arc-reverse-engineering.md
@@ -118,6 +118,9 @@ Legend: [O] observed in shipped artifact or data file, [I] inference, [U] unknow
~105 / ~175 ms in Cra). Colours come from outside (`ColorSpec`): on one
gold theme the back was #E9B300, the front #FCEDBC and every edge black at ~26%; how the back colour follows the
theme was not worked out, so Cra keeps its measured outline over cream. Cra: FolderGlyphView.
+ Dark themes fill both panels with translucent white, so the open back panel's edges showed through the
+ front (reported on X, 4 Nov); Cra masks the back with the front panel's shape (`frontHole`, turned with the
+ front's transform), which is what the opaque light-theme fill does anyway.
- [O] Sidebar glyphs (29 Oct, 1x and 2x captures, fitted pixel by pixel): the tab row's hover ✕ is two 2 pt
round-capped strokes 4.25 pt out from a centre on a whole point, white 0.6 over the hover fill; at 1x it is
perfectly symmetric (176/142/85), which no SF Symbol size reproduces (xmark 13.5 bold is closest at 2x but
@@ -161,6 +164,8 @@ Legend: [O] observed in shipped artifact or data file, [I] inference, [U] unknow
favicon; rows 50pt single-line "Title — url"; the completion row comes first, then the typed query, then matches; open
tabs show "Switch to Tab" + arrow box (other-space tabs show the space name); the selected row is tinted with the
space color. ⌘L with the toolbar visible edits inline: dropdown hangs under the toolbar across the content width.
+ Arc draws the bar inside the window, so it is light or dark with the space's theme; Cra's bar is a child panel,
+ which takes macOS' appearance unless given the window's (it was dark over light spaces on a dark Mac until 4 Nov).
## Dia 1.54 (company.thebrowser.dia)
- [O] ~/Library/Application Support/Dia/StorableProfileContainers.json: containers per profile with `window` or
@@ -668,6 +673,14 @@ already reached the overlay (it activates Cra and acceptsFirstMouse lets it thro
cursor it only looked dead. Drags are measured from each
event's own screen location; `cra.log` gets `pip: move`, `pip: resize <edge> from W×H`, `pip: resized
<edge> W×H → W×H` (with "asked" when Chromium kept another size) and `pip: overlay has no parent window`.
+Swiping (4 Nov, reported on X): Arc's PiP follows two fingers on the trackpad and is thrown into a screen corner;
+its placement enum is `screen(corner) | offscreen | absolute(rect)` with corners topLeft/topRight/bottomLeft/
+bottomRight next to spring presets firm/firmSlow/springy… (strings, Arc 1.171). [U] Its spring and how far a
+throw carries were not measured. Cra (`PictureInPictureThrow`, `PictureInPictureFlight` in CraCore): the window
+follows the scroll deltas (direction from `isDirectionInvertedFromDevice`), the speed of the last 80 ms projects
+the resting point with UIKit's 0.998/ms deceleration, the nearest corner of that screen's visible frame (10 pt
+in) is the target, and a critically damped spring (response 0.4 s) flies it there from the fingers' speed.
+AppKit's momentum events are ignored; a plain wheel moves nothing. `cra.log`: `pip: swipe to <corner> at N pt/s`.
One residual difference: Chrome paints its origin strip ("File on your device", top gradient)
inside the compositor layer for about two seconds when the window first appears (present at
1.5 s, gone at 2.5 s in quarter-second captures); it is drawn whether or not the window is
@@ -717,6 +730,10 @@ isolated test instance; composites in docs/screenshots/compare-*.png.
a Today split item showing "YouTube | Umami"; a second drop produced "YouTube | Umami | Umami" (copies, not
moves). While a new pane is still empty the sidebar shows it as a plain "New Tab" row in Today; the split
cell appears once the pane has a page.
+- [I] The pinned tab a split copied goes to sleep in Arc, so its video doesn't also open in Picture in Picture
+ (a user's report on X, 4 Nov, ⌥Return in the command bar on a pinned YouTube tab; not observed here). Cra discards
+ the pinned tab's page when its copy comes on screen (`BrowserManager.hibernate`, sleep reason `splitCopy`,
+ scenario split-pinned-video).
- [O] Sidebar split cell: one row, white rounded selected background, child segments (favicon + title) separated
by hairlines, ✕ per child on hover.
- Cra status (this session): item model, store operations, multi-pane shell with per-pane toolbars and page
diff --git a/scripts/scenario.sh b/scripts/scenario.sh
index 16cc21c..57a0862 100755
--- a/scripts/scenario.sh
+++ b/scripts/scenario.sh
@@ -23,6 +23,7 @@
# helpers baseline | helpers settle [slack]
# relaunch cra://debug?relaunch=1, then follow the new process
# expect-log <regex> a line Cra logged (cra.log or stdout)
+# reject-log <regex> no such line logged so far
# snapshot <View[,n]> <name> the nth visible view of that class drawn to PNG and compared with
# Tests/Snapshots/<name>.png (CRA_SNAPSHOT_RECORD=1 records it)
# fresh no seeded settings: onboarding shows, as on a new Mac
@@ -166,6 +167,9 @@ while IFS= read -r raw || [ -n "$raw" ]; do
shift; re="$*"; found=""
for _ in $(seq 1 150); do grep -Eq "$re" "$DATA"/cra*.log "$OUT/stdout.log" 2>/dev/null && { found=1; break; }; sleep 0.2; done
[ -n "$found" ] || problem "no log line matching: $re" ;;
+ reject-log)
+ shift; re="$*"
+ ! grep -Eq "$re" "$DATA"/cra*.log "$OUT/stdout.log" 2>/dev/null || problem "a log line matching: $re" ;;
snapshot)
shot="$OUT/snapshots/$3.png"; ref="$ROOT/Tests/Snapshots/$3.png"
mkdir -p "$OUT/snapshots"; send "cra://debug?snapshot=$2&out=$shot"