Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
c8ca171
fix(capture): Never leave a truncated capture under its final name
epilande Nov 3, 2026
7d38d1b
fix(capture): Say which part of a capture failed, and never fail sile…
epilande Nov 3, 2026
0d5ca88
fix(url): Never capture from an annotate:// link
epilande Nov 3, 2026
0295347
fix(settings): Show why Show in Finder couldn't create the capture fo…
epilande Nov 3, 2026
e48ceb4
test(capture): Check capture ordering and Settings close handlers exa…
epilande Nov 3, 2026
c8dcbbc
feat(capture): Add Capture Area
epilande Nov 3, 2026
80e5928
docs(readme): Document Capture Area and when capture needs Screen Rec…
epilande Nov 3, 2026
10ba917
fix(capture): Keep Always-On drawings through Capture Area
epilande Nov 3, 2026
30f12d3
fix(capture): Show the crosshair over an active cursor style
epilande Nov 3, 2026
6fe54cf
test(capture): Render the area picker and check its pixels
epilande Nov 3, 2026
e9303ba
refactor(capture): Remove the unused CaptureDelivery.destination
epilande Nov 3, 2026
3ce78a2
fix(capture): Show the crosshair while picking with a cursor style on
epilande Nov 3, 2026
f26228c
feat(capture): Add a debug switch that makes every capture save fail
epilande Nov 3, 2026
b492133
fix(capture): Keep the crosshair when another display's overlay refre…
epilande Nov 3, 2026
960d9f7
fix(capture): Keep the cursor style's window in place while picking
epilande Nov 3, 2026
2ffb545
fix(capture): Set the crosshair on every pointer move while picking
epilande Nov 3, 2026
208f722
docs: Remove the screenshot capture design spec
epilande Nov 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ Neither needs any interaction. Tests create real AppKit windows, so run them fro

Testing Shortcuts actions end to end needs a build signed with an Apple Development certificate. In the #135 live check, an ad-hoc signed Debug build (Xcode's Sign to Run Locally) listed the actions in Shortcuts, but each one failed with "Shortcuts couldn't communicate with the app". Quit the installed Annotate first, since Shortcuts finds the app by bundle ID.

To check how a failed capture save is reported (the HUD, or the alert with Hide Tool Feedback on), launch a Debug build with `--fail-capture-saves`, for example `open build/dd/Build/Products/Debug/Annotate.app --args --fail-capture-saves`. Every save fails and the clipboard copy still works. `open` passes the argument only when the app isn't already running.

SwiftLint runs in CI through the SwiftLintPlugins package. With `strict: true`, any violation that isn't recorded in `.swiftlint-baseline.json` fails the run, warnings included:

