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.

Capture as in Arc: click an element or drag a region, then copy, save or send it

Victor628b2175f1b8
diff --git a/Packages/CraCore/Sources/CraCore/ContentCapture.swift b/Packages/CraCore/Sources/CraCore/ContentCapture.swift
new file mode 100644
index 0000000..f279195
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/ContentCapture.swift
@@ -0,0 +1,121 @@
+import CoreGraphics
+import Foundation
+
+/// Arc's Capture (⇧⌘2): the page dims and greys, the part about to be captured stays in colour,
+/// a click takes the element under the pointer and a drag takes a rectangle. These are the decisions
+/// behind it, in the overlay's coordinates: points, y down from the page's top-left corner, the way
+/// the page and its screenshot count.
+public enum ContentCapture {
+ /// A press that moves less than this is a click (Arc's NSPanGestureRecognizer threshold).
+ public static let dragThreshold: CGFloat = 4
+ /// A drag smaller than this either way captures nothing.
+ public static let minimumSize: CGFloat = 8
+
+ public static func isDrag(from start: CGPoint, to end: CGPoint) -> Bool {
+ hypot(end.x - start.x, end.y - start.y) >= dragThreshold
+ }
+
+ /// The rectangle a drag spans, kept inside the page.
+ public static func selection(from start: CGPoint, to end: CGPoint, in bounds: CGRect) -> CGRect {
+ let r = CGRect(x: min(start.x, end.x), y: min(start.y, end.y), width: abs(end.x - start.x), height: abs(end.y - start.y))
+ return r.intersection(bounds).isNull ? .zero : r.intersection(bounds)
+ }
+
+ /// Whether a selection is big enough to capture.
+ public static func isCapturable(_ rect: CGRect) -> Bool {
+ rect.width >= minimumSize && rect.height >= minimumSize
+ }
+
+ /// The pixels of a screenshot of the whole page (`imageSize` pixels for `pageSize` points) that
+ /// `rect` covers, on whole pixels and inside the image.
+ public static func pixelRect(for rect: CGRect, pageSize: CGSize, imageSize: CGSize) -> CGRect {
+ guard pageSize.width > 0, pageSize.height > 0 else { return .zero }
+ let sx = imageSize.width / pageSize.width, sy = imageSize.height / pageSize.height
+ let r = CGRect(x: rect.minX * sx, y: rect.minY * sy, width: rect.width * sx, height: rect.height * sy).integral
+ let clipped = r.intersection(CGRect(origin: .zero, size: imageSize))
+ return clipped.isNull ? .zero : clipped
+ }
+
+ /// The element the picker chose, in points inside the page, or nil when it found none (the page
+ /// then only takes drags, and Arc's hint says so). `result` is the picker's JSON: device pixels.
+ public static func elementRect(fromPicker result: [String: Any], scale: CGFloat, pageBounds: CGRect) -> CGRect? {
+ guard scale > 0, let x = number(result["x"]), let y = number(result["y"]),
+ let w = number(result["width"]), let h = number(result["height"]), w > 0, h > 0 else { return nil }
+ let r = CGRect(x: x / scale, y: y / scale, width: w / scale, height: h / scale).intersection(pageBounds)
+ return r.isNull || r.isEmpty ? nil : r
+ }
+
+ // MARK: The lens and the menu (Arc 1.171, offline Arc, 2x window captures, 4 Nov 2026)
+
+ /// An element shows in colour 2 pt beyond its edges (a dragged rectangle exactly)…
+ public static let elementClearance: CGFloat = 2
+ /// …inside a 4 pt ring (#161C2F), 4.5 pt corners inside and 8.5 pt outside.
+ public static let lensRing: CGFloat = 4
+ public static let lensInnerRadius: CGFloat = 4.5
+
+ /// What shows in colour for the element under the pointer.
+ public static func clearArea(element rect: CGRect) -> CGRect {
+ rect.insetBy(dx: -elementClearance, dy: -elementClearance)
+ }
+
+ /// The ring's outer edge around the part shown in colour.
+ public static func lensFrame(around clear: CGRect) -> CGRect {
+ clear.insetBy(dx: -lensRing, dy: -lensRing)
+ }
+
+ /// The menu after a capture: 4.5 pt right of the ring, its top level with the ring's. Where the
+ /// right has no room it goes left of the ring, and where neither side has, inside the page's
+ /// right edge over the capture. Always `margin` inside the page.
+ public static let menuGap: CGFloat = 4.5
+ public static let menuMargin: CGFloat = 8
+
+ public static func menuFrame(size: CGSize, besideLens lens: CGRect, in bounds: CGRect) -> CGRect {
+ var x = lens.maxX + menuGap
+ if x + size.width > bounds.maxX - menuMargin {
+ let left = lens.minX - menuGap - size.width
+ x = left >= bounds.minX + menuMargin ? left : bounds.maxX - menuMargin - size.width
+ }
+ let y = min(max(lens.minY, bounds.minY + menuMargin), bounds.maxY - menuMargin - size.height)
+ return CGRect(x: max(bounds.minX + menuMargin, x), y: max(bounds.minY + menuMargin, y), width: size.width, height: size.height)
+ }
+
+ private static func number(_ v: Any?) -> CGFloat? {
+ if let d = v as? Double { return CGFloat(d) }
+ if let n = v as? NSNumber { return CGFloat(truncating: n) }
+ return nil
+ }
+
+ /// Arc's click-to-capture picker (Arc 1.171, from the binary): of the elements under the
+ /// pointer, the best scored one. Images score up; small (under 100 px a side), full-width,
+ /// full-height, nearly-full-screen and inline elements score down; bigger ones score a little
+ /// higher. Nothing scoring 0 or more means there is nothing to click. Arc measures in the visual
+ /// viewport's units; Cra hands it device pixels and gets device pixels back, so page zoom and
+ /// pinch zoom both come out right. Runs in an isolated world: the page's own scripts can't see it.
+ public static func pickerScript(x: CGFloat, y: CGFloat) -> String {
+ """
+ (() => {
+ const vv = visualViewport, dpr = devicePixelRatio, k = vv.scale;
+ const px = \(Double(x)) / dpr / k + vv.offsetLeft, py = \(Double(y)) / dpr / k + vv.offsetTop;
+ const screenArea = innerWidth * innerHeight;
+ const score = el => {
+ const size = el.getBoundingClientRect();
+ const avgDim = (size.width + size.height) / 2, minDim = Math.min(size.width, size.height);
+ let s = 0;
+ if (minDim < 100) s -= 5;
+ if (size.width >= innerWidth) s -= 5;
+ if (size.height >= innerHeight) s -= 5;
+ if (size.width * size.height > screenArea * 0.7) s -= 5;
+ if (el.tagName === 'IMG' || el.tagName === 'PICTURE' || el.tagName === 'OBJECT') s += 5;
+ s += avgDim / 500;
+ if (getComputedStyle(el).display === 'inline') s -= 10;
+ return s;
+ };
+ const scored = document.elementsFromPoint(px, py).map(el => ({el, s: score(el)})).filter(p => p.s >= 0);
+ scored.sort((a, b) => b.s - a.s);
+ if (!scored.length) return null;
+ const r = scored[0].el.getBoundingClientRect();
+ return {x: (r.left - vv.offsetLeft) * k * dpr, y: (r.top - vv.offsetTop) * k * dpr, width: r.width * k * dpr, height: r.height * k * dpr};
+ })()
+ """
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/ContentCaptureTests.swift b/Packages/CraCore/Tests/CraCoreTests/ContentCaptureTests.swift
new file mode 100644
index 0000000..4714b49
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/ContentCaptureTests.swift
@@ -0,0 +1,99 @@
+import CoreGraphics
+import CraCore
+import Foundation
+import Testing
+
+struct ContentCaptureTests {
+ static let page = CGRect(x: 0, y: 0, width: 1000, height: 700)
+
+ @Test func smallMovesAreClicks() {
+ #expect(!ContentCapture.isDrag(from: .zero, to: CGPoint(x: 2, y: 3)))
+ #expect(ContentCapture.isDrag(from: .zero, to: CGPoint(x: 3, y: 3)))
+ #expect(ContentCapture.isDrag(from: CGPoint(x: 10, y: 10), to: CGPoint(x: 10, y: 4)))
+ }
+
+ @Test func selectionNormalisesAndStaysOnThePage() {
+ #expect(ContentCapture.selection(from: CGPoint(x: 300, y: 200), to: CGPoint(x: 100, y: 50), in: Self.page)
+ == CGRect(x: 100, y: 50, width: 200, height: 150))
+ // Dragged out past the page's bottom-right corner.
+ #expect(ContentCapture.selection(from: CGPoint(x: 900, y: 600), to: CGPoint(x: 1200, y: 900), in: Self.page)
+ == CGRect(x: 900, y: 600, width: 100, height: 100))
+ #expect(ContentCapture.selection(from: CGPoint(x: -50, y: -50), to: CGPoint(x: -10, y: -10), in: Self.page) == .zero)
+ }
+
+ @Test func tinySelectionsCaptureNothing() {
+ #expect(!ContentCapture.isCapturable(CGRect(x: 0, y: 0, width: 200, height: 7)))
+ #expect(!ContentCapture.isCapturable(.zero))
+ #expect(ContentCapture.isCapturable(CGRect(x: 0, y: 0, width: 8, height: 8)))
+ }
+
+ @Test func pixelRectScalesToTheScreenshot() {
+ let px = ContentCapture.pixelRect(for: CGRect(x: 10.25, y: 20, width: 100, height: 50.5),
+ pageSize: Self.page.size, imageSize: CGSize(width: 2000, height: 1400))
+ #expect(px == CGRect(x: 20, y: 40, width: 201, height: 101))
+ // Never outside the image.
+ #expect(ContentCapture.pixelRect(for: CGRect(x: 950, y: 650, width: 100, height: 100),
+ pageSize: Self.page.size, imageSize: CGSize(width: 2000, height: 1400))
+ == CGRect(x: 1900, y: 1300, width: 100, height: 100))
+ #expect(ContentCapture.pixelRect(for: .zero, pageSize: .zero, imageSize: CGSize(width: 10, height: 10)) == .zero)
+ }
+
+ @Test func pickerResultBecomesPoints() {
+ // Device pixels on a 2x screen.
+ let r = ContentCapture.elementRect(fromPicker: ["x": 100.0, "y": 60.0, "width": 400.0, "height": 300.0], scale: 2, pageBounds: Self.page)
+ #expect(r == CGRect(x: 50, y: 30, width: 200, height: 150))
+ // Partly scrolled off the top: only the visible part.
+ let off = ContentCapture.elementRect(fromPicker: ["x": 0, "y": -100, "width": 200, "height": 300] as [String: Any], scale: 1, pageBounds: Self.page)
+ #expect(off == CGRect(x: 0, y: 0, width: 200, height: 200))
+ // JSON numbers arrive as NSNumber.
+ let json = try? JSONSerialization.jsonObject(with: Data(#"{"x":2,"y":4,"width":20,"height":40}"#.utf8)) as? [String: Any]
+ #expect(ContentCapture.elementRect(fromPicker: json ?? [:], scale: 2, pageBounds: Self.page) == CGRect(x: 1, y: 2, width: 10, height: 20))
+ }
+
+ @Test func pickerFindingNothingOrOffPageIsNil() {
+ #expect(ContentCapture.elementRect(fromPicker: [:], scale: 2, pageBounds: Self.page) == nil)
+ #expect(ContentCapture.elementRect(fromPicker: ["x": 0, "y": 0, "width": 0, "height": 10], scale: 2, pageBounds: Self.page) == nil)
+ #expect(ContentCapture.elementRect(fromPicker: ["x": 5000, "y": 0, "width": 10, "height": 10], scale: 1, pageBounds: Self.page) == nil)
+ #expect(ContentCapture.elementRect(fromPicker: ["x": 0, "y": 0, "width": 10, "height": 10], scale: 0, pageBounds: Self.page) == nil)
+ }
+
+ @Test func lensMatchesArc() {
+ // Arc: the image at page (32, 224) 480 × 300 showed in colour from 30, its ring's outer edge 6 pt out.
+ let clear = ContentCapture.clearArea(element: CGRect(x: 32, y: 224, width: 480, height: 300))
+ #expect(clear == CGRect(x: 30, y: 222, width: 484, height: 304))
+ #expect(ContentCapture.lensFrame(around: clear) == CGRect(x: 26, y: 218, width: 492, height: 312))
+ // A dragged rectangle gets its ring right outside it (Arc: a drag ending at x 1080 had its ring to 1084).
+ #expect(ContentCapture.lensFrame(around: CGRect(x: 800, y: 145, width: 280, height: 175)).maxX == 1084)
+ }
+
+ @Test func menuGoesRightOfTheCaptureLikeArc() {
+ // Arc, 1371 × 848 pt page: a dragged rectangle (800, 145)–(1080, 320) put its 273 pt menu at
+ // x 1088 (4.5 right of the ring), level with the ring's top at 141.
+ let page = CGRect(x: 0, y: 0, width: 1371, height: 848)
+ let lens = ContentCapture.lensFrame(around: CGRect(x: 800, y: 145, width: 280, height: 175))
+ let menu = ContentCapture.menuFrame(size: CGSize(width: 273, height: 354), besideLens: lens, in: page)
+ #expect(menu == CGRect(x: 1088.5, y: 141, width: 273, height: 354))
+ }
+
+ @Test func menuFallsBackLeftThenInside() {
+ let size = CGSize(width: 200, height: 180)
+ // No room right: left of the ring.
+ let left = ContentCapture.menuFrame(size: size, besideLens: ContentCapture.lensFrame(around: CGRect(x: 700, y: 100, width: 250, height: 100)), in: Self.page)
+ #expect(left.maxX == 700 - 4 - ContentCapture.menuGap)
+ // A capture as wide as the page: inside its right edge.
+ let inside = ContentCapture.menuFrame(size: size, besideLens: ContentCapture.lensFrame(around: CGRect(x: 0, y: 100, width: 1000, height: 100)), in: Self.page)
+ #expect(inside.maxX == 1000 - ContentCapture.menuMargin)
+ // Near the bottom: pulled up to stay on the page; near the top: pushed down.
+ let low = ContentCapture.menuFrame(size: size, besideLens: ContentCapture.lensFrame(around: CGRect(x: 100, y: 650, width: 100, height: 40)), in: Self.page)
+ #expect(low.maxY == 700 - ContentCapture.menuMargin)
+ let high = ContentCapture.menuFrame(size: size, besideLens: ContentCapture.lensFrame(around: CGRect(x: 100, y: 0, width: 100, height: 40)), in: Self.page)
+ #expect(high.minY == ContentCapture.menuMargin)
+ }
+
+ @Test func pickerScriptCarriesThePoint() {
+ let s = ContentCapture.pickerScript(x: 123.5, y: 456)
+ #expect(s.contains("123.5 / dpr"))
+ #expect(s.contains("456.0 / dpr"))
+ #expect(s.contains("elementsFromPoint"))
+ }
+}
diff --git a/Sources/Cra/UI/Windows/CaptureOverlay.swift b/Sources/Cra/UI/Windows/CaptureOverlay.swift
new file mode 100644
index 0000000..18e685d
--- /dev/null
+++ b/Sources/Cra/UI/Windows/CaptureOverlay.swift
@@ -0,0 +1,892 @@
+import AppKit
+import AudioToolbox
+import CoreImage
+import CraCEF
+import QuartzCore
+import UniformTypeIdentifiers
+
+/// Arc's Capture (⇧⌘2, the camera in the Site Control Center), measured on Arc 1.171 (offline Arc,
+/// 2x window captures and 120 fps recordings, 4 Nov 2026; numbers in docs/arc-reverse-engineering.md).
+/// The page turns grey and darker in one frame; the element under the pointer stays in colour inside
+/// a dark ring that springs from element to element; a click takes that element, a drag takes a
+/// rectangle; a white hint at the bottom says which. Once taken, the capture stays lit and a dark
+/// menu beside it copies, saves or sends it, or starts again.
+///
+/// Cra draws all of it over a picture of the page taken as the mode starts (Chromium's own
+/// Page.captureScreenshot), in a panel over the page, so the page itself is never touched and the
+/// capture is exactly what was on screen. Decisions (picker, geometry) are in CraCore's ContentCapture.
+@MainActor
+final class CaptureOverlay {
+ enum Action { case copy, save, message, retake }
+
+ private let panel: CapturePanel
+ private let view: CaptureView
+ private weak var parent: NSWindow?
+ private var closed = false
+ /// Called once, when the overlay goes away; with the action and the capture's PNG if one was chosen.
+ var onFinish: ((Action?, Data?) -> Void)?
+
+ /// `pageRect`: the page on screen; `shot`: the page's pixels, top-left first.
+ init(over window: NSWindow, pageRect: NSRect, shot: CGImage, browser: CraBrowser) {
+ parent = window
+ panel = CapturePanel(contentRect: pageRect, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
+ view = CaptureView(frame: NSRect(origin: .zero, size: pageRect.size), shot: shot, browser: browser, scale: window.backingScaleFactor)
+ panel.contentView = view
+ view.finish = { [weak self] action, png in self?.finish(action, png) }
+ panel.onResignKey = { [weak self] in
+ // Another window took the keys (the sidebar, another app): the mode ends, as in Arc.
+ if self?.view.isSettled == false { return }
+ self?.finish(nil, nil)
+ }
+ window.addChildWindow(panel, ordered: .above)
+ panel.makeKeyAndOrderFront(nil)
+ panel.makeFirstResponder(view)
+ view.start()
+ }
+
+ var isOpen: Bool { !closed }
+
+ func close() { finish(nil, nil) }
+
+ private func finish(_ action: Action?, _ png: Data?) {
+ guard !closed else { return }
+ closed = true
+ view.stop()
+ parent?.removeChildWindow(panel)
+ panel.orderOut(nil)
+ NSCursor.arrow.set()
+ onFinish?(action, png)
+ onFinish = nil
+ }
+}
+
+final class CapturePanel: NSPanel {
+ var onResignKey: (() -> Void)?
+
+ override init(contentRect: NSRect, styleMask style: NSWindow.StyleMask, backing: NSWindow.BackingStoreType, defer flag: Bool) {
+ super.init(contentRect: contentRect, styleMask: style, backing: backing, defer: flag)
+ isOpaque = true
+ backgroundColor = .black
+ hasShadow = false
+ hidesOnDeactivate = false
+ isReleasedWhenClosed = false
+ animationBehavior = .none
+ acceptsMouseMovedEvents = true
+ becomesKeyOnlyIfNeeded = false
+ }
+
+ override var canBecomeKey: Bool { true }
+ override var canBecomeMain: Bool { false }
+
+ override func resignKey() {
+ super.resignKey()
+ // After the event that moved the keys, so a click in the menu's own window doesn't count.
+ DispatchQueue.main.async { [weak self] in
+ guard let self, !self.isKeyWindow else { return }
+ self.onResignKey?()
+ }
+ }
+}
+
+/// Arc's colours for Capture (ARC_Capture.bundle's asset catalog, dark appearance where it has one).
+enum CaptureStyle {
+ /// The ring around what is being captured (measured #161C2F).
+ static let ring = NSColor(srgbRed: 22 / 255, green: 28 / 255, blue: 47 / 255, alpha: 1)
+ /// Greyscale (Rec. 601 luma) under a 25 % black veil: 243 → 181, 255 → 191 (measured).
+ static let dim: CGFloat = 0.75
+ /// Arc's OverlayBubbleText, which reads at ~78 % on the white card (measured 93,55,169 at its darkest).
+ static let bubbleText = NSColor(srgbRed: 0.204, green: 0.021, blue: 0.58, alpha: 0.78)
+ static let bubbleBlue = NSColor(srgbRed: 0, green: 0.278, blue: 1, alpha: 0.5)
+ static let bubblePink = NSColor(srgbRed: 1, green: 0.6, blue: 0.6, alpha: 0.5)
+ static let menuFill = NSColor(srgbRed: 0.071, green: 0.059, blue: 0.18, alpha: 1)
+ static let menuText = NSColor(white: 1, alpha: 0.9)
+ static let menuIcon = NSColor(white: 1, alpha: 0.3)
+ static let menuDivider = NSColor(white: 1, alpha: 0.07)
+ static let menuHover = NSColor(srgbRed: 0.161, green: 0.18, blue: 0.757, alpha: 1)
+ static let menuHoverText = NSColor(white: 1, alpha: 0.95)
+}
+
+// MARK: - The page, the lens and the pointer
+
+@MainActor
+final class CaptureView: NSView {
+ enum Mode { case selecting, dragging(start: CGPoint), captured(CGRect) }
+
+ var finish: ((CaptureOverlay.Action?, Data?) -> Void)?
+ private let shot: CGImage
+ private weak var browser: CraBrowser?
+ private let scale: CGFloat
+ private var mode: Mode = .selecting
+
+ private let colourLayer = CALayer()
+ private let greyFull = CALayer()
+ private let greyHoled = CALayer()
+ private let holeMask = CAShapeLayer()
+ private let ring = CAShapeLayer()
+ private let ringShadow = CAShapeLayer()
+ private let ringShadowMask = CAShapeLayer()
+ private let bubble = CaptureBubble()
+ private var actionsMenu: CaptureMenu?
+
+ // The lens: where it is, where it is going, and how much of it shows.
+ private var lens: CGRect?
+ private var lensTarget: CGRect?
+ private var lensVelocity = [CGFloat](repeating: 0, count: 4)
+ private var lensAlpha: CGFloat = 0
+ private var lensAlphaTarget: CGFloat = 0
+ private var link: CADisplayLink?
+ private var lastStep: CFTimeInterval = 0
+
+ // The picker: one question at a time, the latest point waiting.
+ private var element: CGRect?
+ private var probing = false
+ private var pendingProbe: CGPoint?
+ private var pointer: CGPoint?
+
+ /// While a choice made in the menu is being carried out, losing the keys isn't a cancel.
+ private(set) var isSettled = true
+
+ init(frame: NSRect, shot: CGImage, browser: CraBrowser, scale: CGFloat) {
+ self.shot = shot
+ self.browser = browser
+ self.scale = scale
+ super.init(frame: frame)
+ wantsLayer = true
+ let root = layer!
+ root.backgroundColor = NSColor.black.cgColor
+ let grey = Self.dimmed(shot)
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ for l in [colourLayer, greyFull, greyHoled] {
+ l.frame = bounds
+ l.contentsGravity = .resize
+ l.contentsScale = scale
+ root.addSublayer(l)
+ }
+ colourLayer.contents = shot
+ greyFull.contents = grey
+ greyHoled.contents = grey
+ holeMask.fillRule = .evenOdd
+ holeMask.frame = bounds
+ greyHoled.mask = holeMask
+ greyFull.opacity = 1
+ ringShadow.fillColor = NSColor.black.cgColor
+ ringShadow.fillRule = .evenOdd
+ ringShadow.shadowColor = NSColor.black.cgColor
+ ringShadow.shadowOpacity = 0.32
+ ringShadow.shadowRadius = 10
+ ringShadow.shadowOffset = CGSize(width: 0, height: 3)
+ ringShadow.opacity = 0
+ // The ring's shadow falls outside it only, never on the lit page inside.
+ ringShadowMask.fillRule = .evenOdd
+ ringShadowMask.frame = bounds
+ ringShadow.mask = ringShadowMask
+ ring.fillColor = CaptureStyle.ring.cgColor
+ ring.fillRule = .evenOdd
+ ring.opacity = 0
+ root.addSublayer(ringShadow)
+ root.addSublayer(ring)
+ CATransaction.commit()
+ addSubview(bubble)
+ layoutBubble()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override var acceptsFirstResponder: Bool { true }
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+
+ func start() {
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseMoved, .activeAlways, .inVisibleRect, .cursorUpdate, .mouseEnteredAndExited], owner: self))
+ bubble.appear()
+ if let p = window?.mouseLocationOutsideOfEventStream, bounds.contains(convert(p, from: nil)) {
+ pointerMoved(to: convert(p, from: nil))
+ }
+ updateCursor()
+ }
+
+ func stop() {
+ link?.invalidate()
+ link = nil
+ }
+
+ /// Greyscale by Rec. 601 luma in the image's own (gamma) values, times `CaptureStyle.dim`, which
+ /// is what Arc shows (243,241,235 → 181; 212,73,76 → 86; 79,155,143 → 98).
+ private static func dimmed(_ image: CGImage) -> CGImage? {
+ let k = CaptureStyle.dim
+ let filter = CIFilter(name: "CIColorMatrix")!
+ filter.setValue(CIImage(cgImage: image), forKey: kCIInputImageKey)
+ let row = CIVector(x: 0.299 * k, y: 0.587 * k, z: 0.114 * k, w: 0)
+ filter.setValue(row, forKey: "inputRVector")
+ filter.setValue(row, forKey: "inputGVector")
+ filter.setValue(row, forKey: "inputBVector")
+ filter.setValue(CIVector(x: 0, y: 0, z: 0, w: 1), forKey: "inputAVector")
+ guard let out = filter.outputImage else { return nil }
+ // No working colour space: the matrix applies to the stored values, as Arc's does.
+ let context = CIContext(options: [.workingColorSpace: NSNull(), .outputColorSpace: NSNull()])
+ return context.createCGImage(out, from: CGRect(x: 0, y: 0, width: image.width, height: image.height),
+ format: .RGBA8, colorSpace: image.colorSpace ?? CGColorSpace(name: CGColorSpace.sRGB)!)
+ }
+
+ // MARK: Pointer
+
+ override func cursorUpdate(with event: NSEvent) { updateCursor() }
+
+ override func mouseMoved(with event: NSEvent) {
+ let p = convert(event.locationInWindow, from: nil)
+ if let actionsMenu, actionsMenu.frame.contains(p) { NSCursor.arrow.set(); return }
+ if case .selecting = mode { pointerMoved(to: p) }
+ updateCursor()
+ }
+
+ override func mouseExited(with event: NSEvent) {
+ if case .selecting = mode {
+ pointer = nil
+ setElement(nil)
+ }
+ }
+
+ private func pointerMoved(to p: CGPoint) {
+ pointer = p
+ probe(p)
+ }
+
+ private func updateCursor() {
+ switch mode {
+ case .selecting: (element == nil ? CaptureCursors.cross : CaptureCursors.camera).set()
+ case .dragging: CaptureCursors.cross.set()
+ case .captured: NSCursor.arrow.set()
+ }
+ }
+
+ override func mouseDown(with event: NSEvent) {
+ let p = convert(event.locationInWindow, from: nil)
+ if case .captured = mode {
+ if let actionsMenu, actionsMenu.frame.contains(p) { return }
+ // A press beside the capture starts over, from this press.
+ dropMenu()
+ mode = .selecting
+ bubble.show(true)
+ }
+ mode = .dragging(start: p)
+ pressedOnElement = element
+ }
+
+ private var pressedOnElement: CGRect?
+
+ override func mouseDragged(with event: NSEvent) {
+ guard case .dragging(let start) = mode else { return }
+ let p = convert(event.locationInWindow, from: nil)
+ guard ContentCapture.isDrag(from: start, to: p) || pressedOnElement == nil else { return }
+ pressedOnElement = nil
+ let r = ContentCapture.selection(from: start, to: p, in: bounds)
+ element = nil
+ bubble.setCanClick(false)
+ snapLens(to: r.isEmpty ? nil : r)
+ CaptureCursors.cross.set()
+ }
+
+ override func mouseUp(with event: NSEvent) {
+ guard case .dragging(let start) = mode else { return }
+ let p = convert(event.locationInWindow, from: nil)
+ if let clicked = pressedOnElement, !ContentCapture.isDrag(from: start, to: p) {
+ capture(clicked, lens: ContentCapture.clearArea(element: clicked))
+ return
+ }
+ let r = ContentCapture.selection(from: start, to: p, in: bounds)
+ if ContentCapture.isCapturable(r) {
+ capture(r, lens: r)
+ } else {
+ mode = .selecting
+ snapLens(to: nil)
+ pointerMoved(to: p)
+ updateCursor()
+ }
+ }
+
+ override func scrollWheel(with event: NSEvent) {}
+
+ // MARK: Keys
+
+ override func keyDown(with event: NSEvent) {
+ if let actionsMenu, actionsMenu.handleKey(event) { return }
+ if event.keyCode == 53 { finish?(nil, nil); return }
+ super.keyDown(with: event)
+ }
+
+ override func cancelOperation(_ sender: Any?) { finish?(nil, nil) }
+
+ /// Any other shortcut (a new tab, another space) ends the mode before the menu bar runs it; the
+ /// capture shortcut is left to the menu bar, which closes the mode itself.
+ override func performKeyEquivalent(with event: NSEvent) -> Bool {
+ // With a capture taken, ⌘C and ⌘S copy and save it.
+ if case .captured = mode, let menu = actionsMenu,
+ event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command {
+ switch event.charactersIgnoringModifiers {
+ case "c": menu.run(.copy); return true
+ case "s": menu.run(.save); return true
+ default: break
+ }
+ }
+ if event.modifierFlags.contains(.command), KeyBindingRegistry.shared.action(for: event)?.id != "capturePage" {
+ finish?(nil, nil)
+ }
+ return false
+ }
+
+ // MARK: The element under the pointer
+
+ private func probe(_ p: CGPoint) {
+ guard let browser, browser.isCreated, !browser.isClosed else { return }
+ if probing { pendingProbe = p; return }
+ probing = true
+ let script = ContentCapture.pickerScript(x: p.x * scale, y: p.y * scale)
+ let params = (try? JSONSerialization.data(withJSONObject: ["expression": script, "returnByValue": true]))
+ .flatMap { String(data: $0, encoding: .utf8) } ?? "{}"
+ browser.evaluate(inIsolatedWorld: PageScript.world, params: params) { [weak self] result, _ in
+ DispatchQueue.main.async {
+ guard let self else { return }
+ self.probing = false
+ var rect: CGRect?
+ if let data = result?.data(using: .utf8),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let value = (json["result"] as? [String: Any])?["value"] as? [String: Any] {
+ rect = ContentCapture.elementRect(fromPicker: value, scale: self.scale, pageBounds: self.bounds)
+ }
+ if let next = self.pendingProbe {
+ self.pendingProbe = nil
+ self.probe(next)
+ }
+ // Only while the pointer is still choosing, and only if it is still over this answer's point.
+ guard case .selecting = self.mode, self.pointer != nil else { return }
+ if let rect, let ptr = self.pointer, !rect.insetBy(dx: -2, dy: -2).contains(ptr) { return }
+ self.setElement(rect)
+ }
+ }
+ }
+
+ private func setElement(_ rect: CGRect?) {
+ guard rect != element else { return }
+ element = rect
+ bubble.setCanClick(rect != nil)
+ if let rect {
+ springLens(to: ContentCapture.clearArea(element: rect))
+ } else {
+ fadeLens()
+ }
+ updateCursor()
+ }
+
+ // MARK: Capture
+
+ /// `rect` is what goes in the image; `lens` what stays lit (an element's 2 pt more).
+ private func capture(_ rect: CGRect, lens clear: CGRect) {
+ mode = .captured(rect)
+ element = nil
+ pressedOnElement = nil
+ snapLens(to: clear)
+ let px = ContentCapture.pixelRect(for: rect, pageSize: bounds.size, imageSize: CGSize(width: shot.width, height: shot.height))
+ guard let cropped = shot.cropping(to: px), let png = Self.png(cropped) else { finish?(nil, nil); return }
+ CaptureSound.play()
+ bubble.show(false)
+ showMenu(png: png)
+ NSCursor.arrow.set()
+ }
+
+ static func png(_ image: CGImage) -> Data? {
+ let data = NSMutableData()
+ guard let dest = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil) else { return nil }
+ CGImageDestinationAddImage(dest, image, nil)
+ return CGImageDestinationFinalize(dest) ? data as Data : nil
+ }
+
+ private func showMenu(png: Data) {
+ dropMenu()
+ let m = CaptureMenu { [weak self] action in
+ guard let self else { return }
+ self.isSettled = false
+ if action == .retake {
+ self.finish?(.retake, nil)
+ } else {
+ self.finish?(action, png)
+ }
+ }
+ let lensFrame = ContentCapture.lensFrame(around: lens ?? .zero)
+ m.frame = ContentCapture.menuFrame(size: m.intrinsicContentSize, besideLens: lensFrame, in: bounds)
+ addSubview(m)
+ m.appear()
+ actionsMenu = m
+ }
+
+ private func dropMenu() {
+ actionsMenu?.removeFromSuperview()
+ actionsMenu = nil
+ }
+
+ // MARK: Lens drawing and motion
+
+ /// Arc's FocusRectAnimator: a spring on the whole rectangle (measured 120 fps: ~0.15 s to arrive,
+ /// 0.4 % overshoot), i.e. stiffness ≈ 2000, damping ≈ 78 for unit mass.
+ private static let stiffness: CGFloat = 2000
+ private static let damping: CGFloat = 78
+ /// The lens fades in and out (Arc's lensOpacity).
+ private static let fadeDuration: CGFloat = 0.12
+
+ private func springLens(to rect: CGRect) {
+ if lens == nil || lensAlpha < 0.05 {
+ lens = rect
+ lensVelocity = [0, 0, 0, 0]
+ }
+ lensTarget = rect
+ lensAlphaTarget = 1
+ run()
+ }
+
+ private func fadeLens() {
+ lensAlphaTarget = 0
+ run()
+ }
+
+ /// Straight to `rect` (a drag), no spring.
+ private func snapLens(to rect: CGRect?) {
+ if let rect {
+ lens = rect
+ lensTarget = rect
+ lensVelocity = [0, 0, 0, 0]
+ lensAlpha = 1
+ lensAlphaTarget = 1
+ } else {
+ lensAlphaTarget = 0
+ lensAlpha = 0
+ }
+ draw()
+ run()
+ }
+
+ private func run() {
+ guard link == nil else { return }
+ let l = displayLink(target: self, selector: #selector(step))
+ l.add(to: .main, forMode: .common)
+ link = l
+ lastStep = CACurrentMediaTime()
+ }
+
+ @objc private func step(_ l: CADisplayLink) {
+ let now = CACurrentMediaTime()
+ let elapsed = min(now - lastStep, 1.0 / 30)
+ var dt = elapsed
+ lastStep = now
+ var moving = false
+ if var r = lens, let t = lensTarget {
+ var v = lensVelocity
+ var cur = [r.minX, r.minY, r.width, r.height]
+ let goal = [t.minX, t.minY, t.width, t.height]
+ while dt > 0 {
+ let h = min(dt, 1.0 / 480)
+ for i in 0..<4 {
+ let a = -Self.stiffness * (cur[i] - goal[i]) - Self.damping * v[i]
+ v[i] += a * h
+ cur[i] += v[i] * h
+ }
+ dt -= h
+ }
+ r = CGRect(x: cur[0], y: cur[1], width: cur[2], height: cur[3])
+ if zip(cur, goal).allSatisfy({ abs($0 - $1) < 0.05 }) && v.allSatisfy({ abs($0) < 0.5 }) {
+ r = t
+ v = [0, 0, 0, 0]
+ } else {
+ moving = true
+ }
+ lens = r
+ lensVelocity = v
+ }
+ if lensAlpha != lensAlphaTarget {
+ let d = CGFloat(elapsed) / Self.fadeDuration
+ lensAlpha = lensAlphaTarget > lensAlpha ? min(lensAlphaTarget, lensAlpha + d) : max(lensAlphaTarget, lensAlpha - d)
+ moving = true
+ }
+ draw()
+ if !moving {
+ l.invalidate()
+ link = nil
+ if lensAlpha == 0 { lens = nil; lensTarget = nil }
+ }
+ }
+
+ private func draw() {
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ let full = CGPath(rect: bounds, transform: nil)
+ if let r = lens, lensAlpha > 0 {
+ let inner = ContentCapture.lensInnerRadius
+ let outer = inner + ContentCapture.lensRing
+ let clear = CGPath(roundedRect: r, cornerWidth: min(inner, r.width / 2), cornerHeight: min(inner, r.height / 2), transform: nil)
+ let o = ContentCapture.lensFrame(around: r)
+ let outerPath = CGPath(roundedRect: o, cornerWidth: min(outer, o.width / 2), cornerHeight: min(outer, o.height / 2), transform: nil)
+ let hole = CGMutablePath()
+ hole.addPath(full)
+ hole.addPath(clear)
+ holeMask.path = hole
+ let ringPath = CGMutablePath()
+ ringPath.addPath(outerPath)
+ ringPath.addPath(clear)
+ ring.path = ringPath
+ ringShadow.path = outerPath
+ ringShadow.shadowPath = outerPath
+ let outside = CGMutablePath()
+ outside.addPath(full)
+ outside.addPath(outerPath)
+ ringShadowMask.path = outside
+ ring.opacity = Float(lensAlpha)
+ ringShadow.opacity = Float(lensAlpha)
+ greyFull.opacity = Float(1 - lensAlpha)
+ } else {
+ holeMask.path = full
+ ring.opacity = 0
+ ringShadow.opacity = 0
+ greyFull.opacity = 1
+ }
+ CATransaction.commit()
+ }
+
+ private func layoutBubble() {
+ let size = CaptureBubble.size
+ bubble.frame = NSRect(x: ((bounds.width - size.width) / 2).rounded(), y: bounds.height - CaptureBubble.bottomInset - size.height,
+ width: size.width, height: size.height)
+ }
+}
+
+// MARK: - The hint at the bottom
+
+/// Arc's ContentCaptureOverlayBubble: a white 354 × 65 pt card 36.5 pt above the page's bottom,
+/// centred, 17 pt corners, a hairline from pink to blue, 14 pt semibold purple text, in a soft
+/// pink and blue glow. "Click or drag…" while there is an element to click, "Drag…" otherwise.
+/// It fades in over ~0.16 s; the dimming itself is instant.
+final class CaptureBubble: NSView {
+ static let size = CGSize(width: 354, height: 65)
+ static let bottomInset: CGFloat = 36.5
+ static let cornerRadius: CGFloat = 17
+ static let clickText = "Click or drag to capture a portion of this page"
+ static let dragText = "Drag to capture a portion of this page"
+
+ private let glowPink = CAGradientLayer()
+ private let glowBlue = CAGradientLayer()
+ private let card = CALayer()
+ private let rim = CAGradientLayer()
+ private let rimMask = CAShapeLayer()
+ private let label = NSTextField(labelWithString: CaptureBubble.dragText)
+ private var canClick = false
+
+ override init(frame: NSRect) {
+ super.init(frame: frame)
+ wantsLayer = true
+ layer?.masksToBounds = false
+ // Arc's glow darkens the dimmed page with a tint rather than lighting it (measured beside the
+ // card: 163 grey → 155,147,148 on the left, 140,143,156 on the right, gone ~90 pt out).
+ let pink = NSColor(srgbRed: 95 / 255, green: 45 / 255, blue: 50 / 255, alpha: 0.3)
+ let blue = NSColor(srgbRed: 20 / 255, green: 35 / 255, blue: 120 / 255, alpha: 0.34)
+ for (g, c) in [(glowPink, pink), (glowBlue, blue)] {
+ g.type = .radial
+ g.colors = [c.cgColor, c.withAlphaComponent(0).cgColor]
+ g.startPoint = CGPoint(x: 0.5, y: 0.5)
+ g.endPoint = CGPoint(x: 1, y: 1)
+ layer?.addSublayer(g)
+ }
+ card.backgroundColor = NSColor.white.cgColor
+ card.cornerRadius = Self.cornerRadius
+ card.cornerCurve = .continuous
+ layer?.addSublayer(card)
+ rim.colors = [CaptureStyle.bubblePink.withAlphaComponent(0.35).cgColor, CaptureStyle.bubbleBlue.withAlphaComponent(0.35).cgColor]
+ rim.startPoint = CGPoint(x: 0, y: 0.5)
+ rim.endPoint = CGPoint(x: 1, y: 0.5)
+ rimMask.fillColor = nil
+ rimMask.strokeColor = NSColor.black.cgColor
+ rimMask.lineWidth = 1
+ rim.mask = rimMask
+ layer?.addSublayer(rim)
+ label.font = .systemFont(ofSize: 14, weight: .semibold)
+ label.textColor = CaptureStyle.bubbleText
+ label.alignment = .center
+ addSubview(label)
+ alphaValue = 0
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ override func layout() {
+ super.layout()
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ card.frame = bounds
+ rim.frame = bounds
+ rimMask.frame = bounds
+ rimMask.path = CGPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), cornerWidth: Self.cornerRadius - 0.5, cornerHeight: Self.cornerRadius - 0.5, transform: nil)
+ // The glow: pink low on the left, blue on the right, spilling well past the card.
+ glowPink.frame = CGRect(x: -130, y: -70, width: 330, height: 205)
+ glowBlue.frame = CGRect(x: bounds.width - 200, y: -80, width: 330, height: 225)
+ CATransaction.commit()
+ label.sizeToFit()
+ label.frame = NSRect(x: 0, y: ((bounds.height - label.frame.height) / 2).rounded(), width: bounds.width, height: label.frame.height)
+ }
+
+ func appear() {
+ NSAnimationContext.runAnimationGroup { c in
+ c.duration = 0.16
+ c.timingFunction = CAMediaTimingFunction(name: .easeOut)
+ animator().alphaValue = 1
+ }
+ }
+
+ func show(_ visible: Bool) {
+ alphaValue = visible ? 1 : 0
+ }
+
+ func setCanClick(_ can: Bool) {
+ guard can != canClick else { return }
+ canClick = can
+ label.stringValue = can ? Self.clickText : Self.dragText
+ }
+}
+
+// MARK: - The menu after a capture
+
+/// Arc's CapturedImageActionsView, dark whatever the theme: 273 pt wide, 10 pt corners, fill
+/// (18,15,46); 40 pt rows with a 13 pt symbol centred 25 pt in at white 30 % and 14 pt medium text
+/// from 41 pt at white 90 %; sections apart by 9 pt with a hairline 10 pt in from both sides.
+/// Arc's other rows (Send To… for Easels, Save to Library, Edit, New Easel) belong to features
+/// Cra doesn't have.
+final class CaptureMenu: NSView {
+ struct Row {
+ let title: String
+ let symbol: String
+ let action: CaptureOverlay.Action
+ }
+
+ static let width: CGFloat = 273
+ static let rowHeight: CGFloat = 40
+ static let sectionGap: CGFloat = 9
+ static let padding: CGFloat = 6
+ static let cornerRadius: CGFloat = 10
+ static let sections: [[Row]] = [
+ [Row(title: "Copy", symbol: "doc.on.doc.fill", action: .copy),
+ Row(title: "Save...", symbol: "square.and.arrow.down.fill", action: .save),
+ Row(title: "Send via iMessage...", symbol: "message.fill", action: .message)],
+ [Row(title: "Retake", symbol: "arrow.counterclockwise", action: .retake)],
+ ]
+
+ private var rowViews: [CaptureMenuRow] = []
+ private var selected: Int? { didSet { for (i, r) in rowViews.enumerated() { r.highlighted = i == selected } } }
+ private let choose: (CaptureOverlay.Action) -> Void
+
+ init(choose: @escaping (CaptureOverlay.Action) -> Void) {
+ self.choose = choose
+ super.init(frame: .zero)
+ wantsLayer = true
+ layer?.backgroundColor = CaptureStyle.menuFill.cgColor
+ layer?.cornerRadius = Self.cornerRadius
+ layer?.cornerCurve = .continuous
+ shadow = {
+ let s = NSShadow()
+ s.shadowColor = NSColor.black.withAlphaComponent(0.3)
+ s.shadowBlurRadius = 12
+ s.shadowOffset = NSSize(width: 0, height: -4)
+ return s
+ }()
+ var y = Self.padding
+ for (si, section) in Self.sections.enumerated() {
+ if si > 0 {
+ let line = NSView(frame: NSRect(x: 10, y: y + 3.5, width: Self.width - 20, height: 0.5))
+ line.wantsLayer = true
+ line.layer?.backgroundColor = CaptureStyle.menuDivider.cgColor
+ addSubview(line)
+ y += Self.sectionGap
+ }
+ for row in section {
+ let index = rowViews.count
+ let v = CaptureMenuRow(row: row) { [weak self] in self?.choose(row.action) }
+ v.onHover = { [weak self] inside in
+ if inside { self?.selected = index } else if self?.selected == index { self?.selected = nil }
+ }
+ v.frame = NSRect(x: 0, y: y, width: Self.width, height: Self.rowHeight)
+ addSubview(v)
+ rowViews.append(v)
+ y += Self.rowHeight
+ }
+ }
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+
+ override var intrinsicContentSize: NSSize {
+ let rows = Self.sections.reduce(0) { $0 + $1.count }
+ return NSSize(width: Self.width, height: Self.padding * 2 + CGFloat(rows) * Self.rowHeight + CGFloat(Self.sections.count - 1) * Self.sectionGap)
+ }
+
+ func appear() {
+ alphaValue = 0
+ NSAnimationContext.runAnimationGroup { c in
+ c.duration = 0.12
+ animator().alphaValue = 1
+ }
+ }
+
+ func run(_ action: CaptureOverlay.Action) { choose(action) }
+
+ /// ↑ ↓ pick a row, Return runs it.
+ func handleKey(_ event: NSEvent) -> Bool {
+ switch event.keyCode {
+ case 125: selected = selected.map { min($0 + 1, rowViews.count - 1) } ?? 0; return true
+ case 126: selected = selected.map { max($0 - 1, 0) } ?? rowViews.count - 1; return true
+ case 36, 76:
+ guard let i = selected else { return false }
+ rowViews[i].run()
+ return true
+ default: return false
+ }
+ }
+}
+
+final class CaptureMenuRow: NSView {
+ private let fill = CALayer()
+ private let icon = NSImageView()
+ private let label: NSTextField
+ private let action: () -> Void
+ var onHover: ((Bool) -> Void)?
+ var highlighted = false { didSet { paint() } }
+
+ init(row: CaptureMenu.Row, action: @escaping () -> Void) {
+ self.action = action
+ label = NSTextField(labelWithString: row.title)
+ super.init(frame: .zero)
+ wantsLayer = true
+ fill.cornerRadius = 6
+ fill.cornerCurve = .continuous
+ layer?.addSublayer(fill)
+ icon.image = NSImage(systemSymbolName: row.symbol, accessibilityDescription: nil)?
+ .withSymbolConfiguration(.init(pointSize: 13, weight: .medium))
+ icon.imageScaling = .scaleNone
+ label.font = .systemFont(ofSize: 14, weight: .medium)
+ addSubview(icon)
+ addSubview(label)
+ setAccessibilityRole(.button)
+ setAccessibilityLabel(row.title)
+ paint()
+ }
+
+ required init?(coder: NSCoder) { fatalError() }
+
+ override var isFlipped: Bool { true }
+ override func hitTest(_ point: NSPoint) -> NSView? { frame.contains(point) ? self : nil }
+
+ override func layout() {
+ super.layout()
+ fill.frame = bounds.insetBy(dx: 5, dy: 2)
+ icon.frame = NSRect(x: 25 - 10, y: (bounds.height - 20) / 2, width: 20, height: 20)
+ label.sizeToFit()
+ label.frame.origin = NSPoint(x: 41, y: ((bounds.height - label.frame.height) / 2).rounded())
+ }
+
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ for t in trackingAreas { removeTrackingArea(t) }
+ addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self))
+ }
+
+ override func mouseEntered(with event: NSEvent) { onHover?(true) }
+ override func mouseExited(with event: NSEvent) { onHover?(false) }
+ override func mouseDown(with event: NSEvent) {}
+ override func mouseUp(with event: NSEvent) {
+ if bounds.contains(convert(event.locationInWindow, from: nil)) { run() }
+ }
+
+ override func accessibilityPerformPress() -> Bool { run(); return true }
+
+ func run() { action() }
+
+ private func paint() {
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ fill.backgroundColor = highlighted ? CaptureStyle.menuHover.cgColor : nil
+ CATransaction.commit()
+ label.textColor = highlighted ? CaptureStyle.menuHoverText : CaptureStyle.menuText
+ icon.contentTintColor = highlighted ? CaptureStyle.menuHoverText : CaptureStyle.menuIcon
+ }
+}
+
+// MARK: - Pointers and sound
+
+/// Arc's two capture pointers, drawn the same way: a dark camera with a white outline over an
+/// element that a click would take, and a crosshair with that camera at its top right elsewhere.
+@MainActor
+enum CaptureCursors {
+ static let camera: NSCursor = {
+ let size = NSSize(width: 24, height: 19)
+ let image = NSImage(size: size, flipped: false) { r in
+ drawCamera(in: r.insetBy(dx: 1, dy: 1))
+ return true
+ }
+ return NSCursor(image: image, hotSpot: NSPoint(x: size.width / 2, y: size.height / 2))
+ }()
+
+ static let cross: NSCursor = {
+ let size = NSSize(width: 34, height: 32)
+ let image = NSImage(size: size, flipped: false) { _ in
+ // The crosshair: 16 pt arms, 1.5 pt dark lines on a light halo, centred 9 pt from the
+ // bottom-left; the camera above and right of it.
+ let c = NSPoint(x: 9, y: 9)
+ for (color, width) in [(NSColor.white.withAlphaComponent(0.8), 3.5), (NSColor(white: 0.17, alpha: 1), 1.5)] {
+ color.setStroke()
+ let p = NSBezierPath()
+ p.lineWidth = width
+ p.move(to: NSPoint(x: c.x - 8, y: c.y)); p.line(to: NSPoint(x: c.x + 8, y: c.y))
+ p.move(to: NSPoint(x: c.x, y: c.y - 8)); p.line(to: NSPoint(x: c.x, y: c.y + 8))
+ p.stroke()
+ }
+ drawCamera(in: NSRect(x: 12, y: 14, width: 21, height: 16))
+ return true
+ }
+ // Hot spots count from the top-left.
+ return NSCursor(image: image, hotSpot: NSPoint(x: 9, y: size.height - 9))
+ }()
+
+ /// A camera body with a lens ring and a dot, dark with a white outline, in `r` (y up).
+ private static func drawCamera(in r: NSRect) {
+ let body = NSRect(x: r.minX, y: r.minY, width: r.width, height: r.height * 0.78)
+ let hump = NSRect(x: r.midX - r.width * 0.2, y: body.maxY - 2, width: r.width * 0.4, height: r.height * 0.22 + 2)
+ let shape = NSBezierPath(roundedRect: body, xRadius: 3, yRadius: 3)
+ shape.append(NSBezierPath(roundedRect: hump, xRadius: 1.5, yRadius: 1.5))
+ NSColor.white.setStroke()
+ shape.lineWidth = 2
+ shape.stroke()
+ NSColor(srgbRed: 0.13, green: 0.16, blue: 0.19, alpha: 1).setFill()
+ shape.fill()
+ let d = body.height * 0.5
+ let lens = NSBezierPath(ovalIn: NSRect(x: body.midX - d / 2, y: body.midY - d / 2, width: d, height: d))
+ NSColor.white.setStroke()
+ lens.lineWidth = 1.4
+ lens.stroke()
+ NSColor.white.setFill()
+ NSBezierPath(ovalIn: NSRect(x: body.maxX - 4.5, y: body.maxY - 4.5, width: 2, height: 2)).fill()
+ }
+}
+
+/// macOS's own screenshot sound, when a capture is taken (Arc plays its capture.wav there). A
+/// system sound plays in the sound server, so the main thread never waits for an output device.
+@MainActor
+enum CaptureSound {
+ private static let id: SystemSoundID? = {
+ var id: SystemSoundID = 0
+ let url = URL(fileURLWithPath: "/System/Library/Components/CoreAudio.component/Contents/SharedSupport/SystemSounds/system/Screen Capture.aif")
+ return AudioServicesCreateSystemSoundID(url as CFURL, &id) == noErr ? id : nil
+ }()
+
+ static func play() {
+ if let id { AudioServicesPlaySystemSound(id) }
+ }
+}
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index 127b942..5b70a45 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -1439,13 +1439,98 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
b.setZoomLevel(b.zoomLevel() + delta)
}
- /// Arc's Capture: the visible page as a PNG. Chromium draws it (Page.captureScreenshot), so
- /// it holds the page whatever display the window is on and whatever is in front of it.
+ /// Arc's Capture (⇧⌘2 again closes it): the page dims, a click takes the element under the
+ /// pointer and a drag a rectangle, then a menu copies, saves or sends it (CaptureOverlay).
+ /// Chromium draws the picture it works on (Page.captureScreenshot), so it holds the page
+ /// whatever display the window is on and whatever is in front of it.
func capturePage() {
- guard let b = currentBrowser else { return }
- b.sendDevToolsMethod("Page.captureScreenshot", params: #"{"format":"png","captureBeyondViewport":false}"#) { [weak self] shot, error in
- MainActor.assumeIsolated { self?.finishCapture(shot, error: error) }
+ if let open = captureOverlay, open.isOpen { open.close(); return }
+ guard !captureStarting, let rt = browsers.visibleRuntime, rt.browser.isCreated, !rt.browser.isClosed,
+ pageScreenRect(rt) != nil else { return }
+ let b = rt.browser
+ captureStarting = true
+ b.sendDevToolsMethod("Page.captureScreenshot", params: #"{"format":"png","captureBeyondViewport":false}"#) { [weak self, weak b] shot, error in
+ MainActor.assumeIsolated {
+ guard let self else { return }
+ self.captureStarting = false
+ guard let b, let window = self.window, let rt = self.browsers.visibleRuntime, rt.browser === b,
+ let rect = self.pageScreenRect(rt) else { return }
+ guard let image = Self.screenshotImage(shot) else {
+ NSLog("Cra: capture failed: %@", error ?? "no data")
+ self.showToast("Capture Failed")
+ return
+ }
+ let overlay = CaptureOverlay(over: window, pageRect: rect, shot: image, browser: b)
+ overlay.onFinish = { [weak self] action, png in self?.captureFinished(action, png) }
+ self.captureOverlay = overlay
+ }
+ }
+ }
+
+ private var captureOverlay: CaptureOverlay?
+ private var captureStarting = false
+
+ /// The focused page on screen, whether its view is embedded in the card or in its own window.
+ private func pageScreenRect(_ rt: TabRuntime) -> NSRect? {
+ let view = rt.hostWindow.flatMap { EmbeddedPages.pageViews(of: $0)?.last } ?? rt.browser.containerView
+ guard let w = view.window, !view.isHiddenOrHasHiddenAncestor, view.bounds.width > 1, view.bounds.height > 1 else { return nil }
+ return w.convertToScreen(view.convert(view.bounds, to: nil))
+ }
+
+ private static func screenshotImage(_ shot: String?) -> CGImage? {
+ guard let shot, let o = try? JSONSerialization.jsonObject(with: Data(shot.utf8)) as? [String: Any],
+ let b64 = o["data"] as? String, let png = Data(base64Encoded: b64),
+ let source = CGImageSourceCreateWithData(png as CFData, nil) else { return nil }
+ return CGImageSourceCreateImageAtIndex(source, 0, nil)
+ }
+
+ /// The capture menu's choice, once the overlay is down.
+ private func captureFinished(_ action: CaptureOverlay.Action?, _ png: Data?) {
+ captureOverlay = nil
+ if action != nil || NSApp.isActive, window?.isVisible == true {
+ window?.makeKey()
+ currentBrowser?.setFocused(true)
+ }
+ switch action {
+ case .copy?:
+ guard let png else { return }
+ copyCapture(png)
+ showToast("Screenshot Copied to Clipboard")
+ case .save?:
+ if let png { saveCapture(png) }
+ case .message?:
+ if let png { sendCaptureViaMessages(png) }
+ case .retake?:
+ capturePage()
+ case nil:
+ break
+ }
+ }
+
+ private func copyCapture(_ png: Data) {
+ let pasteboard = NSPasteboard.general
+ pasteboard.declareTypes([.png, .tiff], owner: nil)
+ pasteboard.setData(png, forType: .png)
+ if let tiff = NSImage(data: png)?.tiffRepresentation { pasteboard.setData(tiff, forType: .tiff) }
+ }
+
+ /// Arc's "Send via iMessage…": Messages' compose sheet with the capture attached.
+ private func sendCaptureViaMessages(_ png: Data) {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("Cra Captures", isDirectory: true)
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ let url = dir.appendingPathComponent(Self.captureFileName())
+ guard (try? png.write(to: url)) != nil, let service = NSSharingService(named: .composeMessage),
+ service.canPerform(withItems: [url]) else {
+ showToast("Messages Isn't Available")
+ return
}
+ service.perform(withItems: [url])
+ }
+
+ private static func captureFileName() -> String {
+ let f = DateFormatter()
+ f.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss"
+ return "Cra Capture \(f.string(from: Date())).png"
}
// MARK: Sidebar
@@ -2123,6 +2208,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
/// Arc's "Capture the full page": the whole document, beyond the viewport, as a PNG.
func captureFullPage() {
+ captureOverlay?.close()
guard let b = currentBrowser else { return }
showToast("Capture in Progress")
// Both completions come on the main queue.
@@ -2144,32 +2230,22 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
/// the toast's Save puts it in a file. Finder stays where it is (GitHub #90).
private func finishCapture(_ shot: String?, error: String?) {
guard let shot, let o = try? JSONSerialization.jsonObject(with: Data(shot.utf8)) as? [String: Any],
- let b64 = o["data"] as? String, let png = Data(base64Encoded: b64), let image = NSImage(data: png) else {
+ let b64 = o["data"] as? String, let png = Data(base64Encoded: b64), NSImage(data: png) != nil else {
NSLog("Cra: capture failed: %@", error ?? "no data")
showToast("Capture Failed")
return
}
- let pasteboard = NSPasteboard.general
- pasteboard.declareTypes([.png, .tiff], owner: nil)
- pasteboard.setData(png, forType: .png)
- if let tiff = image.tiffRepresentation { pasteboard.setData(tiff, forType: .tiff) }
- Self.shutter?.stop()
- Self.shutter?.play()
+ copyCapture(png)
+ CaptureSound.play()
showToast("Screenshot Copied to Clipboard", action: ShinyToast.Action(title: "Save") { [weak self] in self?.saveCapture(png) })
}
- /// macOS's own screenshot sound.
- private static let shutter = NSSound(contentsOfFile: "/System/Library/Components/CoreAudio.component/Contents/SharedSupport/SystemSounds/system/Screen Capture.aif",
- byReference: true)
-
/// The toast's Save: Arc's "Save Capture Image" panel, in Downloads.
private func saveCapture(_ png: Data) {
guard let window else { return }
- let f = DateFormatter()
- f.dateFormat = "yyyy-MM-dd 'at' HH.mm.ss"
let panel = NSSavePanel()
panel.title = "Save Capture Image"
- panel.nameFieldStringValue = "Cra Capture \(f.string(from: Date())).png"
+ panel.nameFieldStringValue = Self.captureFileName()
panel.allowedContentTypes = [.png]
panel.directoryURL = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first
panel.beginSheetModal(for: window) { [weak self] response in
diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.md
index eb1a0b1..802d497 100644
--- a/docs/arc-reverse-engineering.md
+++ b/docs/arc-reverse-engineering.md
@@ -2789,3 +2789,39 @@ event with `shiftClickModalEntryPointEnabled` set for the run, AX frames and 60
the peeked page on the right. Cra: MainWindowController.closedPeek, LittleWindowController.promoteToSplit.
- [?] Not measured: the card at other window widths (Cra keeps 80 % of the area), and the Peek with Arc's
toolbar turned off.
+
+## Capture (Arc 1.171, 4 Nov 2026, X request, Swift metadata + strings + offline Arc at 2x, 120 fps recordings)
+- [O metadata] Module `Capture`: ContentCaptureViewController holds ContentCaptureView (grayscale and darkened layers with
+ shape masks, a lens ShadowView, a camera cursor view, single/double click and pan recognizers, an Esc monitor,
+ `FocusRectAnimator` = a Motion spring on the rect plus `lensOpacity`), ContentCaptureOverlayBubble, CapturedImageView
+ and CapturedImageActionsView (a SwiftUI menu). Actions (`CaptureImageMenuView.Item.ContentType`): easel(String),
+ newEasel, copy, library (toggle), saveAsFile, sendAsMessage, edit, retake. `CaptureType` partialPage / fullWindow
+ (the "pretty screenshot" with wallpaper/tint/watermark is fullWindow). Captures are kept in StorableCaptures.json for
+ the Library's Media.
+- [O strings] Click-to-capture picker (JS, `elementsFromPoint`): score each element under the pointer: −5 if its smaller
+ side < 100, −5 if as wide as the window, −5 if as tall, −5 if over 70 % of the window's area, +5 for IMG/PICTURE/OBJECT,
+ + (w + h) / 2 / 500, −10 if `display: inline`; keep scores ≥ 0, take the best. Live: over a 3-card grid it picked the
+ grid; text, a full-width header and a taller-than-window block got nothing (bubble then says "Drag…").
+- [O live] ⇧⌘2: the page (not the toolbar or sidebar) turns greyscale under a 25 % black veil in ONE frame:
+ value = 0.75 × Rec. 601 luma of the stored sRGB values (243,241,235 → 181; 212,73,76 → 86; 79,155,143 → 98; within 1).
+- [O live] Lens: the element shows in colour 2 pt beyond its edges with 4.5 pt corners, inside a 4 pt ring #161C2F
+ (outer corners 8.5 pt), and a soft shadow outside it (~26 pt falloff, a few pt low). A dragged rectangle gets the ring
+ right outside it (no 2 pt clearance). Moving between elements the rect springs: ~0.15 s to arrive, 0.4 % overshoot,
+ settled by ~0.2 s (≈ stiffness 2000, damping 78, unit mass).
+- [O live] Bubble: white 354 × 65 pt, centred on the page, its bottom 36.5 pt above the page's bottom, ~17 pt corners,
+ a 1 px pink → blue rim, "Click or drag to capture a portion of this page" / "Drag to capture a portion of this page"
+ in 14 pt semibold OverlayBubbleText (#3405 94, reads ~78 %). Around it a dark tinted glow (163 grey → 155,147,148 left,
+ 140,143,156 right, gone ~90 pt out), slowly moving. It fades in over ~0.16 s.
+- [O live] Pointers: a dark camera with a white outline over a clickable element; a crosshair with the camera at its
+ top right elsewhere and while dragging.
+- [O live] A first-time tip at the top right: "Next time, hold ⇧⌘ and drag your mouse to capture any time."
+- [O live] After a drag: the capture stays lit with its ring; a menu 273 × 354 pt, 4.5 pt right of the ring, tops level,
+ ~10 pt corners, fill (18,15,44) (Background, dark) even on a light theme: "Send To…" field (13–42.5 pt, white 7 %),
+ rows 40 pt apart (Save to Library ○, Copy, Save…, Send via iMessage…), hairline, Edit, Retake, hairline, New Easel.
+ Symbols 30 % white centred 25 pt in, 14 pt medium text 90 % white from 41 pt; hairlines 10 pt in from both sides.
+ The partial capture does not touch the clipboard by itself. First Esc left the menu up, the second ended the mode.
+- [?] A scripted HID click on an element did not capture (no menu after 0.6 s), so the click result, Copy's toast text
+ and Retake were not observed. Arc's strings have "Confirmation toast when copying a captured image" (text inline).
+- Cra (CaptureOverlay, ContentCapture in CraCore): the same mode over a Page.captureScreenshot picture in a panel over
+ the page; picker run in Cra's isolated world; Copy / Save… / Send via iMessage… / Retake (no Easels, Library Media or
+ Edit in Cra); Copy shows "Screenshot Copied to Clipboard"; the macOS screenshot sound plays when a capture is taken.