```sh
Expand Down
20 changes: 15 additions & 5 deletions Annotate/AnnotateCommand.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import Cocoa

/// An action other apps can trigger, from Shortcuts actions or `annotate://` links.
/// Each command runs the same `AppDelegate` code the menu and shortcuts do, then shows the
/// on-screen HUD on any open overlay.
/// An action other apps can trigger, from Shortcuts actions or `annotate://` links (except
/// the ones `runsFromLinks` leaves out). Each command runs the same `AppDelegate` code the menu
/// and shortcuts do, then shows the on-screen HUD on any open overlay.
enum AnnotateCommand: Hashable, Sendable {
case toggle
case show
Expand All @@ -16,7 +16,8 @@ enum AnnotateCommand: Hashable, Sendable {
case toolbar(CommandSwitch)
case fade(CommandSwitch)
case board(CommandSwitch)
/// Saves an image of the display with its annotations and copies it to the clipboard.
/// Saves an image of the display, or of an area the user drags out, with its annotations
/// and copies it to the clipboard. Never runs from a link.
case capture(CaptureScope)

/// Whether running a command changed anything.
Expand All @@ -26,6 +27,14 @@ enum AnnotateCommand: Hashable, Sendable {
case noOp
}

/// Whether an `annotate://` link may run the command. Any web page or app can open a link,
/// so links never run a capture, which reads the screen and writes the clipboard. Shortcuts,
/// the menu, and the keyboard still capture.
var runsFromLinks: Bool {
if case .capture = self { return false }
return true
}

// MARK: - Path form

/// The command's stable string form, `/<command>[/<value>]`, such as `/show`, `/tool/arrow`,
Expand Down Expand Up @@ -142,7 +151,8 @@ enum AnnotateCommand: Hashable, Sendable {
icon: board.currentBoardType == .blackboard ? "⬛" : "⬜")
return enabled == current ? .noOp : .ran
case .capture(let scope):
// The capture finishes later and reports itself on the overlay.
// The capture finishes later and reports itself on the overlay. Capture Area
// first waits for the user to drag out the area.
appDelegate.capture(scope)
return .ran
}
Expand Down
166 changes: 151 additions & 15 deletions Annotate/AppDelegate+Capture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,52 @@ import os

private let log = Logger(subsystem: "com.epilande.Annotate", category: "Capture")

/// Capture Screen from the menu, the overlay shortcut, and `AnnotateCommand.capture`: picks the
/// display, reads what its overlay shows, and reports the result on that overlay.
/// Capture Screen and Capture Area from the menu, the overlay shortcuts, and
/// `AnnotateCommand.capture`: picks the display, reads what its overlay shows, and reports the
/// result on that overlay.
extension AppDelegate {
/// The display a capture saves: the key interactive overlay's, else the one under the
/// pointer, else the main display.
static func captureTarget<Display>(keyOverlay: Display?, pointer: Display?, main: Display?) -> Display? {
keyOverlay ?? pointer ?? main
}

/// Where captures go: a file in `folder` and the clipboard. In a debug build launched with
/// `FileSink.failSavesArgument`, every save fails.
static func captureSinks(
folder: URL = FileSink.defaultFolder,
pasteboard: NSPasteboard = .general,
arguments: [String] = ProcessInfo.processInfo.arguments
) -> [CaptureSink] {
var file = FileSink(folder: folder)
#if DEBUG
if arguments.contains(FileSink.failSavesArgument) {
log.notice("Capture saves fail on purpose: launched with \(FileSink.failSavesArgument, privacy: .public)")
file.writeBytes = { _, _ in throw FileSink.ForcedSaveFailure() }
}
#endif
return [file, ClipboardSink(pasteboard: pasteboard)]
}

var captureTargetScreen: NSScreen? {
let keyOverlay = alwaysOnMode
? nil : overlayWindows.first { $0.value.isVisible && $0.value.isKeyWindow }?.key
return Self.captureTarget(keyOverlay: keyOverlay, pointer: getCurrentScreen(), main: NSScreen.main)
}

/// The display Capture Area picks on: the key interactive overlay's, else the open overlay
/// under the pointer, else any open overlay.
private var areaTargetScreen: NSScreen? {
let open = overlayWindows.filter { $0.value.isVisible }
if let key = open.first(where: { $0.value.isKeyWindow })?.key { return key }
if let pointer = getCurrentScreen(), open[pointer] != nil { return pointer }
return NSScreen.screens.first { open[$0] != nil }
}

func capture(_ scope: CaptureScope) {
switch scope {
case .screen: captureScreen()
case .area: captureArea()
}
}

Expand All @@ -32,12 +60,86 @@ extension AppDelegate {
return
}
let overlay = overlayWindows[screen]
let request = CaptureRequest(
display: display,
scene: overlay.flatMap { $0.isVisible ? captureScene(of: $0) : nil },
hostTime: CACurrentMediaTime(),
date: Date())
startCapture(
CaptureRequest(
display: display,
scene: overlay.flatMap { $0.isVisible ? captureScene(of: $0) : nil },
hostTime: CACurrentMediaTime(),
date: Date()),
on: overlay)
}

/// Lets the user drag out part of a display, then saves it with its board and annotations
/// and copies it, as Capture Screen does. The picker needs the interactive overlay, so with
/// none open, including in Always-On, this opens it first. The fade holds while picking,
/// and the capture shows each annotation at the fade the picker showed.
@objc func captureArea() {
// Without Screen Recording the drag would come to nothing, so ask before anything opens.
// From Always-On, the Screen Recording flow brings Always-On back afterwards, drawings
// and all.
let board = BoardManager.shared
if !captureService.source.canCapture,
!CaptureScene.boardCoversScreen(board.appearance, opacity: CGFloat(board.opacity))
{
showScreenRecordingOff(on: areaTargetScreen.flatMap { overlayWindows[$0] })
return
}
var heldAlwaysOnFade: OverlayWindow?
if !isInteractiveOverlayOpen {
// Always-On annotations are on screen, so the overlay opening over them keeps them,
// even with Clear Drawings on Start, and keeps Always-On's Persist fade until the
// picker closes, or leaving Always-On would expire the older ones at once.
if alwaysOnMode, let screen = getCurrentScreen(), let overlay = overlayWindows[screen] {
overlaysKeepingDrawings.insert(ObjectIdentifier(overlay))
overlaysHoldingAlwaysOnFade.insert(ObjectIdentifier(overlay))
heldAlwaysOnFade = overlay
}
showInteractiveOverlay()
}
let opened = beginAreaPicker(releasingHeldFadeOf: heldAlwaysOnFade)
if !opened, let heldAlwaysOnFade {
releaseHeldAlwaysOnFade(of: heldAlwaysOnFade)
}
}

/// Opens the picker on the target display, and returns whether it opened. When it does,
/// closing it in any way releases `held`'s Always-On fade.
private func beginAreaPicker(releasingHeldFadeOf held: OverlayWindow?) -> Bool {
guard let screen = areaTargetScreen, let overlay = overlayWindows[screen],
let display = DisplayInfo(screen: screen)
else {
log.error("No overlay to pick an area on")
return false
}
guard !overlay.isRegionPickerOpen else { return false }
// The picker reads Escape from its own overlay, and another display's may be key.
overlay.makeKeyAndOrderFront(nil)
let onDismiss: () -> Void = { [weak self] in
guard let self, let held else { return }
self.releaseHeldAlwaysOnFade(of: held)
}
return overlay.beginRegionPicker(onDismiss: onDismiss) { [weak self, weak overlay] rect in
guard let self, let overlay else { return }
// Runs before the picker closes, so the scene's fade clock is still frozen.
self.startCapture(
CaptureRequest(
display: display,
region: .rect(fromViewRect: rect, displayHeight: display.frame.height),
scene: self.captureScene(of: overlay),
hostTime: CACurrentMediaTime(),
date: Date()),
on: overlay)
}
}

/// Gives an overlay Capture Area opened from Always-On its Fade Mode setting back. Back in
/// Always-On, as when its shortcut ended the pick, Persist stays as Always-On wants.
func releaseHeldAlwaysOnFade(of overlay: OverlayWindow) {
guard overlaysHoldingAlwaysOnFade.remove(ObjectIdentifier(overlay)) != nil, !alwaysOnMode else { return }
overlay.overlayView.fadeMode = settings[.fadeMode]
}

private func startCapture(_ request: CaptureRequest, on overlay: OverlayWindow?) {
// Each capture waits for the one before it, so captures finish in the order they were
// asked for: an older image never replaces a newer one on the clipboard or in the HUD,
// and every capture still gets its own file. The scene above is already taken, so the
Expand All @@ -53,7 +155,7 @@ extension AppDelegate {
self?.showScreenRecordingOff(on: overlay)
} catch {
log.error("Capture failed: \(error.localizedDescription)")
self?.reportCaptureProblem("Capture Failed", icon: "⚠️", on: overlay)
self?.reportCaptureProblem(.failed, on: overlay)
}
}
}
Expand All @@ -74,22 +176,29 @@ extension AppDelegate {
now: view.fadeClock())
}

/// Success shows on the overlay, if it is open. When one destination failed, says which,
/// even with the overlay closed.
private func reportCapture(_ result: CaptureResult, on overlay: OverlayWindow?) {
if let file = result.savedFile {
if let copyError = result.failure(of: .clipboard) {
reportCaptureProblem(.copyFailed(savedAs: file, error: copyError), on: overlay)
return
}
guard let overlay, overlay.isVisible else { return }
overlay.showToggleFeedback("Saved \(file.lastPathComponent)", icon: "📸")
} else if result.copiedToClipboard {
reportCaptureProblem("Couldn't Save. Copied to Clipboard", icon: "📋", on: overlay)
reportCaptureProblem(.saveFailed(error: result.failure(of: .file)), on: overlay)
}
}

/// On the overlay when it is open. Otherwise, as from the status menu with the overlay
/// closed, an alert, so a failed capture is never silent.
private func reportCaptureProblem(_ message: String, icon: String, on overlay: OverlayWindow?) {
if let overlay, overlay.isVisible {
overlay.showToggleFeedback(message, icon: icon)
/// On the overlay's HUD when it is open and showing feedback. Otherwise an alert: from the
/// status menu with the overlay closed, or with Hide Tool Feedback on, a failed capture is
/// never silent.
private func reportCaptureProblem(_ problem: CaptureProblem, on overlay: OverlayWindow?) {
if let overlay, overlay.isVisible, !settings[.hideToolFeedback] {
overlay.showToggleFeedback(problem.title, icon: problem.icon)
} else {
showCaptureProblemAlert(message)
showCaptureProblemAlert(problem.title, problem.detail)
}
}

Expand Down Expand Up @@ -170,6 +279,33 @@ extension AppDelegate {
}
}

/// A capture that went wrong, in whole or in part: a short title for the HUD and the alert,
/// and the alert's detail.
struct CaptureProblem: Equatable {
let title: String
let icon: String
let detail: String

static let failed = CaptureProblem(
title: "Capture Failed", icon: "⚠️", detail: "Annotate couldn't finish the capture. Try again in a moment.")

static func copyFailed(savedAs file: URL, error: Error) -> CaptureProblem {
CaptureProblem(
title: "Couldn't Copy. Saved \(file.lastPathComponent)",
icon: "⚠️",
detail: "The image was saved, but Annotate couldn't copy it to the clipboard. \(error.localizedDescription)")
}

static func saveFailed(error: Error?) -> CaptureProblem {
CaptureProblem(
title: "Couldn't Save. Copied to Clipboard",
icon: "📋",
detail: ["The image is on the clipboard, but Annotate couldn't save it.", error?.localizedDescription]
.compactMap { $0 }
.joined(separator: " "))
}
}

/// The macOS privacy prompt, which asks for Screen Recording among other permissions. Another
/// process shows it, `universalAccessAuthWarn`, and its windows can be found by owner without
/// any permission.
Expand Down
40 changes: 30 additions & 10 deletions Annotate/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,26 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem
/// Created as launch starts, before launch or any link can activate the app.
var linkFocusHandoff: LinkFocusHandoff?

/// Makes Capture Screen's images. Tests swap in one with a stub source, a temporary
/// folder, and a private pasteboard.
lazy var captureService = CaptureService(
source: ScreenSampler.shared,
sinks: [FileSink(folder: FileSink.defaultFolder), ClipboardSink()])
/// Makes Capture Screen's and Capture Area's images. Tests swap in one with a stub source,
/// a temporary folder, and a private pasteboard.
lazy var captureService = CaptureService(source: ScreenSampler.shared, sinks: Self.captureSinks())
/// The latest capture. The next one waits for it, and tests await it.
var captureTask: Task<Void, Never>?
/// How long the Screen Recording HUD stays up before the overlay closes for Settings.
var screenRecordingNoticeDelay: TimeInterval = 1.5
/// Reports a capture problem when no overlay is open to show it on. Tests replace it.
var showCaptureProblemAlert: (_ message: String) -> Void = { message in
/// Reports a capture problem when no overlay HUD can show it. Tests replace it.
var showCaptureProblemAlert: (_ message: String, _ detail: String) -> Void = { message, detail in
NSApp.activate(ignoringOtherApps: true)
let alert = NSAlert()
alert.alertStyle = .warning
alert.messageText = message
alert.informativeText = "Annotate couldn't finish the capture. Try again in a moment."
alert.informativeText = detail
// With Hide Tool Feedback on, an overlay can be open, and it sits above modal panels.
// `runModal` resets the level as it starts; the main queue drains inside the modal
// session, so the raise lands after that.
DispatchQueue.main.async {
alert.window.level = NSWindow.Level(rawValue: OverlayWindow.elevatedLevel.rawValue + 1)
}
alert.runModal()
}
/// Whether a macOS privacy prompt is on screen. Tests replace it.
Expand All @@ -63,6 +67,10 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem
/// Overlays closed by the app rather than the user, which keep their drawings the next
/// time they open even with Clear Drawings on Start.
var overlaysKeepingDrawings: Set<ObjectIdentifier> = []
/// Overlays Capture Area opened from Always-On. They keep Always-On's Persist fade until
/// the picker closes, so drawings Always-On still shows past their fade stay for the pick
/// and the capture.
var overlaysHoldingAlwaysOnFade: Set<ObjectIdentifier> = []
/// Opens Settings to a pane. `requestingScreenRecording` asks for access once the pane
/// shows, and `onClose` runs when the Settings window closes. Tests replace it so no
/// Settings window opens.
Expand Down Expand Up @@ -397,6 +405,11 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem
title: "Capture Screen",
action: #selector(captureScreen),
keyEquivalent: ""))
menu.addItem(
NSMenuItem(
title: "Capture Area",
action: #selector(captureArea),
keyEquivalent: ""))

menu.addItem(NSMenuItem.separator())

Expand Down Expand Up @@ -890,7 +903,8 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem
overlayWindow.overlayView.isReadOnlyMode = false
overlayWindow.updateToolbarVisibility()

overlayWindow.overlayView.fadeMode = settings[.fadeMode]
overlayWindow.overlayView.fadeMode =
overlaysHoldingAlwaysOnFade.contains(ObjectIdentifier(overlayWindow)) ? false : settings[.fadeMode]
overlayWindow.overlayView.fadeDelay = settings[.fadeDelay]
overlayWindow.overlayView.startFadeLoopIfNeeded()
}
Expand Down Expand Up @@ -1015,6 +1029,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem
case #selector(toggleToolbar): action = .toggleToolbar
case #selector(clearAllAnnotations): action = .clearAll
case #selector(captureScreen): action = .captureScreen
case #selector(captureArea): action = .captureArea
default:
continue
}
Expand Down Expand Up @@ -1306,7 +1321,12 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem
@objc func cursorHighlightStateChanged() {
updateAllCursorHighlightWindows()
CursorHighlightManager.shared.updateCursorVisibility()
overlayWindows.values.forEach { window in
// Every overlay sets the one system cursor, whichever display it is on, so the last
// one wins. An overlay with a cursor override, as Capture Area's picker sets, goes
// last: otherwise another display's I-beam or hidden cursor would replace the crosshair.
let windows = Array(overlayWindows.values)
let overriding = windows.filter { $0.overlayView.cursorOverride != nil }
for window in windows.filter({ $0.overlayView.cursorOverride == nil }) + overriding {
window.overlayView.updateCursor()
window.overlayView.window?.invalidateCursorRects(for: window.overlayView)
}
Expand Down
Loading
Loading