From c8ca1713dd84599ac07121dc82b6c8da10a8f080 Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Mon, 2 Nov 2026 23:47:53 -0800 Subject: [PATCH 01/17] fix(capture): Never leave a truncated capture under its final name FileSink wrote the PNG straight to its final name, so a write that failed partway, such as on a full disk, left a cut-off image that looked like a capture. The bytes now go to a hidden temporary file in the same folder and are moved into place whole. The move refuses to overwrite, so the " (2)" retry on a name collision works as before, and the temporary file is removed whatever happens. --- Annotate/CaptureSinks.swift | 28 +++++++++++++++----- AnnotateTests/CaptureTests.swift | 44 ++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/Annotate/CaptureSinks.swift b/Annotate/CaptureSinks.swift index 745f766..dfa85ae 100644 --- a/Annotate/CaptureSinks.swift +++ b/Annotate/CaptureSinks.swift @@ -43,16 +43,27 @@ struct FileSink: CaptureSink { attempt <= 1 ? "\(baseName).png" : "\(baseName) (\(attempt)).png" } - /// Writes `data` under the first free name, creating the folder if needed. Each attempt - /// refuses to overwrite, so two captures in the same second never replace each other. - /// Runs off the main actor. - nonisolated static func write(_ data: Data, baseName: String, in folder: URL) async throws -> URL { - try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + /// Writes `data` under the first free name, creating the folder if needed. The bytes go + /// to a hidden temporary file in the same folder first and are moved into place whole, so + /// a write that fails partway never leaves a truncated image under a capture's name. Each + /// move refuses to overwrite, so two captures in the same second never replace each other. + /// Runs off the main actor. `writeBytes` writes the temporary file; tests make it fail + /// partway. + nonisolated static func write( + _ data: Data, baseName: String, in folder: URL, + writeBytes: @Sendable (Data, URL) throws -> Void = { try $0.write(to: $1, options: .withoutOverwriting) } + ) async throws -> URL { + let fileManager = FileManager.default + try fileManager.createDirectory(at: folder, withIntermediateDirectories: true) + let temporary = folder.appendingPathComponent(temporaryFileName(), isDirectory: false) + // Whatever happens, the temporary file goes; after a move there is nothing left to remove. + defer { try? fileManager.removeItem(at: temporary) } + try writeBytes(data, temporary) var attempt = 1 while true { let url = folder.appendingPathComponent(fileName(baseName, attempt: attempt), isDirectory: false) do { - try data.write(to: url, options: .withoutOverwriting) + try fileManager.moveItem(at: temporary, to: url) return url } catch CocoaError.fileWriteFileExists where attempt < maxAttempts { attempt += 1 @@ -60,6 +71,11 @@ struct FileSink: CaptureSink { } } + /// A hidden name no capture uses, unique per write. + nonisolated static func temporaryFileName() -> String { + ".Annotate-\(UUID().uuidString).png.tmp" + } + nonisolated private static let maxAttempts = 1000 } diff --git a/AnnotateTests/CaptureTests.swift b/AnnotateTests/CaptureTests.swift index 1621cb4..3c02167 100644 --- a/AnnotateTests/CaptureTests.swift +++ b/AnnotateTests/CaptureTests.swift @@ -429,6 +429,50 @@ final class CaptureTests: XCTestCase { XCTAssertEqual(third.lastPathComponent, "Annotate X (3).png") XCTAssertEqual(try Data(contentsOf: first), Data([1])) XCTAssertEqual(try Data(contentsOf: second), Data([2])) + XCTAssertEqual( + try FileManager.default.contentsOfDirectory(atPath: folder.path).sorted(), + ["Annotate X (2).png", "Annotate X (3).png", "Annotate X.png"], + "No temporary file is left behind") + } + + func testWriteGoesThroughAHiddenTemporaryFileInTheSameFolder() { + let name = FileSink.temporaryFileName() + XCTAssertTrue(name.hasPrefix("."), "Finder hides it while it is written") + XCTAssertFalse(name.hasSuffix(".png"), "Nothing mistakes it for a capture") + XCTAssertNotEqual(name, FileSink.temporaryFileName()) + } + + func testWriteThatFailsPartwayLeavesNoTruncatedCapture() async throws { + let folder = try temporaryFolder() + struct DiskFull: Error {} + + do { + _ = try await FileSink.write(Data([1, 2, 3, 4]), baseName: "Annotate X", in: folder) { data, url in + // Half the bytes land, then the disk fills up. + try data.prefix(2).write(to: url) + throw DiskFull() + } + XCTFail("Expected the write to fail") + } catch is DiskFull {} + + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: folder.path), []) + } + + func testFailedWriteLeavesNoFileBehind() async throws { + let folder = try temporaryFolder() + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + // A read-only folder: the temporary file can't be written, so nothing may appear. + try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: folder.path) + addTeardownBlock { + try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: folder.path) + } + + do { + _ = try await FileSink.write(Data([1]), baseName: "Annotate X", in: folder) + XCTFail("Expected the write to fail") + } catch {} + + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: folder.path), []) } func testDefaultFolderIsPicturesAnnotateInTheRealHome() { From 7d38d1b67ad5e0016315f156f1fe2b60e07d60a2 Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Mon, 2 Nov 2026 23:49:05 -0800 Subject: [PATCH 02/17] fix(capture): Say which part of a capture failed, and never fail silently A capture that saved its file but couldn't copy it to the clipboard reported only "Saved", and said nothing at all with the overlay closed. Each sink now names its destination, so the result says which one failed. A failed copy shows "Couldn't Copy. Saved ", and a failed save keeps "Couldn't Save. Copied to Clipboard" with an alert that says the save failed instead of "couldn't finish the capture". With Hide Tool Feedback on, the HUD that carried a failure never showed. Problems now go to an alert whenever no HUD can show them: the overlay is closed or tool feedback is hidden. The alert is raised above the overlay, which otherwise sits over modal panels. A successful capture still shows only the HUD. --- Annotate/AppDelegate+Capture.swift | 50 ++++++++++++++++---- Annotate/AppDelegate.swift | 12 +++-- Annotate/Capture.swift | 35 ++++++++++++-- Annotate/CaptureSinks.swift | 4 ++ AnnotateTests/AnnotateCommandTests.swift | 59 +++++++++++++++++++++++- AnnotateTests/CaptureTests.swift | 27 ++++++++++- docs/screenshot-capture-spec.md | 4 ++ 7 files changed, 174 insertions(+), 17 deletions(-) diff --git a/Annotate/AppDelegate+Capture.swift b/Annotate/AppDelegate+Capture.swift index 0b8a378..1a50426 100644 --- a/Annotate/AppDelegate+Capture.swift +++ b/Annotate/AppDelegate+Capture.swift @@ -53,7 +53,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) } } } @@ -74,22 +74,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) } } @@ -170,6 +177,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. diff --git a/Annotate/AppDelegate.swift b/Annotate/AppDelegate.swift index eace345..b161899 100644 --- a/Annotate/AppDelegate.swift +++ b/Annotate/AppDelegate.swift @@ -41,13 +41,19 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem var captureTask: Task? /// 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. diff --git a/Annotate/Capture.swift b/Annotate/Capture.swift index 37400ba..ec242d4 100644 --- a/Annotate/Capture.swift +++ b/Annotate/Capture.swift @@ -106,14 +106,36 @@ struct Capture { enum CaptureDelivery: Equatable, Sendable { case file(URL) case clipboard + + var destination: CaptureDestination { + switch self { + case .file: return .file + case .clipboard: return .clipboard + } + } +} + +/// The kinds of place a capture can go. +enum CaptureDestination: Equatable, Sendable { + case file + case clipboard } /// A destination for finished captures. @MainActor protocol CaptureSink { + /// What `deliver` returns on success, so a failure can say what didn't happen. + var destination: CaptureDestination { get } + func deliver(_ capture: Capture, png: Data) async throws -> CaptureDelivery } +/// A sink that threw, and what it threw. +struct CaptureSinkFailure { + let destination: CaptureDestination + let error: Error +} + /// Why a capture produced nothing. enum CaptureError: Error, Equatable { /// Screen Recording is not granted, and the capture needs screen pixels. @@ -129,13 +151,18 @@ enum CaptureError: Error, Equatable { struct CaptureResult { let capture: Capture let deliveries: [CaptureDelivery] - let failures: [Error] + let failures: [CaptureSinkFailure] var savedFile: URL? { deliveries.lazy.compactMap { if case .file(let url) = $0 { return url } else { return nil } }.first } var copiedToClipboard: Bool { deliveries.contains(.clipboard) } + + /// The error a sink of `destination` threw, if one did. + func failure(of destination: CaptureDestination) -> Error? { + failures.first { $0.destination == destination }?.error + } } /// Makes captures: takes the screen pixels, composites the scene over them, encodes a PNG, @@ -181,16 +208,16 @@ final class CaptureService { } var deliveries: [CaptureDelivery] = [] - var failures: [Error] = [] + var failures: [CaptureSinkFailure] = [] for sink in sinks { do { deliveries.append(try await sink.deliver(capture, png: png)) } catch { log.error("Capture sink failed: \(error.localizedDescription)") - failures.append(error) + failures.append(CaptureSinkFailure(destination: sink.destination, error: error)) } } - if deliveries.isEmpty, let first = failures.first { throw first } + if deliveries.isEmpty, let first = failures.first { throw first.error } return CaptureResult(capture: capture, deliveries: deliveries, failures: failures) } } diff --git a/Annotate/CaptureSinks.swift b/Annotate/CaptureSinks.swift index dfa85ae..a4c64a7 100644 --- a/Annotate/CaptureSinks.swift +++ b/Annotate/CaptureSinks.swift @@ -5,6 +5,8 @@ import AppKit struct FileSink: CaptureSink { var folder: URL + var destination: CaptureDestination { .file } + /// `~/Pictures/Annotate`. Pictures is reachable through the app's Pictures entitlement /// and, unlike Desktop, Documents, and Downloads, has no first-access prompt that would /// open under the overlay. @@ -83,6 +85,8 @@ struct FileSink: CaptureSink { struct ClipboardSink: CaptureSink { var pasteboard: NSPasteboard = .general + var destination: CaptureDestination { .clipboard } + func deliver(_ capture: Capture, png: Data) async throws -> CaptureDelivery { pasteboard.clearContents() guard pasteboard.setData(png, forType: .png) else { throw CocoaError(.fileWriteUnknown) } diff --git a/AnnotateTests/AnnotateCommandTests.swift b/AnnotateTests/AnnotateCommandTests.swift index b6c512e..c84618b 100644 --- a/AnnotateTests/AnnotateCommandTests.swift +++ b/AnnotateTests/AnnotateCommandTests.swift @@ -13,6 +13,8 @@ final class AnnotateCommandTests: XCTestCase { var privacyPromptUp = false /// Messages a capture reported in an alert, which tests record instead of showing. var captureProblemAlerts: [String] = [] + /// The detail text of each alert in `captureProblemAlerts`. + var captureProblemDetails: [String] = [] override func setUp() { super.setUp() @@ -496,7 +498,11 @@ final class AnnotateCommandTests: XCTestCase { privacyPromptUp = false appDelegate.isPrivacyPromptOnScreen = { [unowned self] in self.privacyPromptUp } captureProblemAlerts = [] - appDelegate.showCaptureProblemAlert = { [unowned self] in self.captureProblemAlerts.append($0) } + captureProblemDetails = [] + appDelegate.showCaptureProblemAlert = { [unowned self] message, detail in + self.captureProblemAlerts.append(message) + self.captureProblemDetails.append(detail) + } appDelegate.privacyPromptPollInterval = 0.02 appDelegate.captureService = CaptureService( source: source ?? StubDisplayCapturing(canCapture: canCapture, snapshotImage: snapshot), @@ -806,6 +812,19 @@ final class AnnotateCommandTests: XCTestCase { await appDelegate.captureTask?.value XCTAssertEqual(captureProblemAlerts, ["Capture Failed"]) + XCTAssertEqual(captureProblemDetails, ["Annotate couldn't finish the capture. Try again in a moment."]) + } + + func testCaptureFailureWithToolFeedbackHiddenStillShowsAnAlert() async throws { + try useStubCapture(source: StubDisplayCapturing(snapshotImage: nil)) + testDefaults.settings[.hideToolFeedback] = true + run(.show) + + appDelegate.captureScreen() + await appDelegate.captureTask?.value + + XCTAssertNil(feedbackText(on: overlay)) + XCTAssertEqual(captureProblemAlerts, ["Capture Failed"], "A failure is never silent") } func testCaptureFailureWithTheOverlayOpenStaysOnTheOverlay() async throws { @@ -837,6 +856,44 @@ final class AnnotateCommandTests: XCTestCase { XCTAssertNotNil(pasteboard.data(forType: .png)) XCTAssertEqual(captureProblemAlerts, ["Couldn't Save. Copied to Clipboard"]) + let detail = try XCTUnwrap(captureProblemDetails.first) + XCTAssertTrue(detail.hasPrefix("The image is on the clipboard, but Annotate couldn't save it."), detail) + XCTAssertFalse(detail.contains("couldn't finish the capture"), "Only the save failed") + } + + /// Saves to a temporary folder while every copy to the clipboard fails. + private func useCaptureWhoseCopyFails() throws -> URL { + try useStubCapture() + let folder = FileManager.default.temporaryDirectory + .appendingPathComponent("AnnotateCommandTests-\(UUID().uuidString)", isDirectory: true) + addTeardownBlock { try? FileManager.default.removeItem(at: folder) } + appDelegate.captureService = CaptureService( + source: StubDisplayCapturing(snapshotImage: CaptureTestImages.solid(width: 32, height: 20, RGBA(r: 0, g: 0, b: 255, a: 255))), + sinks: [FileSink(folder: folder), FailingSink(destination: .clipboard)]) + return folder + } + + func testFailedCopyWithTheOverlayClosedIsReported() async throws { + let folder = try useCaptureWhoseCopyFails() + + appDelegate.captureScreen() + await appDelegate.captureTask?.value + + let file = try XCTUnwrap(try FileManager.default.contentsOfDirectory(atPath: folder.path).first) + XCTAssertEqual(captureProblemAlerts, ["Couldn't Copy. Saved \(file)"]) + XCTAssertTrue(try XCTUnwrap(captureProblemDetails.first).hasPrefix("The image was saved, but Annotate couldn't copy it")) + } + + func testFailedCopyWithTheOverlayOpenSaysSoOnTheOverlay() async throws { + let folder = try useCaptureWhoseCopyFails() + run(.show) + + appDelegate.captureScreen() + await appDelegate.captureTask?.value + + let file = try XCTUnwrap(try FileManager.default.contentsOfDirectory(atPath: folder.path).first) + XCTAssertEqual(feedbackText(on: overlay), "⚠️ Couldn't Copy. Saved \(file)") + XCTAssertTrue(captureProblemAlerts.isEmpty) } func testShareableContentListsAppsWhoseWindowsAreOffScreen() { diff --git a/AnnotateTests/CaptureTests.swift b/AnnotateTests/CaptureTests.swift index 3c02167..d3dc7af 100644 --- a/AnnotateTests/CaptureTests.swift +++ b/AnnotateTests/CaptureTests.swift @@ -51,6 +51,15 @@ final class GatedDisplayCapturing: DisplayCapturing { } } +/// A sink that always throws, standing in for a destination that fails. +struct FailingSink: CaptureSink { + let destination: CaptureDestination + + func deliver(_ capture: Capture, png: Data) async throws -> CaptureDelivery { + throw CocoaError(.fileWriteUnknown) + } +} + /// An RGBA color with 0-255 components. struct RGBA: Equatable, CustomStringConvertible { var r: Int, g: Int, b: Int, a: Int @@ -397,10 +406,26 @@ final class CaptureTests: XCTestCase { XCTAssertNil(result.savedFile) XCTAssertTrue(result.copiedToClipboard) - XCTAssertEqual(result.failures.count, 1) + XCTAssertEqual(result.failures.map(\.destination), [.file]) + XCTAssertNotNil(result.failure(of: .file)) + XCTAssertNil(result.failure(of: .clipboard)) XCTAssertNotNil(pasteboard.data(forType: .png)) } + func testServiceSaysWhichDestinationFailed() async throws { + let folder = try temporaryFolder() + let service = CaptureService( + source: StubDisplayCapturing(snapshotImage: CaptureTestImages.solid(width: 100, height: 50, Self.blue)), + sinks: [FileSink(folder: folder), FailingSink(destination: .clipboard)]) + + let result = try await service.capture(request(display: display(), scene: nil)) + + XCTAssertNotNil(result.savedFile) + XCTAssertFalse(result.copiedToClipboard) + XCTAssertNotNil(result.failure(of: .clipboard)) + XCTAssertNil(result.failure(of: .file)) + } + // MARK: - File naming func testFileNameMirrorsMacOSScreenshots() throws { diff --git a/docs/screenshot-capture-spec.md b/docs/screenshot-capture-spec.md index 4de5e33..fb6aef9 100644 --- a/docs/screenshot-capture-spec.md +++ b/docs/screenshot-capture-spec.md @@ -86,3 +86,7 @@ Settled 2026-11-01 from the open questions. - Full-screen capture in Fade Mode: annotations at their current fade, as shown on screen. - The Redact Screen Recording permission row moves from the Tools pane into the Capture pane. - Capture settings get their own Settings pane, Capture. + +Settled 2026-11-02 in the review of #142. + +- When only the save or only the clipboard copy fails, Annotate says which. Failures show an alert when no overlay HUD can show them, including with Hide Tool Feedback on. From 0d5ca889b671ad2abf05e8384da71c5abeff5068 Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Mon, 2 Nov 2026 23:49:47 -0800 Subject: [PATCH 03/17] fix(url): Never capture from an annotate:// link `annotate://capture/screen` parsed and ran, so any web page or app that could open a link could read the screen and replace the clipboard. The link parser now rejects capture commands with their own reason, logged like any other ignored link. Shortcuts, the status menu, and the overlay shortcut still capture. This changes the approved spec, which planned capture links for PR 5. The spec's Decisions now record it. --- Annotate/AnnotateCommand.swift | 15 ++++++++++++--- Annotate/URLCommands.swift | 5 ++++- AnnotateTests/URLCommandTests.swift | 17 ++++++++++++++++- docs/screenshot-capture-spec.md | 9 +++++---- 4 files changed, 37 insertions(+), 9 deletions(-) diff --git a/Annotate/AnnotateCommand.swift b/Annotate/AnnotateCommand.swift index ec85a07..689ebd3 100644 --- a/Annotate/AnnotateCommand.swift +++ b/Annotate/AnnotateCommand.swift @@ -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 @@ -17,6 +17,7 @@ enum AnnotateCommand: Hashable, Sendable { case fade(CommandSwitch) case board(CommandSwitch) /// Saves an image of the display with its annotations and copies it to the clipboard. + /// Never runs from a link. case capture(CaptureScope) /// Whether running a command changed anything. @@ -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, `/[/]`, such as `/show`, `/tool/arrow`, diff --git a/Annotate/URLCommands.swift b/Annotate/URLCommands.swift index c0a2b81..ccd1e6f 100644 --- a/Annotate/URLCommands.swift +++ b/Annotate/URLCommands.swift @@ -22,11 +22,13 @@ extension AnnotateCommand { case missingCommand = "it names no command" case extraParts = "it has a user, password, port, query, or fragment" case unknownCommand = "its command or value is unknown" + case notFromLinks = "its command never runs from a link" } /// Parses a link such as `annotate://show` or `annotate://tool/arrow`: the host is the command /// and the path its value, matched like `init?(path:)`. Fails for another scheme, a missing - /// command, a user, password, port, query, or fragment, or a path `init?(path:)` rejects. + /// command, a user, password, port, query, or fragment, a path `init?(path:)` rejects, or a + /// command that `runsFromLinks` keeps from links, such as a capture. static func parse(url: URL, scheme: String = AnnotateCommand.urlScheme) -> Result { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return .failure(.unparseable) @@ -39,6 +41,7 @@ extension AnnotateCommand { guard let command = AnnotateCommand(path: host + components.path) else { return .failure(.unknownCommand) } + guard command.runsFromLinks else { return .failure(.notFromLinks) } return .success(command) } diff --git a/AnnotateTests/URLCommandTests.swift b/AnnotateTests/URLCommandTests.swift index 6ead3b4..49c2c4a 100644 --- a/AnnotateTests/URLCommandTests.swift +++ b/AnnotateTests/URLCommandTests.swift @@ -60,7 +60,7 @@ final class URLCommandTests: XCTestCase { } func testEveryCommandRoundTripsThroughALink() throws { - for command in AnnotateCommandTests.everyCommand { + for command in AnnotateCommandTests.everyCommand where command.runsFromLinks { for scheme in ["annotate", "annotate-debug"] { let url = try link("\(scheme):/\(command.path)") XCTAssertEqual(AnnotateCommand(url: url, scheme: scheme), command, url.absoluteString) @@ -110,6 +110,8 @@ final class URLCommandTests: XCTestCase { ("annotate://nope", .unknownCommand), ("annotate://tool/brush", .unknownCommand), ("annotate://tool/arrow/extra", .unknownCommand), + ("annotate://capture/screen", .notFromLinks), + ("ANNOTATE://Capture/Screen/", .notFromLinks), ] for (string, reason) in cases { guard case .failure(let rejection) = AnnotateCommand.parse(url: try link(string), scheme: "annotate") else { @@ -190,6 +192,19 @@ final class URLCommandTests: XCTestCase { XCTAssertEqual(overlay?.isVisible, true, "Links run again once the setting is back on") } + func testCaptureLinksNeverReadTheScreen() throws { + launch() + let source = StubDisplayCapturing(snapshotImage: CaptureTestImages.solid(width: 8, height: 8, RGBA(r: 0, g: 0, b: 255, a: 255))) + appDelegate.captureService = CaptureService(source: source, sinks: []) + try open("annotate-debug://show") + + XCTAssertNil(appDelegate.openCommandURL(try link("annotate-debug://capture/screen"))) + try open("annotate-debug://capture/screen") + + XCTAssertNil(appDelegate.captureTask) + XCTAssertEqual(source.captureCount, 0) + } + func testMalformedLinksChangeNothing() throws { launch() let colorBefore = appDelegate.currentColor diff --git a/docs/screenshot-capture-spec.md b/docs/screenshot-capture-spec.md index fb6aef9..02f7a1f 100644 --- a/docs/screenshot-capture-spec.md +++ b/docs/screenshot-capture-spec.md @@ -6,7 +6,7 @@ Status: approved 2026-11-01, with the open questions settled under Decisions. Wr Capture fits Annotate. It closes the "annotate, capture, share" loop the issue describes, and three quarters of the plumbing exists: `ScreenSampler` already takes ScreenCaptureKit screenshots of one display with Annotate's windows excluded, the command layer runs the same code from menus, Shortcuts, and `annotate://`, and every annotation already carries a monotonic creation time. -**v1 ships:** Capture Screen and Capture Area for one display, PNG to a folder, a copy on the clipboard, an on-overlay confirmation plus a system notification with Show in Finder, a Capture pane in Settings (folder, after-capture destination, notification, Screen Recording status for Capture and Redact), both commands in Shortcuts and `annotate://`, and an opt-in JSON sidecar. +**v1 ships:** Capture Screen and Capture Area for one display, PNG to a folder, a copy on the clipboard, an on-overlay confirmation plus a system notification with Show in Finder, a Capture pane in Settings (folder, after-capture destination, notification, Screen Recording status for Capture and Redact), both commands in Shortcuts (not `annotate://`, see Decisions), and an opt-in JSON sidecar. **Waits:** window crop, stitching several displays, global hotkeys for capture, sidecar on by default, session recording and bundles, and opening an image to annotate. @@ -47,7 +47,7 @@ Timestamps and ids: `creationTime` is `CACurrentMediaTime`, mach host time, and - Full-screen Spaces: display capture sees the full-screen app; the overlay's `.canJoinAllSpaces` means annotations are there too. - macOS 15 and later show a periodic ScreenCaptureKit reminder alert; it will sit under an open overlay until it closes. Already true for Redact; capture widens exposure. -**7. Shortcuts and links.** Yes. `AnnotateCommand.capture(CaptureScope)` with `screen` and `area` gives `annotate://capture/screen` and `annotate://capture/area`, plus Capture Screen and Capture Area intents returning the PNG as an `IntentFile`. Overlay shortcuts `captureScreen` (⌘S) and `captureArea` (⇧⌘S), rebindable, through `newlyEditable`; `s` is free of reserved keys and fixed key equivalents. Status menu items for both. "Open an image to annotate" needs a parameter the link parser rejects by design; when it comes, it is an intent with a file parameter. +**7. Shortcuts and links.** Shortcuts yes, links no (see Decisions). `AnnotateCommand.capture(CaptureScope)` with `screen` and `area` has the paths `/capture/screen` and `/capture/area`, which the link parser rejects, plus Capture Screen and Capture Area intents returning the PNG as an `IntentFile`. Overlay shortcuts `captureScreen` (⌘S) and `captureArea` (⇧⌘S), rebindable, through `newlyEditable`; `s` is free of reserved keys and fixed key equivalents. Status menu items for both. "Open an image to annotate" needs a parameter the link parser rejects by design; when it comes, it is an intent with a file parameter. **8. Stacked PRs.** @@ -55,7 +55,7 @@ Timestamps and ids: `creationTime` is `CACurrentMediaTime`, mach host time, and 2. Capture Screen. `DisplayCapturing`, `Capture`, `CaptureService`, `FileSink`, `ClipboardSink` (the default saves and copies), PNG encode off main, HUD, Capture pane with default folder and the Screen Recording row moved from Tools, `ShortcutKey.captureScreen`, menu item, `AnnotateCommand.capture(.screen)`. Tests: composite pixels against a stub snapshot (board on and off, scale 1 and 2), file naming and collisions, clipboard contents, display selection rule, command outcome. Mac: Retina plus external display, board, fade, Always-On, denied permission flow. 3. Capture Area. `RegionPicker`, fade freeze, crop, `captureArea`, opening the interactive overlay when none is open. Tests: picker geometry and keys, rect normalization, crop math, frozen clock, opening from a hidden or Always-On overlay. Mac: drag on each display, Escape, tiny rects, picker on a display whose overlay is not key, Always-On. 4. Folder, destinations, notification. Entitlement change, bookmark key and stale handling, the after-capture destination setting, notification protocol and stub. Tests: bookmark round trip in a temp directory, stale fallback, destination setting. Mac: a notarized build, pick a folder on an external volume, revoke it, click the notification. -5. Intents and links, README, AGENTS. Tests in `AnnotateCommandTests`, `URLCommandTests`, intent display representations. +5. Intents, README, AGENTS. Tests in `AnnotateCommandTests`, intent display representations. Links stay blocked (PR 3). 6. Sidecar and ids. `CaptureRecord` v1, ids on annotations, the toggle, a schema doc under `docs/`. Tests: golden JSON, coordinate transform, clock fields. **9. Risks.** The renderer extraction is the regression risk; pixel tests and a no-behavior-change rule contain it. Permission UX: the prompt and the macOS 15 reminder both hide under the overlay, so every prompt comes from Settings. Entitlement changes touch notarization; PR 4 needs a signed build check. 5K composites peak around 200 MB; encode off main. CI has no Screen Recording, so nothing in tests may call ScreenCaptureKit, which the protocol enforces. @@ -74,7 +74,7 @@ For the session feature, v1 does differently because of it: a renderer that draw 4. Default folder `~/Pictures/Annotate` with the Pictures entitlement; custom folder by bookmark. 5. Save and copy to the clipboard by default; HUD plus system notification, authorization from Settings only. 6. Sidecar shipped off by default; ids on every annotation. -7. Names Capture Screen and Capture Area, ⌘S and ⇧⌘S, `annotate://capture/`. +7. Names Capture Screen and Capture Area, ⌘S and ⇧⌘S. No `annotate://` links for capture (see Decisions). 8. A sixth Settings pane, Capture, which also takes the Screen Recording row from Tools. ## Decisions @@ -89,4 +89,5 @@ Settled 2026-11-01 from the open questions. Settled 2026-11-02 in the review of #142. +- `annotate://` links never run a capture, Capture Screen or Capture Area. Any web page or app can open a link, and a capture reads the screen and writes the clipboard. The link parser rejects `/capture/...` with its own reason. Shortcuts, the menu, and the keyboard still capture. This replaces the link parts of answers 2, 3, 6, 7, and 8. - When only the save or only the clipboard copy fails, Annotate says which. Failures show an alert when no overlay HUD can show them, including with Hide Tool Feedback on. From 0295347a93f544f52f4a143c4ed871c1437afccb Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Mon, 2 Nov 2026 23:50:08 -0800 Subject: [PATCH 04/17] fix(settings): Show why Show in Finder couldn't create the capture folder Show in Finder ignored a failure to create ~/Pictures/Annotate and opened the missing folder anyway, which did nothing. It now shows the error under the folder in the Capture pane and skips opening it. The message clears on the next success. --- Annotate/CaptureSettingsView.swift | 31 +++++++++++++++++++++++++++--- AnnotateTests/CaptureTests.swift | 22 +++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/Annotate/CaptureSettingsView.swift b/Annotate/CaptureSettingsView.swift index b26ff57..2fb9120 100644 --- a/Annotate/CaptureSettingsView.swift +++ b/Annotate/CaptureSettingsView.swift @@ -3,6 +3,8 @@ import SwiftUI struct CaptureSettingsView: View { var navigation: SettingsNavigation @State private var hasScreenCaptureAccess = ScreenSampler.shared.hasScreenCaptureAccess + /// Why Show in Finder couldn't make the folder, until it next succeeds. + @State private var folderError: String? static let screenCaptureSettingsURL = URL( string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")! @@ -35,6 +37,13 @@ struct CaptureSettingsView: View { Button("Show in Finder", action: showFolder) } } + if let folderError { + Label(folderError, systemImage: "exclamationmark.triangle.fill") + .font(.footnote) + .foregroundStyle(.red) + .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("capture.folderError") + } Text("Capture Screen saves a PNG of the display, with the board and annotations as they appear, to this folder and copies it to the clipboard.") .font(.footnote) .foregroundStyle(.secondary) @@ -108,8 +117,24 @@ struct CaptureSettingsView: View { } private func showFolder() { - let folder = FileSink.defaultFolder - try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) - NSWorkspace.shared.open(folder) + switch Self.prepareFolder(FileSink.defaultFolder) { + case .success(let folder): + folderError = nil + NSWorkspace.shared.open(folder) + case .failure(let error): + folderError = Self.folderErrorMessage(error) + } + } + + /// Creates `folder` if it is missing, so Finder has something to open. + static func prepareFolder(_ folder: URL) -> Result { + Result { + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + return folder + } + } + + static func folderErrorMessage(_ error: Error) -> String { + "Couldn't create the folder. \(error.localizedDescription)" } } diff --git a/AnnotateTests/CaptureTests.swift b/AnnotateTests/CaptureTests.swift index d3dc7af..dfd049a 100644 --- a/AnnotateTests/CaptureTests.swift +++ b/AnnotateTests/CaptureTests.swift @@ -531,6 +531,28 @@ final class CaptureTests: XCTestCase { XCTAssertTrue(ShortcutKey.newlyEditable.contains(.captureScreen)) XCTAssertEqual(ShortcutKey.captureScreen.displayName, "Capture Screen") } + + // MARK: - Capture pane + + func testShowInFinderReportsAFolderItCantCreate() throws { + // A regular file where the folder should be. + let blocker = try temporaryFolder() + try Data().write(to: blocker) + + guard case .failure(let error) = CaptureSettingsView.prepareFolder(blocker) else { + return XCTFail("Expected the folder to fail") + } + XCTAssertTrue(CaptureSettingsView.folderErrorMessage(error).hasPrefix("Couldn't create the folder.")) + + let folder = try temporaryFolder() + guard case .success(let created) = CaptureSettingsView.prepareFolder(folder) else { + return XCTFail("Expected the folder to be created") + } + XCTAssertEqual(created, folder) + var isDirectory: ObjCBool = false + XCTAssertTrue(FileManager.default.fileExists(atPath: folder.path, isDirectory: &isDirectory)) + XCTAssertTrue(isDirectory.boolValue) + } } /// `XCTUnwrap` for an optional produced by an `await`. From e48ceb4575408d53ff229fb5af83ff6f49b18444 Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Mon, 2 Nov 2026 23:50:22 -0800 Subject: [PATCH 05/17] test(capture): Check capture ordering and Settings close handlers exactly The ordering test now asserts that only the first capture has started before the gate opens, so a second capture that runs early fails it even if the clipboard still ends up right. The close-handler test gives each handler its own counter, so one handler running twice and the other not at all no longer adds up to a pass. --- AnnotateTests/AnnotateCommandTests.swift | 1 + AnnotateTests/SettingsViewTests.swift | 16 ++++++++++------ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/AnnotateTests/AnnotateCommandTests.swift b/AnnotateTests/AnnotateCommandTests.swift index c84618b..0f13ceb 100644 --- a/AnnotateTests/AnnotateCommandTests.swift +++ b/AnnotateTests/AnnotateCommandTests.swift @@ -638,6 +638,7 @@ final class AnnotateCommandTests: XCTestCase { run(.capture(.screen)) // Give the second capture time to overtake the held first one if nothing orders them. try await Task.sleep(for: .milliseconds(500)) + XCTAssertEqual(source.captureCount, 1, "The second capture must wait for the first to finish") source.open() await appDelegate.captureTask?.value // Unordered, the held capture would still be running here; let it finish too, so the diff --git a/AnnotateTests/SettingsViewTests.swift b/AnnotateTests/SettingsViewTests.swift index a434bb2..60dcd95 100644 --- a/AnnotateTests/SettingsViewTests.swift +++ b/AnnotateTests/SettingsViewTests.swift @@ -132,20 +132,24 @@ final class SettingsViewTests: XCTestCase { } func testCloseHandlersRunOnceWhenTheWindowCloses() throws { - var closed = 0 - SettingsWindowManager.shared.show(pane: .capture) { closed += 1 } + var firstClosed = 0 + var secondClosed = 0 + SettingsWindowManager.shared.show(pane: .capture) { firstClosed += 1 } // A handler added while the window is already open waits for that window too. - SettingsWindowManager.shared.show { closed += 1 } + SettingsWindowManager.shared.show { secondClosed += 1 } let window = try XCTUnwrap(SettingsWindowManager.shared.settingsWindow) XCTAssertEqual(SettingsWindowManager.shared.navigation.selection, .capture) - XCTAssertEqual(closed, 0) + XCTAssertEqual(firstClosed, 0) + XCTAssertEqual(secondClosed, 0) window.close() - XCTAssertEqual(closed, 2) + XCTAssertEqual(firstClosed, 1) + XCTAssertEqual(secondClosed, 1) SettingsWindowManager.shared.show() SettingsWindowManager.shared.settingsWindow?.close() - XCTAssertEqual(closed, 2, "Handlers run once") + XCTAssertEqual(firstClosed, 1, "Each handler runs once") + XCTAssertEqual(secondClosed, 1, "Each handler runs once") } // MARK: - Dock Icon Tests From c8dcbbc44bf5e2bde158a6d62d7fcd6a880da210 Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Mon, 2 Nov 2026 23:50:45 -0800 Subject: [PATCH 06/17] feat(capture): Add Capture Area Part 3 of the capture plan for #80. Capture Area lets the user drag out part of one display and saves it the way Capture Screen saves the whole display: a PNG in ~/Pictures/Annotate with the board and annotations as they appear, also copied to the clipboard. RegionPicker is a small AppKit view the overlay window installs over its canvas while picking, like the quick picker. It shows a crosshair, dims everything outside the rectangle, and labels the rectangle's size in points. Release picks, and Escape or a right click cancels. A click or a drag under 4 points on a side is ignored and the picker stays open. Every key and mouse event goes to the picker while it is open, so no overlay shortcut fires mid-pick and Escape never reaches the overlay's own Escape handling. It draws through layers, so following the pointer adds no redraw sites, and it knows nothing about the overlay's annotations or about capture. While the picker is open the fade holds: the overlay's fade clock is frozen and the fade loop stops. The capture reads the annotations at that held time, so in Fade Mode an area keeps what was on screen when the drag started. Closing the picker lets the fade run on the real clock again; creation times stay as they are, since undo finds annotations by them. The toolbar moves aside while picking so the whole display can be picked, and comes back after. With no interactive overlay open, including in Always-On, Capture Area opens the overlay under the pointer first, the way the overlay shortcut does. Coming from Always-On, that overlay keeps the drawings that were on screen even with Clear Drawings on Start. Without Screen Recording, it goes straight to the Screen Recording flow before the drag, unless a fully opaque board makes screen pixels unnecessary. CaptureScope gains .area and CaptureRegion gains .rect, in display-local points with a top-left origin. The service composites the whole display as before and crops with ScreenSampler.pixelRect, and the capture's region is read back from the whole pixels kept, so the scale and DPI stay exact. Runs from Shift-Command-S on the overlay (rebindable, new default kept off when taken, and like Command-S it commits a label being typed), a status menu item, and AnnotateCommand.capture(.area). --- Annotate/AnnotateCommand.swift | 7 +- Annotate/AppDelegate+Capture.swift | 73 ++++++++- Annotate/AppDelegate.swift | 10 +- Annotate/Capture.swift | 48 +++++- Annotate/CaptureSettingsView.swift | 12 +- Annotate/Info.plist | 2 +- Annotate/OverlayView.swift | 27 ++++ Annotate/OverlayWindow.swift | 90 +++++++++-- Annotate/RegionPicker.swift | 197 +++++++++++++++++++++++ Annotate/ShortcutManager.swift | 4 + Annotate/ShortcutsSettingsView.swift | 7 + AnnotateTests/AnnotateCommandTests.swift | 192 ++++++++++++++++++++++ AnnotateTests/CaptureTests.swift | 126 ++++++++++++++- AnnotateTests/RegionPickerTests.swift | 127 +++++++++++++++ AnnotateTests/URLCommandTests.swift | 6 +- 15 files changed, 892 insertions(+), 36 deletions(-) create mode 100644 Annotate/RegionPicker.swift create mode 100644 AnnotateTests/RegionPickerTests.swift diff --git a/Annotate/AnnotateCommand.swift b/Annotate/AnnotateCommand.swift index 689ebd3..2624fbd 100644 --- a/Annotate/AnnotateCommand.swift +++ b/Annotate/AnnotateCommand.swift @@ -16,8 +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. - /// Never runs from a link. + /// 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. @@ -151,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 } diff --git a/Annotate/AppDelegate+Capture.swift b/Annotate/AppDelegate+Capture.swift index 1a50426..047e76c 100644 --- a/Annotate/AppDelegate+Capture.swift +++ b/Annotate/AppDelegate+Capture.swift @@ -3,8 +3,9 @@ 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. @@ -18,9 +19,19 @@ extension AppDelegate { 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() } } @@ -32,12 +43,60 @@ 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() { + if !isInteractiveOverlayOpen { + // Always-On annotations are on screen, so the overlay opening over them keeps them, + // even with Clear Drawings on Start. + if alwaysOnMode, let screen = getCurrentScreen(), let overlay = overlayWindows[screen] { + overlaysKeepingDrawings.insert(ObjectIdentifier(overlay)) + } + showInteractiveOverlay() + } + guard let screen = areaTargetScreen, let overlay = overlayWindows[screen], + let display = DisplayInfo(screen: screen) + else { + log.error("No overlay to pick an area on") + return + } + guard !overlay.isRegionPickerOpen else { return } + // Without Screen Recording the drag would come to nothing, so ask before it starts. + let board = BoardManager.shared + if !captureService.source.canCapture, + !CaptureScene.boardCoversScreen(board.appearance, opacity: CGFloat(board.opacity)) + { + showScreenRecordingOff(on: overlay) + return + } + // The picker reads Escape from its own overlay, and another display's may be key. + overlay.makeKeyAndOrderFront(nil) + overlay.beginRegionPicker { [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) + } + } + 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 diff --git a/Annotate/AppDelegate.swift b/Annotate/AppDelegate.swift index b161899..04e21f5 100644 --- a/Annotate/AppDelegate.swift +++ b/Annotate/AppDelegate.swift @@ -32,8 +32,8 @@ 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. + /// 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: [FileSink(folder: FileSink.defaultFolder), ClipboardSink()]) @@ -403,6 +403,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()) @@ -1021,6 +1026,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 } diff --git a/Annotate/Capture.swift b/Annotate/Capture.swift index ec242d4..9f5e5a5 100644 --- a/Annotate/Capture.swift +++ b/Annotate/Capture.swift @@ -3,8 +3,9 @@ import ImageIO import UniformTypeIdentifiers import os -// Capture Screen: a ScreenCaptureKit snapshot of one display with Annotate's windows left out, -// with the board and annotations composited over it in process. Nothing here reads app +// Capture Screen and Capture Area: a ScreenCaptureKit snapshot of one display with Annotate's +// windows left out, with the board and annotations composited over it in process, cropped to +// the picked area for Capture Area. Nothing here reads app // singletons or views; `AppDelegate+Capture.swift` gathers the overlay's state and passes it in. private let log = Logger(subsystem: "com.epilande.Annotate", category: "Capture") @@ -13,11 +14,19 @@ private let log = Logger(subsystem: "com.epilande.Annotate", category: "Capture" /// saved links. enum CaptureScope: String, CaseIterable, Sendable { case screen + case area } /// The part of a display a capture keeps. enum CaptureRegion: Equatable, Sendable { case display + /// Part of the display, in display-local points with a top-left origin. + case rect(CGRect) + + /// A rectangle from an overlay view, whose origin is the display's bottom-left corner. + static func rect(fromViewRect rect: CGRect, displayHeight: CGFloat) -> CaptureRegion { + .rect(CGRect(x: rect.minX, y: displayHeight - rect.maxY, width: rect.width, height: rect.height)) + } } /// One display, as a capture records it. @@ -65,7 +74,11 @@ struct CaptureScene { var now: CFTimeInterval /// A fully opaque board hides every screen pixel, so such a capture needs none. - var coversScreen: Bool { board.isVisible && boardOpacity >= 1 } + var coversScreen: Bool { Self.boardCoversScreen(board, opacity: boardOpacity) } + + static func boardCoversScreen(_ board: BoardAppearance, opacity: CGFloat) -> Bool { + board.isVisible && opacity >= 1 + } } /// A capture to make. `scene` is nil when the display's overlay is hidden, which saves the @@ -144,6 +157,8 @@ enum CaptureError: Error, Equatable { case snapshotFailed /// The image could not be composited or encoded. case renderFailed + /// The area to keep lies off the display or is less than a pixel across. + case emptyRegion } /// The outcome of a capture that produced an image. `failures` holds the sinks that threw; @@ -193,12 +208,14 @@ final class CaptureService { in: current.document, from: snapshot, display: request.display) } - guard let image = CaptureCompositor.composite(snapshot: snapshot, display: request.display, scene: scene) + guard let composite = CaptureCompositor.composite(snapshot: snapshot, display: request.display, scene: scene) else { throw CaptureError.renderFailed } + guard let (image, region) = CaptureCompositor.crop(composite, to: request.region, display: request.display) + else { throw CaptureError.emptyRegion } let capture = Capture( image: image, display: request.display, - region: CGRect(origin: .zero, size: request.display.frame.size), + region: region, scene: scene, capturedAt: request.date, hostTime: request.hostTime) @@ -267,6 +284,27 @@ enum CaptureCompositor { return context.makeImage() } + /// The part of a full-display composite that `region` keeps, and the area it covers in + /// display-local points with a top-left origin. Edges round to whole pixels with the + /// redaction crop's math, and the area is read back from those pixels, so the image's + /// scale stays exact. Nil when the region misses the display or is under a pixel. + static func crop(_ image: CGImage, to region: CaptureRegion, display: DisplayInfo) -> (CGImage, CGRect)? { + let size = display.frame.size + guard case .rect(let local) = region else { return (image, CGRect(origin: .zero, size: size)) } + guard size.width > 0 else { return nil } + let scale = CGFloat(image.width) / size.width + // `pixelRect` works in Cocoa screen coordinates; a frame at the origin keeps the + // conversion local. + let frame = CGRect(origin: .zero, size: size) + let screenRect = CGRect(x: local.minX, y: size.height - local.maxY, width: local.width, height: local.height) + guard let pixels = ScreenSampler.pixelRect(screenRect: screenRect, displayFrame: frame, scale: scale), + let cropped = image.cropping(to: pixels) + else { return nil } + let points = CGRect( + x: pixels.minX / scale, y: pixels.minY / scale, width: pixels.width / scale, height: pixels.height / scale) + return (cropped, points) + } + /// A copy of `document` whose pixelate and blur redactions hold samples from `snapshot`, /// the pixels this capture saves. Samples the overlay made earlier can show what was /// under the rectangle before the screen changed, so every one is replaced; without a diff --git a/Annotate/CaptureSettingsView.swift b/Annotate/CaptureSettingsView.swift index 2fb9120..25dd168 100644 --- a/Annotate/CaptureSettingsView.swift +++ b/Annotate/CaptureSettingsView.swift @@ -44,7 +44,7 @@ struct CaptureSettingsView: View { .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("capture.folderError") } - Text("Capture Screen saves a PNG of the display, with the board and annotations as they appear, to this folder and copies it to the clipboard.") + Text("Capture Screen saves a PNG of the display, and Capture Area of a part you drag out, with the board and annotations as they appear, to this folder and copies it to the clipboard.") .font(.footnote) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) @@ -52,8 +52,8 @@ struct CaptureSettingsView: View { SettingsHeader( icon: "camera.viewfinder", color: .teal, - title: "Capture Screen", - subtitle: "Save the display with its annotations" + title: "Capture", + subtitle: "Save the display or an area with its annotations" ) } @@ -78,8 +78,8 @@ struct CaptureSettingsView: View { .onChange(of: navigation.requestsScreenRecording) { _, _ in requestAccessIfAsked() } } - /// Capture Screen and the Redact tool's Pixelate and Blur read the screen, which macOS - /// gates behind Screen Recording. + /// Capture and the Redact tool's Pixelate and Blur read the screen, which macOS gates + /// behind Screen Recording. private var screenRecordingRow: some View { VStack(alignment: .leading, spacing: 6) { HStack(spacing: 6) { @@ -96,7 +96,7 @@ struct CaptureSettingsView: View { } } } - Text("Capture Screen and the Redact tool's Pixelate and Blur styles read the pixels on screen. Until access is granted, Capture Screen works only while a fully opaque board is showing, and redactions use a solid fill. macOS may ask you to relaunch Annotate first.") + Text("Capture Screen, Capture Area, and the Redact tool's Pixelate and Blur styles read the pixels on screen. Until access is granted, capture works only while a fully opaque board is showing, and redactions use a solid fill. macOS may ask you to relaunch Annotate first.") .font(.footnote) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) diff --git a/Annotate/Info.plist b/Annotate/Info.plist index a1a86f6..888dd51 100644 --- a/Annotate/Info.plist +++ b/Annotate/Info.plist @@ -38,7 +38,7 @@ LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) NSScreenCaptureUsageDescription - Capture Screen saves what is on screen with your annotations, and Pixelate and Blur redactions read the pixels under the rectangle. + Capture Screen and Capture Area save what is on screen with your annotations, and Pixelate and Blur redactions read the pixels under the rectangle. SUFeedURL https://raw.githubusercontent.com/epilande/Annotate/main/appcast.xml SUPublicEDKey diff --git a/Annotate/OverlayView.swift b/Annotate/OverlayView.swift index 444248b..d4c4317 100644 --- a/Annotate/OverlayView.swift +++ b/Annotate/OverlayView.swift @@ -300,6 +300,10 @@ class OverlayView: NSView, NSTextFieldDelegate { /// The time fade alphas and expiry are measured at. Test hook: production keeps the media /// clock that creation times are stamped with. var fadeClock: () -> CFTimeInterval = CACurrentMediaTime + /// The running clock while `freezeFade()` holds `fadeClock` still, or nil. + private var clockBeforeFreeze: (() -> CFTimeInterval)? + /// Whether `freezeFade()` is holding every annotation at its current fade. + var isFadeFrozen: Bool { clockBeforeFreeze != nil } /// How long annotations caught mid-fade take to return to full strength after a switch /// to Persist. let persistRestoreDuration: CFTimeInterval = 0.15 @@ -470,6 +474,29 @@ class OverlayView: NSView, NSTextFieldDelegate { selectedObjects.removeAll() } + /// Holds every annotation at its current fade while Capture Area's picker is open. Fade + /// Mode's default hold is shorter than a drag, so without this an area would empty before + /// it was picked. Wraps the clock rather than replacing it, so a test clock keeps running + /// underneath. + func freezeFade() { + guard clockBeforeFreeze == nil else { return } + let running = fadeClock + let frozenAt = running() + clockBeforeFreeze = running + fadeClock = { frozenAt } + (window as? OverlayWindow)?.stopFadeLoop() + } + + /// Lets the fade run on the real clock again. Each annotation picks up the fade its age + /// gives it; creation times stay as they are, since undo finds annotations by them. + func resumeFade() { + guard let running = clockBeforeFreeze else { return } + clockBeforeFreeze = nil + fadeClock = running + advanceFade() + startFadeLoopIfNeeded() + } + func startFadeLoopIfNeeded() { compactExpiredAnnotations() guard isAnythingFading() else { return } diff --git a/Annotate/OverlayWindow.swift b/Annotate/OverlayWindow.swift index 9801d5a..5f40f23 100644 --- a/Annotate/OverlayWindow.swift +++ b/Annotate/OverlayWindow.swift @@ -38,6 +38,8 @@ class OverlayWindow: NSPanel { /// True when the picker consumed this mouse-down, so the matching up must not commit geometry. private var pickerConsumedMouseDown = false private var mouseCoalescingSnapshot: Bool? + /// Capture Area's picker while it is open. See `beginRegionPicker(onPick:)`. + private(set) var regionPicker: RegionPicker? // Latched at mouseDown: currentTool can change mid-drag via tool shortcuts private var activeFreehandTool: ToolType? private var activeShapeTool: ToolType? @@ -361,6 +363,7 @@ class OverlayWindow: NSPanel { override func orderOut(_ sender: Any?) { cancelQuickPicker() + cancelRegionPicker() restoreMouseCoalescing() overlayView.discardRedactionSamples() super.orderOut(sender) @@ -382,15 +385,19 @@ class OverlayWindow: NSPanel { override func close() { // The fade timer retains the window, and the observer would keep re-measuring a toolbar // nobody sees, so a closed overlay has to drop both or it lives for the rest of the process. - stopFadeLoop() NotificationCenter.default.removeObserver(self, name: .shortcutsDidChange, object: nil) toolbarPanel?.tearDown() toolbarPanel = nil + // After the toolbar goes, so the picker has no bar to put back, and before the fade + // loop stops, since closing the picker lets the fade run again. + cancelRegionPicker() + stopFadeLoop() super.close() } override func resignKey() { cancelQuickPicker() + cancelRegionPicker() restoreMouseCoalescing() super.resignKey() } @@ -426,7 +433,8 @@ class OverlayWindow: NSPanel { } func startFadeLoop() { - guard fadeTimer == nil else { return } + // A frozen fade draws the same frame every tick. + guard fadeTimer == nil, overlayView?.isFadeFrozen != true else { return } fadeTimer = Timer.scheduledTimer( timeInterval: fadeInterval, target: self, @@ -462,6 +470,11 @@ class OverlayWindow: NSPanel { } switch (event.type, KeyChord(event: event)) { + case (.keyDown, let chord?) where regionPicker != nil, (.keyUp, let chord?) where regionPicker != nil: + if event.type == .keyDown { + regionPicker?.handleKey(chord) + } + return case (.keyDown, let chord?): if quickPicker != nil { _ = handleQuickPickerKeyDown(chord) @@ -503,7 +516,7 @@ class OverlayWindow: NSPanel { .rightMouseDown, .rightMouseUp, .otherMouseDown, .otherMouseUp: break case .scrollWheel: - return quickPicker != nil + return quickPicker != nil || regionPicker != nil default: return false } @@ -514,6 +527,12 @@ class OverlayWindow: NSPanel { return true } + // Capture Area's picker owns every press, including one on the menu bar. + if let regionPicker { + regionPicker.handleMouseEvent(event) + return true + } + if quickPicker != nil { // A press that opened the status menu never saw its release, which the menu's // tracking loop ate. The picker now owns the press, so its release must reach @@ -610,7 +629,7 @@ class OverlayWindow: NSPanel { activationKey: String? = nil, activationKeyCode: UInt16? = nil ) { - guard quickPicker == nil else { return } + guard quickPicker == nil, regionPicker == nil else { return } discardLiveDrawing() @@ -697,6 +716,49 @@ class OverlayWindow: NSPanel { dismissQuickPicker() } + var isRegionPickerOpen: Bool { regionPicker != nil } + + /// Opens Capture Area's picker over the canvas and returns whether it opened. Closes a + /// quick picker, commits a label being typed, drops any drawing in progress, freezes the + /// fade, and moves the toolbar aside so the whole display can be picked. `onPick` gets the + /// picked rectangle in the overlay view's coordinates, before the picker closes, so a + /// capture made there reads the annotations at the fade the picker showed. + @discardableResult + func beginRegionPicker(onPick: @escaping (CGRect) -> Void) -> Bool { + guard regionPicker == nil, !overlayView.isReadOnlyMode else { return false } + cancelQuickPicker() + if let activeField = overlayView.activeTextField { + overlayView.finalizeTextAnnotation(activeField) + } + discardLiveDrawing() + restoreMouseCoalescing() + + let picker = RegionPicker(frame: overlayView.bounds) + picker.onPick = { [weak self] rect in + onPick(rect) + self?.cancelRegionPicker() + } + picker.onCancel = { [weak self] in self?.cancelRegionPicker() } + overlayView.addSubview(picker) + regionPicker = picker + overlayView.freezeFade() + toolbarPanel?.detach() + invalidateCursorRects(for: picker) + NSCursor.crosshair.set() + return true + } + + /// Closes Capture Area's picker without picking, and lets the fade run again. + func cancelRegionPicker() { + guard let picker = regionPicker else { return } + regionPicker = nil + picker.removeFromSuperview() + overlayView.resumeFade() + updateToolbarVisibility() + invalidateCursorRects(for: overlayView) + overlayView.updateCursor() + } + override func mouseMoved(with event: NSEvent) { guard quickPicker != nil else { super.mouseMoved(with: event) @@ -894,16 +956,19 @@ class OverlayWindow: NSPanel { case .clearAll: performClearAll() case .captureScreen: if !chord.isRepeat { AppDelegate.shared?.captureScreen() } + case .captureArea: + if !chord.isRepeat { AppDelegate.shared?.captureArea() } } return true } - /// Whether `action`'s shortcut works while a label is being typed. Capture Screen does - /// when its binding has Command, which no typed character carries; it commits the label - /// and captures, as the menu item does. Every other shortcut, and a Capture Screen binding - /// without Command, types into the label instead. + /// Whether `action`'s shortcut works while a label is being typed. Capture Screen and + /// Capture Area do when their binding has Command, which no typed character carries; they + /// commit the label first, as their menu items do. Every other shortcut, and a capture + /// binding without Command, types into the label instead. static func firesWhileEditingText(_ action: ShortcutKey) -> Bool { - action == .captureScreen && ShortcutManager.shared.binding(for: action).modifiers.contains(.command) + [.captureScreen, .captureArea].contains(action) + && ShortcutManager.shared.binding(for: action).modifiers.contains(.command) } private func handleQuickPickerKeyUp(_ chord: KeyChord) -> Bool { @@ -1665,6 +1730,10 @@ class OverlayWindow: NSPanel { super.keyDown(with: event) return } + if let regionPicker { + regionPicker.handleKey(chord) + return + } if handleQuickPickerKeyDown(chord) { return } @@ -2315,6 +2384,9 @@ class OverlayWindow: NSPanel { guard let chord = KeyChord(event: event) else { return super.performKeyEquivalent(with: event) } + if let regionPicker { + return regionPicker.handleKey(chord) + } if handleQuickPickerKeyDown(chord) || handleOverlayShortcut(chord) { return true } // Selection commands accept any extra modifiers. Command-B accepts only Shift. diff --git a/Annotate/RegionPicker.swift b/Annotate/RegionPicker.swift new file mode 100644 index 0000000..772e5ba --- /dev/null +++ b/Annotate/RegionPicker.swift @@ -0,0 +1,197 @@ +import AppKit + +/// Capture Area's picker: a crosshair over the display, dimmed outside the rectangle being +/// dragged, with the rectangle's size in points beside it. Release picks the rectangle, and +/// Escape or a right click cancels. +/// +/// AppKit only, with no knowledge of the overlay's annotations or of capture: the overlay +/// window installs it over its canvas and forwards the mouse and key events it receives. +/// Drawing goes through layers, so following the pointer never asks the view to redraw. +final class RegionPicker: NSView { + /// A release whose rectangle is narrower or shorter than this, in points, counts as a + /// click: nothing is picked and the picker stays open. + static let minimumSide: CGFloat = 4 + /// How dark the area outside the rectangle gets. + static let dimOpacity: Float = 0.35 + + /// Called with the picked rectangle in this view's coordinates. + var onPick: ((CGRect) -> Void)? + var onCancel: (() -> Void)? + + private(set) var dragStart: NSPoint? + private(set) var dragEnd: NSPoint? + + private let dimLayer = CAShapeLayer() + private let borderLayer = CAShapeLayer() + private let sizeLabel = CATextLayer() + + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + wantsLayer = true + autoresizingMask = [.width, .height] + + dimLayer.fillRule = .evenOdd + dimLayer.fillColor = NSColor.black.withAlphaComponent(CGFloat(Self.dimOpacity)).cgColor + borderLayer.fillColor = nil + borderLayer.strokeColor = NSColor.white.cgColor + borderLayer.lineWidth = 1 + sizeLabel.font = NSFont.monospacedDigitSystemFont(ofSize: 12, weight: .medium) + sizeLabel.fontSize = 12 + sizeLabel.foregroundColor = NSColor.white.cgColor + sizeLabel.backgroundColor = NSColor.black.withAlphaComponent(0.7).cgColor + sizeLabel.cornerRadius = 4 + sizeLabel.alignmentMode = .center + sizeLabel.isHidden = true + for sublayer in [dimLayer, borderLayer, sizeLabel] { + layer?.addSublayer(sublayer) + } + updateLayers() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + /// The rectangle dragged so far, normalized and clipped to the view, or nil before a drag. + var selection: CGRect? { + guard let dragStart, let dragEnd else { return nil } + return Self.normalizedRect(from: dragStart, to: dragEnd, within: bounds) + } + + /// The rectangle between two corners, whichever way the drag went, clipped to `bounds`. + static func normalizedRect(from start: NSPoint, to end: NSPoint, within bounds: CGRect) -> CGRect { + let rect = 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)) + let clipped = rect.intersection(bounds) + return clipped.isNull ? CGRect(origin: rect.origin, size: .zero) : clipped + } + + /// Whether `rect` is big enough to pick rather than a click. + static func isPickable(_ rect: CGRect) -> Bool { + rect.width >= minimumSide && rect.height >= minimumSide + } + + /// The size label's text: whole points, as the rectangle covers on screen. + static func sizeText(for rect: CGRect) -> String { + "\(Int(rect.width.rounded())) × \(Int(rect.height.rounded()))" + } + + // MARK: - Events + + /// Handles a mouse event the overlay window forwards. Every mouse event belongs to the + /// picker while it is open, so nothing reaches the canvas. + func handleMouseEvent(_ event: NSEvent) { + let point = convert(event.locationInWindow, from: nil) + switch event.type { + case .leftMouseDown: mouseDown(at: point) + case .leftMouseDragged: mouseDragged(to: point) + case .leftMouseUp: mouseUp(at: point) + case .rightMouseDown, .otherMouseDown: cancel() + default: break + } + } + + func mouseDown(at point: NSPoint) { + NSCursor.crosshair.set() + dragStart = point + dragEnd = point + updateLayers() + } + + func mouseDragged(to point: NSPoint) { + guard dragStart != nil else { return } + dragEnd = point + updateLayers() + } + + func mouseUp(at point: NSPoint) { + guard dragStart != nil else { return } + dragEnd = point + guard let rect = selection, Self.isPickable(rect) else { + // A click, or a drag too small to mean anything: keep picking. + dragStart = nil + dragEnd = nil + updateLayers() + return + } + onPick?(rect) + } + + /// Handles a key the overlay window forwards, and returns whether the picker took it. + /// Escape cancels; every other key is swallowed so no overlay shortcut runs mid-pick. + @discardableResult + func handleKey(_ chord: KeyChord) -> Bool { + if chord.key == "\u{1b}" { + cancel() + } + return true + } + + func cancel() { + onCancel?() + } + + // MARK: - Cursor and layers + + override func resetCursorRects() { + addCursorRect(bounds, cursor: .crosshair) + } + + override func updateTrackingAreas() { + super.updateTrackingAreas() + trackingAreas.forEach(removeTrackingArea) + addTrackingArea( + NSTrackingArea( + rect: bounds, options: [.cursorUpdate, .activeAlways, .inVisibleRect], owner: self, userInfo: nil)) + } + + /// The canvas under the picker sets its own cursor on these, so the picker answers first. + override func cursorUpdate(with event: NSEvent) { + NSCursor.crosshair.set() + } + + override func layout() { + super.layout() + updateLayers() + } + + private func updateLayers() { + CATransaction.begin() + CATransaction.setDisableActions(true) + defer { CATransaction.commit() } + + let dim = CGMutablePath() + dim.addRect(bounds) + guard let rect = selection, rect.width > 0, rect.height > 0 else { + dimLayer.path = dim + borderLayer.path = nil + sizeLabel.isHidden = true + return + } + dim.addRect(rect) + dimLayer.path = dim + borderLayer.path = CGPath(rect: rect.insetBy(dx: -0.5, dy: -0.5), transform: nil) + + sizeLabel.contentsScale = window?.backingScaleFactor ?? 2 + let text = Self.sizeText(for: rect) + sizeLabel.string = text + let textSize = (text as NSString).size( + withAttributes: [.font: NSFont.monospacedDigitSystemFont(ofSize: 12, weight: .medium)]) + let labelSize = CGSize(width: ceil(textSize.width) + 12, height: ceil(textSize.height) + 4) + sizeLabel.frame = Self.labelFrame(size: labelSize, for: rect, within: bounds) + sizeLabel.isHidden = false + } + + /// Below the rectangle's bottom-right corner, or inside it when that would leave the view. + static func labelFrame(size: CGSize, for rect: CGRect, within bounds: CGRect) -> CGRect { + let gap: CGFloat = 6 + var origin = CGPoint(x: rect.maxX - size.width, y: rect.minY - gap - size.height) + if origin.y < bounds.minY { origin.y = rect.minY + gap } + origin.x = min(max(origin.x, bounds.minX), bounds.maxX - size.width) + return CGRect(origin: origin, size: size) + } +} diff --git a/Annotate/ShortcutManager.swift b/Annotate/ShortcutManager.swift index 670f31f..00d84b6 100644 --- a/Annotate/ShortcutManager.swift +++ b/Annotate/ShortcutManager.swift @@ -123,11 +123,13 @@ enum ShortcutKey: String, CaseIterable { case increaseSize case clearAll case captureScreen + case captureArea /// Actions whose default binding arrived after users could already customize shortcuts. /// An existing custom binding on the same key wins over the new default (see `init`). static let newlyEditable: [ShortcutKey] = [ .toggleFade, .toggleToolbar, .decreaseSize, .increaseSize, .clearAll, .redact, .captureScreen, + .captureArea, ] var defaultBinding: ShortcutBinding { @@ -139,6 +141,7 @@ enum ShortcutKey: String, CaseIterable { case .increaseSize: return ShortcutBinding("]") case .clearAll: return ShortcutBinding("\u{7f}", modifiers: .option) case .captureScreen: return ShortcutBinding("s", modifiers: .command) + case .captureArea: return ShortcutBinding("s", modifiers: [.shift, .command]) default: return ShortcutBinding(rawValue) } } @@ -169,6 +172,7 @@ enum ShortcutKey: String, CaseIterable { case .increaseSize: return "Increase Size" case .clearAll: return "Clear All" case .captureScreen: return "Capture Screen" + case .captureArea: return "Capture Area" } } } diff --git a/Annotate/ShortcutsSettingsView.swift b/Annotate/ShortcutsSettingsView.swift index b78f162..9f36862 100644 --- a/Annotate/ShortcutsSettingsView.swift +++ b/Annotate/ShortcutsSettingsView.swift @@ -257,6 +257,13 @@ struct ShortcutsSettingsView: View { shortcuts: $shortcuts, editingShortcut: $editingShortcut ) + ShortcutSettingRow( + tool: .captureArea, + label: ShortcutKey.captureArea.displayName, + description: "Drag out part of the display to save and copy", + shortcuts: $shortcuts, + editingShortcut: $editingShortcut + ) } header: { SettingsHeader( icon: "slider.horizontal.3", diff --git a/AnnotateTests/AnnotateCommandTests.swift b/AnnotateTests/AnnotateCommandTests.swift index 0f13ceb..5dc2d03 100644 --- a/AnnotateTests/AnnotateCommandTests.swift +++ b/AnnotateTests/AnnotateCommandTests.swift @@ -456,6 +456,7 @@ final class AnnotateCommandTests: XCTestCase { XCTAssertEqual(AnnotateCommand.fade(.toggle).path, "/fade/toggle") XCTAssertEqual(AnnotateCommand.board(.on).path, "/board/on") XCTAssertEqual(AnnotateCommand.capture(.screen).path, "/capture/screen") + XCTAssertEqual(AnnotateCommand.capture(.area).path, "/capture/area") } func testPathParsingIsLenientAboutSlashesAndCase() { @@ -911,6 +912,197 @@ final class AnnotateCommandTests: XCTestCase { XCTAssertEqual(item.keyEquivalentModifierMask, .command) } + // MARK: - Capture Area + + /// Presses at `start`, drags to `end`, and releases there, through the overlay's own event + /// routing. Points are in the overlay view's coordinates, which the window shares. + private func drag(from start: NSPoint, to end: NSPoint) throws { + let steps: [(NSEvent.EventType, NSPoint)] = [(.leftMouseDown, start), (.leftMouseDragged, end), (.leftMouseUp, end)] + for (type, point) in steps { + overlay.sendEvent( + try XCTUnwrap(TestEvents.createMouseEvent(type: type, location: point, windowNumber: overlay.windowNumber))) + } + } + + private func pressEscape() throws { + overlay.sendEvent( + try XCTUnwrap( + TestEvents.createKeyEvent( + type: .keyDown, keyCode: 53, characters: "\u{1b}", windowNumber: overlay.windowNumber))) + } + + func testCaptureAreaOpensTheOverlayAndSavesTheDraggedArea() async throws { + let (folder, pasteboard) = try useStubCapture() + XCTAssertTrue(visibleOverlays.isEmpty) + + XCTAssertEqual(run(.capture(.area)), .ran) + + XCTAssertTrue(appDelegate.isInteractiveOverlayOpen) + XCTAssertTrue(overlay.isRegionPickerOpen) + XCTAssertNil(appDelegate.captureTask, "Nothing is captured before the drag") + overlay.overlayView.rectangles = [solidRedactionInTheCorner] + + // Up and to the left, from (80, 60) to the display's bottom-left corner. + try drag(from: NSPoint(x: 80, y: 60), to: .zero) + XCTAssertFalse(overlay.isRegionPickerOpen) + await appDelegate.captureTask?.value + + let files = try FileManager.default.contentsOfDirectory(atPath: folder.path) + XCTAssertEqual(files.count, 1) + XCTAssertEqual(feedbackText(on: overlay), "📸 Saved \(try XCTUnwrap(files.first))") + let image = try XCTUnwrap(NSBitmapImageRep(data: try XCTUnwrap(pasteboard.data(forType: .png)))?.cgImage) + let scale = screen.backingScaleFactor + XCTAssertEqual(image.width, Int(80 * scale)) + XCTAssertEqual(image.height, Int(60 * scale)) + // The 40 point solid redaction in the bottom-left corner, and the screen beside it. + let corner = CaptureTestImages.pixel(image, x: 4, y: image.height - 4) + XCTAssertTrue(corner.isClose(to: RGBA(r: 0, g: 0, b: 0, a: 255)), "\(corner)") + let topRight = CaptureTestImages.pixel(image, x: image.width - 4, y: 4) + XCTAssertTrue(topRight.isClose(to: RGBA(r: 0, g: 0, b: 255, a: 255)), "\(topRight)") + } + + func testEscapeCancelsCaptureAreaAndKeepsTheOverlayOpen() throws { + try useStubCapture() + run(.show) + let toolbarWasAttached = overlay.toolbarPanel?.isAttached + run(.capture(.area)) + XCTAssertTrue(overlay.isRegionPickerOpen) + XCTAssertEqual(overlay.toolbarPanel?.isAttached ?? false, false, "The whole display can be picked") + + try pressEscape() + + XCTAssertFalse(overlay.isRegionPickerOpen) + XCTAssertTrue(appDelegate.isInteractiveOverlayOpen, "Escape closes only the picker") + XCTAssertFalse(overlay.overlayView.isFadeFrozen) + XCTAssertEqual(overlay.toolbarPanel?.isAttached, toolbarWasAttached) + XCTAssertNil(appDelegate.captureTask) + } + + func testCaptureAreaHoldsTheFadeAndCapturesAtTheHeldTime() async throws { + let (_, pasteboard) = try useStubCapture() + run(.show) + let view = try XCTUnwrap(overlay.overlayView) + var clock: CFTimeInterval = 1000 + view.fadeClock = { clock } + view.fadeMode = true + // A thick red outline around the bottom-left corner, made just now. + var outline = Rectangle( + startPoint: .zero, endPoint: NSPoint(x: 40, y: 40), color: .red, lineWidth: 20, style: .outline) + outline.creationTime = clock + view.rectangles = [outline] + + run(.capture(.area)) + XCTAssertTrue(view.isFadeFrozen) + XCTAssertNil(overlay.fadeTimer, "A held fade has nothing to animate") + // The drag takes far longer than the outline lasts. + clock += view.fadeDuration * 10 + XCTAssertEqual(view.fadeClock(), 1000) + + try drag(from: .zero, to: NSPoint(x: 80, y: 60)) + + XCTAssertFalse(view.isFadeFrozen) + XCTAssertEqual(view.fadeClock(), clock, "The fade runs on the real clock again") + XCTAssertTrue(view.rectangles.isEmpty, "Once the picker closes the outline is past its fade") + await appDelegate.captureTask?.value + let image = try XCTUnwrap(NSBitmapImageRep(data: try XCTUnwrap(pasteboard.data(forType: .png)))?.cgImage) + let corner = CaptureTestImages.pixel(image, x: 2, y: image.height - 2) + XCTAssertTrue(corner.isClose(to: RGBA(r: 255, g: 0, b: 0, a: 255), tolerance: 40), "Captured as the picker showed it: \(corner)") + } + + func testCaptureAreaFromAlwaysOnOpensTheInteractiveOverlayWithItsDrawings() throws { + try useStubCapture() + testDefaults.settings[.clearDrawingsOnStart] = true + appDelegate.toggleAlwaysOnMode() + overlay.overlayView.paths.append(TestFactory.createDrawingPath()) + + run(.capture(.area)) + + XCTAssertFalse(appDelegate.alwaysOnMode) + XCTAssertTrue(appDelegate.isInteractiveOverlayOpen) + XCTAssertTrue(overlay.isRegionPickerOpen) + XCTAssertEqual(overlay.overlayView.paths.count, 1, "The Always-On drawings were on screen, so they stay") + } + + func testCaptureAreaFromAClosedOverlayStillClearsWithClearDrawingsOnStart() throws { + try useStubCapture() + testDefaults.settings[.clearDrawingsOnStart] = true + overlay.overlayView.paths.append(TestFactory.createDrawingPath()) + + run(.capture(.area)) + + XCTAssertTrue(overlay.isRegionPickerOpen) + XCTAssertTrue(overlay.overlayView.paths.isEmpty, "Opens the way the overlay shortcut does") + } + + func testShiftCommandSWhileTypingALabelCommitsItAndPicks() throws { + try useStubCapture() + let view = try startTypingALabel("Hello") + + XCTAssertTrue(overlay.performKeyEquivalent(with: try keyDown("S", modifiers: [.shift, .command]))) + + XCTAssertNil(view.activeTextField) + XCTAssertEqual(view.textAnnotations.map(\.text), ["Hello"]) + XCTAssertTrue(overlay.isRegionPickerOpen) + } + + func testShortcutsStandDownWhilePicking() throws { + try useStubCapture() + run(.show) + overlay.overlayView.currentTool = .arrow + run(.capture(.area)) + + overlay.sendEvent(try keyDown("p")) + XCTAssertTrue(overlay.performKeyEquivalent(with: try keyDown("s", modifiers: .command))) + + XCTAssertEqual(overlay.overlayView.currentTool, .arrow) + XCTAssertTrue(overlay.isRegionPickerOpen) + XCTAssertNil(appDelegate.captureTask) + } + + func testClosingTheOverlayCancelsThePicker() throws { + try useStubCapture() + run(.capture(.area)) + XCTAssertTrue(overlay.overlayView.isFadeFrozen) + + run(.hide) + + XCTAssertFalse(overlay.isRegionPickerOpen) + XCTAssertFalse(overlay.overlayView.isFadeFrozen) + } + + func testCaptureAreaWithoutScreenRecordingAsksBeforePicking() throws { + try useStubCapture(canCapture: false) + appDelegate.screenRecordingNoticeDelay = 0 + var opened: [SettingsPane] = [] + appDelegate.openSettingsPane = { pane, _, _ in opened.append(pane) } + run(.show) + + run(.capture(.area)) + + XCTAssertFalse(overlay.isRegionPickerOpen) + runLoop { !opened.isEmpty } + XCTAssertEqual(opened, [.capture]) + } + + func testCaptureAreaOverAnOpaqueBoardNeedsNoScreenRecording() throws { + try useStubCapture(canCapture: false) + BoardManager.shared.isEnabled = true + BoardManager.shared.opacity = 1 + run(.show) + + run(.capture(.area)) + + XCTAssertTrue(overlay.isRegionPickerOpen) + } + + func testCaptureAreaMenuItemTakesTheShortcut() throws { + let item = try XCTUnwrap( + appDelegate.statusItem.menu?.items.first { $0.action == #selector(AppDelegate.captureArea) }) + XCTAssertEqual(item.title, "Capture Area") + XCTAssertEqual(item.keyEquivalent, "s") + XCTAssertEqual(item.keyEquivalentModifierMask, [.shift, .command]) + } + // MARK: - App Intents func testEveryPickerCaseHasADisplayRepresentation() { diff --git a/AnnotateTests/CaptureTests.swift b/AnnotateTests/CaptureTests.swift index dfd049a..9337999 100644 --- a/AnnotateTests/CaptureTests.swift +++ b/AnnotateTests/CaptureTests.swift @@ -149,8 +149,11 @@ final class CaptureTests: XCTestCase { CaptureScene(document: document, board: board, boardOpacity: opacity, fade: fade, now: now) } - private func request(display: DisplayInfo, scene: CaptureScene?) -> CaptureRequest { - CaptureRequest(display: display, scene: scene, hostTime: 42, date: Date(timeIntervalSince1970: 0)) + private func request( + display: DisplayInfo, region: CaptureRegion = .display, scene: CaptureScene? + ) -> CaptureRequest { + CaptureRequest( + display: display, region: region, scene: scene, hostTime: 42, date: Date(timeIntervalSince1970: 0)) } private func temporaryFolder() throws -> URL { @@ -426,6 +429,118 @@ final class CaptureTests: XCTestCase { XCTAssertNil(result.failure(of: .file)) } + // MARK: - Area + + func testViewRectBecomesATopLeftRegion() { + // A view rect 10 pt above the bottom of a 50 pt tall display. + let region = CaptureRegion.rect(fromViewRect: CGRect(x: 20, y: 10, width: 30, height: 15), displayHeight: 50) + XCTAssertEqual(region, .rect(CGRect(x: 20, y: 25, width: 30, height: 15))) + } + + func testCropKeepsTheRegionAtScaleOneAndTwo() throws { + for scale in [CGFloat(1), 2] { + let width = Int(100 * scale) + let height = Int(50 * scale) + // Red top rows above a blue rest, and green left columns, so a crop's corners tell + // which part of the display it kept. + let image = CaptureTestImages.image( + width: width, + height: height, + top: Self.red, + bottom: Self.blue, + topRows: Int(10 * scale), + left: Self.green, + leftColumns: Int(20 * scale)) + let region = CaptureRegion.rect(CGRect(x: 10, y: 5, width: 30, height: 20)) + + let (cropped, points) = try XCTUnwrap(CaptureCompositor.crop(image, to: region, display: display(scale: scale))) + + XCTAssertEqual(points, CGRect(x: 10, y: 5, width: 30, height: 20), "scale \(scale)") + XCTAssertEqual(cropped.width, Int(30 * scale)) + XCTAssertEqual(cropped.height, Int(20 * scale)) + // Top-left: inside the green columns, which paint over the red rows. + XCTAssertTrue(CaptureTestImages.pixel(cropped, x: 1, y: 1).isClose(to: Self.green), "scale \(scale)") + // Top-right: red rows, right of the green columns. + XCTAssertTrue( + CaptureTestImages.pixel(cropped, x: cropped.width - 2, y: 1).isClose(to: Self.red), "scale \(scale)") + // Bottom-right: blue. + XCTAssertTrue( + CaptureTestImages.pixel(cropped, x: cropped.width - 2, y: cropped.height - 2).isClose(to: Self.blue), + "scale \(scale)") + } + } + + func testCropRoundsToWholePixelsAndReportsTheAreaItKept() throws { + let image = CaptureTestImages.solid(width: 200, height: 100, Self.blue) + let region = CaptureRegion.rect(CGRect(x: 10.2, y: 5.3, width: 30.1, height: 20.2)) + + let (cropped, points) = try XCTUnwrap(CaptureCompositor.crop(image, to: region, display: display(scale: 2))) + + // Edges round to the nearest pixel: 20.4 to 20, 10.6 to 11, 80.6 to 81, 51 stays. + XCTAssertEqual(cropped.width, 61) + XCTAssertEqual(cropped.height, 40) + XCTAssertEqual(points, CGRect(x: 10, y: 5.5, width: 30.5, height: 20)) + XCTAssertEqual(CGFloat(cropped.width) / points.width, 2, "The scale stays exact") + } + + func testCropClipsToTheDisplayAndRejectsAnAreaOffIt() throws { + let image = CaptureTestImages.solid(width: 100, height: 50, Self.blue) + + let (cropped, points) = try XCTUnwrap( + CaptureCompositor.crop(image, to: .rect(CGRect(x: 80, y: 40, width: 50, height: 50)), display: display())) + XCTAssertEqual(points, CGRect(x: 80, y: 40, width: 20, height: 10)) + XCTAssertEqual(cropped.width, 20) + XCTAssertEqual(cropped.height, 10) + + XCTAssertNil(CaptureCompositor.crop(image, to: .rect(CGRect(x: 200, y: 0, width: 10, height: 10)), display: display())) + XCTAssertNil(CaptureCompositor.crop(image, to: .rect(CGRect(x: 10, y: 10, width: 0.2, height: 10)), display: display())) + } + + func testCropOfTheWholeDisplayKeepsTheImage() throws { + let image = CaptureTestImages.solid(width: 200, height: 100, Self.blue) + let (cropped, points) = try XCTUnwrap(CaptureCompositor.crop(image, to: .display, display: display(scale: 2))) + XCTAssertTrue(cropped === image) + XCTAssertEqual(points, CGRect(x: 0, y: 0, width: 100, height: 50)) + } + + func testServiceCropsAnAreaWithItsAnnotations() async throws { + let pasteboard = privatePasteboard() + let service = CaptureService( + source: StubDisplayCapturing(snapshotImage: CaptureTestImages.solid(width: 200, height: 100, Self.blue)), + sinks: [ClipboardSink(pasteboard: pasteboard)]) + var document = OverlayDocument() + // A solid redaction over the display's bottom-left 20 x 10 points. + document.rectangles = [redaction(CGRect(x: 0, y: 0, width: 20, height: 10))] + // The bottom-left 40 x 20 points, as a picker on the overlay reports it. + let region = CaptureRegion.rect(fromViewRect: CGRect(x: 0, y: 0, width: 40, height: 20), displayHeight: 50) + + let result = try await service.capture(request(display: display(scale: 2), region: region, scene: scene(document))) + + XCTAssertEqual(result.capture.region, CGRect(x: 0, y: 30, width: 40, height: 20)) + XCTAssertEqual(result.capture.scale, 2) + let image = result.capture.image + XCTAssertEqual(image.width, 80) + XCTAssertEqual(image.height, 40) + XCTAssertTrue(CaptureTestImages.pixel(image, x: 2, y: image.height - 2).isClose(to: Self.black)) + XCTAssertTrue(CaptureTestImages.pixel(image, x: image.width - 2, y: 2).isClose(to: Self.blue)) + let decoded = try XCTUnwrap(NSImage(data: try XCTUnwrap(pasteboard.data(forType: .png)))) + XCTAssertEqual(decoded.size, NSSize(width: 40, height: 20), "DPI keeps the area's point size") + } + + func testServiceRejectsAnAreaOffTheDisplay() async throws { + let service = CaptureService( + source: StubDisplayCapturing(snapshotImage: CaptureTestImages.solid(width: 100, height: 50, Self.blue)), + sinks: []) + + do { + _ = try await service.capture( + request(display: display(), region: .rect(CGRect(x: 500, y: 0, width: 10, height: 10)), scene: nil)) + XCTFail("Expected emptyRegion") + } catch { + XCTAssertEqual(error as? CaptureError, .emptyRegion) + } + } + // MARK: - File naming func testFileNameMirrorsMacOSScreenshots() throws { @@ -532,6 +647,13 @@ final class CaptureTests: XCTestCase { XCTAssertEqual(ShortcutKey.captureScreen.displayName, "Capture Screen") } + func testCaptureAreaDefaultsToShiftCommandS() { + XCTAssertEqual(ShortcutKey.captureArea.defaultBinding, ShortcutBinding("s", modifiers: [.shift, .command])) + XCTAssertFalse(ShortcutKey.captureArea.defaultBinding.isReserved) + XCTAssertTrue(ShortcutKey.newlyEditable.contains(.captureArea)) + XCTAssertEqual(ShortcutKey.captureArea.displayName, "Capture Area") + } + // MARK: - Capture pane func testShowInFinderReportsAFolderItCantCreate() throws { diff --git a/AnnotateTests/RegionPickerTests.swift b/AnnotateTests/RegionPickerTests.swift new file mode 100644 index 0000000..77607ba --- /dev/null +++ b/AnnotateTests/RegionPickerTests.swift @@ -0,0 +1,127 @@ +import XCTest + +@testable import Annotate + +@MainActor +final class RegionPickerTests: XCTestCase { + private let bounds = CGRect(x: 0, y: 0, width: 400, height: 300) + private var picker: RegionPicker! + private var picked: [CGRect] = [] + private var cancels = 0 + + override func setUp() { + super.setUp() + picker = RegionPicker(frame: bounds) + picked = [] + cancels = 0 + picker.onPick = { [unowned self] in self.picked.append($0) } + picker.onCancel = { [unowned self] in self.cancels += 1 } + } + + override func tearDown() { + picker = nil + super.tearDown() + } + + private func chord(_ key: String, keyCode: UInt16, modifiers: NSEvent.ModifierFlags = []) -> KeyChord { + KeyChord(keyCode: keyCode, key: key, commandKey: nil, modifiers: modifiers, characters: key, isRepeat: false) + } + + // MARK: - Geometry + + func testDragsInEveryDirectionGiveTheSameRect() { + let expected = CGRect(x: 10, y: 20, width: 30, height: 40) + let corners: [(NSPoint, NSPoint)] = [ + (NSPoint(x: 10, y: 20), NSPoint(x: 40, y: 60)), + (NSPoint(x: 40, y: 60), NSPoint(x: 10, y: 20)), + (NSPoint(x: 10, y: 60), NSPoint(x: 40, y: 20)), + (NSPoint(x: 40, y: 20), NSPoint(x: 10, y: 60)), + ] + for (start, end) in corners { + XCTAssertEqual(RegionPicker.normalizedRect(from: start, to: end, within: bounds), expected, "\(start) to \(end)") + } + } + + func testDragsPastTheEdgeStopAtTheDisplay() { + let rect = RegionPicker.normalizedRect(from: NSPoint(x: 380, y: 290), to: NSPoint(x: 450, y: -20), within: bounds) + XCTAssertEqual(rect, CGRect(x: 380, y: 0, width: 20, height: 290)) + } + + func testOnlyRectsAtLeastTheMinimumOnBothSidesArePickable() { + let side = RegionPicker.minimumSide + XCTAssertTrue(RegionPicker.isPickable(CGRect(x: 0, y: 0, width: side, height: side))) + XCTAssertFalse(RegionPicker.isPickable(CGRect(x: 0, y: 0, width: side - 1, height: 100))) + XCTAssertFalse(RegionPicker.isPickable(CGRect(x: 0, y: 0, width: 100, height: 0))) + } + + func testSizeLabelShowsWholePoints() { + XCTAssertEqual(RegionPicker.sizeText(for: CGRect(x: 0, y: 0, width: 120.4, height: 80.6)), "120 × 81") + } + + func testSizeLabelStaysOnTheDisplay() { + let size = CGSize(width: 60, height: 18) + // Below the rect's bottom-right corner when there is room. + let below = RegionPicker.labelFrame(size: size, for: CGRect(x: 100, y: 100, width: 80, height: 50), within: bounds) + XCTAssertEqual(below.maxX, 180) + XCTAssertLessThan(below.maxY, 100) + // Inside the rect when it touches the bottom edge, and clamped to the left edge. + let inside = RegionPicker.labelFrame(size: size, for: CGRect(x: 0, y: 0, width: 20, height: 50), within: bounds) + XCTAssertGreaterThanOrEqual(inside.minY, 0) + XCTAssertEqual(inside.minX, 0) + } + + // MARK: - Mouse + + func testReleasePicksTheDraggedRect() { + picker.mouseDown(at: NSPoint(x: 200, y: 150)) + picker.mouseDragged(to: NSPoint(x: 120, y: 200)) + XCTAssertEqual(picker.selection, CGRect(x: 120, y: 150, width: 80, height: 50)) + XCTAssertTrue(picked.isEmpty, "Nothing is picked until release") + + picker.mouseUp(at: NSPoint(x: 100, y: 210)) + + XCTAssertEqual(picked, [CGRect(x: 100, y: 150, width: 100, height: 60)]) + XCTAssertEqual(cancels, 0) + } + + func testAClickKeepsPicking() { + picker.mouseDown(at: NSPoint(x: 50, y: 50)) + picker.mouseUp(at: NSPoint(x: 52, y: 51)) + + XCTAssertTrue(picked.isEmpty) + XCTAssertEqual(cancels, 0) + XCTAssertNil(picker.selection, "The next press starts a fresh rect") + + picker.mouseDown(at: NSPoint(x: 10, y: 10)) + picker.mouseUp(at: NSPoint(x: 30, y: 40)) + XCTAssertEqual(picked, [CGRect(x: 10, y: 10, width: 20, height: 30)]) + } + + func testDragWithoutAPressDoesNothing() { + picker.mouseDragged(to: NSPoint(x: 100, y: 100)) + picker.mouseUp(at: NSPoint(x: 200, y: 200)) + XCTAssertNil(picker.selection) + XCTAssertTrue(picked.isEmpty) + } + + func testRightClickCancels() throws { + let event = try XCTUnwrap(TestEvents.createMouseEvent(type: .rightMouseDown, location: NSPoint(x: 10, y: 10))) + picker.handleMouseEvent(event) + XCTAssertEqual(cancels, 1) + XCTAssertTrue(picked.isEmpty) + } + + // MARK: - Keys + + func testEscapeCancels() { + XCTAssertTrue(picker.handleKey(chord("\u{1b}", keyCode: 53))) + XCTAssertEqual(cancels, 1) + } + + func testOtherKeysAreSwallowedWithoutCancelling() { + XCTAssertTrue(picker.handleKey(chord("p", keyCode: 35))) + XCTAssertTrue(picker.handleKey(chord("s", keyCode: 1, modifiers: .command))) + XCTAssertEqual(cancels, 0) + XCTAssertTrue(picked.isEmpty) + } +} diff --git a/AnnotateTests/URLCommandTests.swift b/AnnotateTests/URLCommandTests.swift index 49c2c4a..8d0d6e1 100644 --- a/AnnotateTests/URLCommandTests.swift +++ b/AnnotateTests/URLCommandTests.swift @@ -111,6 +111,7 @@ final class URLCommandTests: XCTestCase { ("annotate://tool/brush", .unknownCommand), ("annotate://tool/arrow/extra", .unknownCommand), ("annotate://capture/screen", .notFromLinks), + ("annotate://capture/area", .notFromLinks), ("ANNOTATE://Capture/Screen/", .notFromLinks), ] for (string, reason) in cases { @@ -197,12 +198,15 @@ final class URLCommandTests: XCTestCase { let source = StubDisplayCapturing(snapshotImage: CaptureTestImages.solid(width: 8, height: 8, RGBA(r: 0, g: 0, b: 255, a: 255))) appDelegate.captureService = CaptureService(source: source, sinks: []) try open("annotate-debug://show") + let overlay = try XCTUnwrap(overlay) XCTAssertNil(appDelegate.openCommandURL(try link("annotate-debug://capture/screen"))) - try open("annotate-debug://capture/screen") + XCTAssertNil(appDelegate.openCommandURL(try link("annotate-debug://capture/area"))) + try open("annotate-debug://capture/screen", "annotate-debug://capture/area") XCTAssertNil(appDelegate.captureTask) XCTAssertEqual(source.captureCount, 0) + XCTAssertFalse(overlay.isRegionPickerOpen) } func testMalformedLinksChangeNothing() throws { From 80e5928cd847e208889d5df8ea5259b7bbfdd4ce Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Mon, 2 Nov 2026 23:50:50 -0800 Subject: [PATCH 07/17] docs(readme): Document Capture Area and when capture needs Screen Recording Adds the Shift-Command-S row in Quick Actions, Capture Area in the Capture section and the Utilities list, and a note under the link table that capture has no annotate:// link. The Screen Recording entry now says capture works without the permission while a fully opaque board is showing, and that Show in Finder reports a folder it can't create. --- README.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 4b20c0e..8ac26db 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,7 @@ brew install --cask annotate #### ⚡ Quick Actions -Fade mode, toolbar visibility, size stepping, Clear All, and Capture Screen can be rebound in **Settings → Shortcuts**, using a single key or a modifier combination. The table shows their defaults. +Fade mode, toolbar visibility, size stepping, Clear All, Capture Screen, and Capture Area can be rebound in **Settings → Shortcuts**, using a single key or a modifier combination. The table shows their defaults. | Shortcut | Action | Description | | ----------------------------------------------------- | -------------------- | -------------------------------------------------------------------------- | @@ -159,6 +159,7 @@ Fade mode, toolbar visibility, size stepping, Clear All, and Capture Screen can | Delete | **Delete** | Remove selected objects or most recent annotation | | Option + Delete | **Clear All** | Remove all annotations | | Command + S | **Capture Screen** | Save the display with its annotations as a PNG and copy it | +| Command + Shift + S | **Capture Area** | Drag out part of the display, save it as a PNG, and copy it | | Command + Z | **Undo** | Undo the last action | | Command + Shift + Z | **Redo** | Redo the last undone action | | Mouse Backward Button | **Undo** | Undo the last action (mouse button 3) | @@ -394,6 +395,8 @@ open "annotate://tool/arrow" | `annotate://fade/` | Turns Fade Mode on, off, or toggles it. In Always-On Mode it applies on exit. | | `annotate://board/` | Turns the whiteboard (blackboard in Dark Mode) on, off, or toggles it. | +Capture has no link. Any web page or app can open a link, so links never read the screen or write to the clipboard. Use the keyboard or the menu bar icon instead. + - **Tools:** `pen`, `arrow`, `line`, `highlighter`, `rectangle`, `circle`, `redact`, `text`, `counter`, `select`, `eraser` - **Colors:** `red`, `orange`, `yellow`, `green`, `cyan`, `indigo`, `magenta`, `white`, `black` @@ -458,8 +461,9 @@ Cursor effects hide while the macOS screenshot selection (Shift + Date: Tue, 3 Nov 2026 07:25:55 -0800 Subject: [PATCH 08/17] fix(capture): Keep Always-On drawings through Capture Area Always-On holds annotations in Persist, so with Fade Mode on it can show drawings older than their fade. Capture Area from Always-On opened the interactive overlay, which put Fade Mode back and expired those drawings before the picker could freeze them, so neither the picker nor the image had them. The overlay Capture Area opens from Always-On now keeps Always-On's Persist until the picker closes, then takes the Fade Mode setting back. Screen Recording is also checked before Always-On is left, so a denied capture goes through the usual flow and Always-On comes back with its drawings. The global Always-On shortcut could also turn the overlay click-through with the picker still on it, dimmed, frozen, and impossible to finish. Entering Always-On now closes the picker first, and an overlay that came from Always-On stays in Persist. --- Annotate/AppDelegate+Capture.swift | 50 ++++++++++--- Annotate/AppDelegate.swift | 7 +- Annotate/OverlayWindow.swift | 12 ++- AnnotateTests/AnnotateCommandTests.swift | 94 ++++++++++++++++++++++++ 4 files changed, 148 insertions(+), 15 deletions(-) diff --git a/Annotate/AppDelegate+Capture.swift b/Annotate/AppDelegate+Capture.swift index 047e76c..abab6ac 100644 --- a/Annotate/AppDelegate+Capture.swift +++ b/Annotate/AppDelegate+Capture.swift @@ -57,32 +57,51 @@ extension AppDelegate { /// 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. + // 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 - } - guard !overlay.isRegionPickerOpen else { return } - // Without Screen Recording the drag would come to nothing, so ask before it starts. - let board = BoardManager.shared - if !captureService.source.canCapture, - !CaptureScene.boardCoversScreen(board.appearance, opacity: CGFloat(board.opacity)) - { - showScreenRecordingOff(on: overlay) - return + 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) - overlay.beginRegionPicker { [weak self, weak overlay] rect in + 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( @@ -96,6 +115,13 @@ extension AppDelegate { } } + /// 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, diff --git a/Annotate/AppDelegate.swift b/Annotate/AppDelegate.swift index 04e21f5..8171716 100644 --- a/Annotate/AppDelegate.swift +++ b/Annotate/AppDelegate.swift @@ -69,6 +69,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 = [] + /// 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 = [] /// 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. @@ -901,7 +905,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() } diff --git a/Annotate/OverlayWindow.swift b/Annotate/OverlayWindow.swift index 5f40f23..662f1d8 100644 --- a/Annotate/OverlayWindow.swift +++ b/Annotate/OverlayWindow.swift @@ -40,6 +40,7 @@ class OverlayWindow: NSPanel { private var mouseCoalescingSnapshot: Bool? /// Capture Area's picker while it is open. See `beginRegionPicker(onPick:)`. private(set) var regionPicker: RegionPicker? + private var regionPickerDismissHandler: (() -> Void)? // Latched at mouseDown: currentTool can change mid-drag via tool shortcuts private var activeFreehandTool: ToolType? private var activeShapeTool: ToolType? @@ -722,9 +723,10 @@ class OverlayWindow: NSPanel { /// quick picker, commits a label being typed, drops any drawing in progress, freezes the /// fade, and moves the toolbar aside so the whole display can be picked. `onPick` gets the /// picked rectangle in the overlay view's coordinates, before the picker closes, so a - /// capture made there reads the annotations at the fade the picker showed. + /// capture made there reads the annotations at the fade the picker showed. `onDismiss` + /// runs once the picker has closed, whether it picked or not. @discardableResult - func beginRegionPicker(onPick: @escaping (CGRect) -> Void) -> Bool { + func beginRegionPicker(onDismiss: (() -> Void)? = nil, onPick: @escaping (CGRect) -> Void) -> Bool { guard regionPicker == nil, !overlayView.isReadOnlyMode else { return false } cancelQuickPicker() if let activeField = overlayView.activeTextField { @@ -741,6 +743,7 @@ class OverlayWindow: NSPanel { picker.onCancel = { [weak self] in self?.cancelRegionPicker() } overlayView.addSubview(picker) regionPicker = picker + regionPickerDismissHandler = onDismiss overlayView.freezeFade() toolbarPanel?.detach() invalidateCursorRects(for: picker) @@ -757,6 +760,9 @@ class OverlayWindow: NSPanel { updateToolbarVisibility() invalidateCursorRects(for: overlayView) overlayView.updateCursor() + let onDismiss = regionPickerDismissHandler + regionPickerDismissHandler = nil + onDismiss?() } override func mouseMoved(with event: NSEvent) { @@ -1596,6 +1602,8 @@ class OverlayWindow: NSPanel { } func prepareForAlwaysOnMode() { + // Always-On is click-through, so a picker left open could never finish. + cancelRegionPicker() cancelQuickPicker() restoreMouseCoalescing() cancelFreehandStroke() diff --git a/AnnotateTests/AnnotateCommandTests.swift b/AnnotateTests/AnnotateCommandTests.swift index 5dc2d03..ea4f054 100644 --- a/AnnotateTests/AnnotateCommandTests.swift +++ b/AnnotateTests/AnnotateCommandTests.swift @@ -1023,6 +1023,100 @@ final class AnnotateCommandTests: XCTestCase { XCTAssertEqual(overlay.overlayView.paths.count, 1, "The Always-On drawings were on screen, so they stay") } + /// Enters Always-On in Fade Mode with a thick red outline around the bottom-left corner + /// made long ago: Always-On holds it in Persist, while Fade Mode would have expired it. + @discardableResult + private func showAnOldDrawingInAlwaysOn() throws -> OverlayView { + testDefaults.settings[.fadeMode] = true + let view = try XCTUnwrap(overlay.overlayView) + let clock: CFTimeInterval = 1000 + view.fadeClock = { clock } + appDelegate.toggleAlwaysOnMode() + var outline = Rectangle( + startPoint: .zero, endPoint: NSPoint(x: 40, y: 40), color: .red, lineWidth: 20, style: .outline) + outline.creationTime = clock - view.fadeDuration * 10 + view.rectangles = [outline] + return view + } + + func testCaptureAreaFromAlwaysOnKeepsDrawingsPastTheirFade() async throws { + let (_, pasteboard) = try useStubCapture() + let view = try showAnOldDrawingInAlwaysOn() + + run(.capture(.area)) + + XCTAssertFalse(appDelegate.alwaysOnMode) + XCTAssertTrue(overlay.isRegionPickerOpen) + XCTAssertFalse(view.fadeMode, "Always-On's Persist holds through the pick") + XCTAssertEqual(view.rectangles.count, 1, "Leaving Always-On must not expire what it showed") + + try drag(from: .zero, to: NSPoint(x: 80, y: 60)) + await appDelegate.captureTask?.value + + let image = try XCTUnwrap(NSBitmapImageRep(data: try XCTUnwrap(pasteboard.data(forType: .png)))?.cgImage) + let corner = CaptureTestImages.pixel(image, x: 2, y: image.height - 2) + XCTAssertTrue(corner.isClose(to: RGBA(r: 255, g: 0, b: 0, a: 255), tolerance: 40), "\(corner)") + XCTAssertTrue(view.fadeMode, "The Fade Mode setting is back once the picker closes") + XCTAssertTrue(appDelegate.overlaysHoldingAlwaysOnFade.isEmpty) + } + + func testCaptureAreaFromAlwaysOnGivesFadeModeBackOnEscape() throws { + try useStubCapture() + let view = try showAnOldDrawingInAlwaysOn() + run(.capture(.area)) + + try pressEscape() + + XCTAssertTrue(view.fadeMode) + XCTAssertTrue(appDelegate.overlaysHoldingAlwaysOnFade.isEmpty) + } + + func testAlwaysOnShortcutWhilePickingClosesThePicker() throws { + try useStubCapture() + run(.show) + let view = try XCTUnwrap(overlay.overlayView) + run(.capture(.area)) + XCTAssertTrue(overlay.isRegionPickerOpen) + + // The global Always-On shortcut calls this directly, outside the picker's key handling. + appDelegate.toggleAlwaysOnMode() + + XCTAssertTrue(appDelegate.alwaysOnMode) + XCTAssertFalse(overlay.isRegionPickerOpen) + XCTAssertFalse(view.isFadeFrozen) + XCTAssertFalse(view.subviews.contains { $0 is RegionPicker }, "No dimming left on a click-through overlay") + } + + func testAlwaysOnShortcutWhilePickingFromAlwaysOnKeepsTheDrawings() throws { + try useStubCapture() + let view = try showAnOldDrawingInAlwaysOn() + run(.capture(.area)) + + appDelegate.toggleAlwaysOnMode() + + XCTAssertTrue(appDelegate.alwaysOnMode) + XCTAssertFalse(view.fadeMode, "Back in Always-On's Persist") + XCTAssertEqual(view.rectangles.count, 1) + XCTAssertTrue(appDelegate.overlaysHoldingAlwaysOnFade.isEmpty) + } + + func testCaptureAreaWithoutScreenRecordingInAlwaysOnKeepsTheDrawings() throws { + try useStubCapture(canCapture: false) + appDelegate.screenRecordingNoticeDelay = 0 + var closeSettings: (@MainActor () -> Void)? + appDelegate.openSettingsPane = { _, _, onClose in closeSettings = onClose } + let view = try showAnOldDrawingInAlwaysOn() + + run(.capture(.area)) + runLoop { closeSettings != nil } + + XCTAssertFalse(overlay.isRegionPickerOpen) + XCTAssertTrue(appDelegate.alwaysOnMode, "Asking for access never leaves Always-On") + try XCTUnwrap(closeSettings)() + XCTAssertTrue(overlay.isVisible) + XCTAssertEqual(view.rectangles.count, 1) + } + func testCaptureAreaFromAClosedOverlayStillClearsWithClearDrawingsOnStart() throws { try useStubCapture() testDefaults.settings[.clearDrawingsOnStart] = true From 30f12d399e60c04d68adda2a5aaf2f4516cc129c Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Tue, 3 Nov 2026 07:26:01 -0800 Subject: [PATCH 09/17] fix(capture): Show the crosshair over an active cursor style With an active cursor style on, the cursor manager kept hiding the system cursor and drawing its own while Capture Area's picker was open, so the precise crosshair never showed. The style now stands down on the picker's display while the picker is open: the system cursor is shown and the style's cursor isn't drawn. Closing the picker, by picking or cancelling, brings the style back. --- Annotate/CursorHighlightManager.swift | 6 ++-- Annotate/OverlayWindow.swift | 9 +++++- AnnotateTests/AnnotateCommandTests.swift | 37 ++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 3 deletions(-) diff --git a/Annotate/CursorHighlightManager.swift b/Annotate/CursorHighlightManager.swift index 88dced6..820cb04 100644 --- a/Annotate/CursorHighlightManager.swift +++ b/Annotate/CursorHighlightManager.swift @@ -300,7 +300,9 @@ class CursorHighlightManager: @unchecked Sendable { guard activeCursorStyle != .none, !isScreenshotSelectionActive, let overlay = AppDelegate.shared?.overlayWindows[screen], - overlay.isVisible else { return false } + overlay.isVisible, + // Capture Area's picker shows the system crosshair instead. + !overlay.isRegionPickerOpen else { return false } // The always-on overlay is click-through, so an excluded app underneath can capture and pin the cursor. return !(isExcludedAppActive && overlay.ignoresMouseEvents) } @@ -442,7 +444,7 @@ class CursorHighlightManager: @unchecked Sendable { // MARK: - System Cursor Visibility - private var isCursorHidden = false + private(set) var isCursorHidden = false func hideSystemCursor() { guard !isCursorHidden else { return } diff --git a/Annotate/OverlayWindow.swift b/Annotate/OverlayWindow.swift index 662f1d8..8f49764 100644 --- a/Annotate/OverlayWindow.swift +++ b/Annotate/OverlayWindow.swift @@ -746,18 +746,25 @@ class OverlayWindow: NSPanel { regionPickerDismissHandler = onDismiss overlayView.freezeFade() toolbarPanel?.detach() + // An active cursor style hides the system cursor and draws its own; the picker needs + // the crosshair, so the style stands down on this display until the picker closes. + let cursorManager = CursorHighlightManager.shared + cursorManager.overlayVisibilityChanged() + cursorManager.showSystemCursor() invalidateCursorRects(for: picker) NSCursor.crosshair.set() return true } - /// Closes Capture Area's picker without picking, and lets the fade run again. + /// Closes Capture Area's picker without picking, and lets the fade and the active cursor + /// style run again. func cancelRegionPicker() { guard let picker = regionPicker else { return } regionPicker = nil picker.removeFromSuperview() overlayView.resumeFade() updateToolbarVisibility() + CursorHighlightManager.shared.overlayVisibilityChanged() invalidateCursorRects(for: overlayView) overlayView.updateCursor() let onDismiss = regionPickerDismissHandler diff --git a/AnnotateTests/AnnotateCommandTests.swift b/AnnotateTests/AnnotateCommandTests.swift index ea4f054..e1eeac1 100644 --- a/AnnotateTests/AnnotateCommandTests.swift +++ b/AnnotateTests/AnnotateCommandTests.swift @@ -1117,6 +1117,43 @@ final class AnnotateCommandTests: XCTestCase { XCTAssertEqual(view.rectangles.count, 1) } + func testActiveCursorStyleStandsDownWhilePicking() async throws { + try useStubCapture() + let original = CursorHighlightManager.shared + let manager = CursorHighlightManager(userDefaults: testDefaults) + CursorHighlightManager.shared = manager + addTeardownBlock { @MainActor in + manager.showSystemCursor() + CursorHighlightManager.shared = original + } + manager.activeCursorStyle = .circle + run(.show) + let view = try XCTUnwrap(overlay.overlayView) + view.updateCursor() + XCTAssertTrue(manager.shouldShowActiveCursorOnScreen(screen)) + XCTAssertTrue(manager.isCursorHidden) + + // Opening: the crosshair shows, and the canvas asking again doesn't hide it. + run(.capture(.area)) + XCTAssertFalse(manager.shouldShowActiveCursorOnScreen(screen)) + XCTAssertFalse(manager.isCursorHidden) + view.updateCursor() + XCTAssertFalse(manager.isCursorHidden) + + // Cancelling brings the style back. + try pressEscape() + XCTAssertTrue(manager.shouldShowActiveCursorOnScreen(screen)) + XCTAssertTrue(manager.isCursorHidden) + + // So does picking. + run(.capture(.area)) + XCTAssertFalse(manager.isCursorHidden) + try drag(from: .zero, to: NSPoint(x: 80, y: 60)) + XCTAssertTrue(manager.shouldShowActiveCursorOnScreen(screen)) + XCTAssertTrue(manager.isCursorHidden) + await appDelegate.captureTask?.value + } + func testCaptureAreaFromAClosedOverlayStillClearsWithClearDrawingsOnStart() throws { try useStubCapture() testDefaults.settings[.clearDrawingsOnStart] = true From 6fe54cf00f9a46616b812878c4e5cf576dd37ec4 Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Tue, 3 Nov 2026 07:26:01 -0800 Subject: [PATCH 10/17] test(capture): Render the area picker and check its pixels The picker's tests checked geometry and callbacks but never drew it. New tests render its layers over a known background and check the dim before a drag, the clear rectangle with a dimmed outside, the white border, the size label, and the reset to a full dim after a click. The layers are named, so tests find them by name. --- Annotate/RegionPicker.swift | 10 ++ AnnotateTests/RegionPickerRenderTests.swift | 113 ++++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 AnnotateTests/RegionPickerRenderTests.swift diff --git a/Annotate/RegionPicker.swift b/Annotate/RegionPicker.swift index 772e5ba..6716264 100644 --- a/Annotate/RegionPicker.swift +++ b/Annotate/RegionPicker.swift @@ -14,6 +14,13 @@ final class RegionPicker: NSView { /// How dark the area outside the rectangle gets. static let dimOpacity: Float = 0.35 + /// The picker's layers, by name, so tests can find them without relying on their order. + enum LayerName { + static let dim = "regionPicker.dim" + static let border = "regionPicker.border" + static let sizeLabel = "regionPicker.sizeLabel" + } + /// Called with the picked rectangle in this view's coordinates. var onPick: ((CGRect) -> Void)? var onCancel: (() -> Void)? @@ -30,6 +37,9 @@ final class RegionPicker: NSView { wantsLayer = true autoresizingMask = [.width, .height] + dimLayer.name = LayerName.dim + borderLayer.name = LayerName.border + sizeLabel.name = LayerName.sizeLabel dimLayer.fillRule = .evenOdd dimLayer.fillColor = NSColor.black.withAlphaComponent(CGFloat(Self.dimOpacity)).cgColor borderLayer.fillColor = nil diff --git a/AnnotateTests/RegionPickerRenderTests.swift b/AnnotateTests/RegionPickerRenderTests.swift new file mode 100644 index 0000000..de76820 --- /dev/null +++ b/AnnotateTests/RegionPickerRenderTests.swift @@ -0,0 +1,113 @@ +import XCTest + +@testable import Annotate + +/// Renders the picker's layers over a solid background, as they composite on screen. +@MainActor +final class RegionPickerRenderTests: XCTestCase { + private static let white = RGBA(r: 255, g: 255, b: 255, a: 255) + private static let black = RGBA(r: 0, g: 0, b: 0, a: 255) + /// White under the dim layer. + private static let dimmedWhite: RGBA = { + let value = Int((255 * (1 - Double(RegionPicker.dimOpacity))).rounded()) + return RGBA(r: value, g: value, b: value, a: 255) + }() + + private let bounds = CGRect(x: 0, y: 0, width: 200, height: 100) + + /// The picker's layers over `background`, as an image whose rows run top-down. + private func render(_ picker: RegionPicker, over background: RGBA) throws -> CGImage { + let context = try XCTUnwrap( + CGContext( + data: nil, + width: Int(bounds.width), + height: Int(bounds.height), + bitsPerComponent: 8, + bytesPerRow: 0, + space: CaptureTestImages.srgb, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)) + context.setFillColor(background.cgColor) + context.fill(bounds) + try XCTUnwrap(picker.layer).render(in: context) + return try XCTUnwrap(context.makeImage()) + } + + /// The pixel at a point in the picker's coordinates, whose origin is the bottom-left. + private func pixel(_ image: CGImage, at point: NSPoint) -> RGBA { + CaptureTestImages.pixel(image, x: Int(point.x), y: image.height - 1 - Int(point.y)) + } + + private func sublayer(_ name: String, of picker: RegionPicker) throws -> CALayer { + try XCTUnwrap(picker.layer?.sublayers?.first { $0.name == name }, name) + } + + func testBeforeADragTheWholeDisplayDims() throws { + let image = try render(RegionPicker(frame: bounds), over: Self.white) + + for point in [NSPoint(x: 5, y: 5), NSPoint(x: 100, y: 50), NSPoint(x: 195, y: 95)] { + let color = pixel(image, at: point) + XCTAssertTrue(color.isClose(to: Self.dimmedWhite), "\(point): \(color)") + } + } + + func testTheDraggedRectStaysClearWithADimmedOutside() throws { + let picker = RegionPicker(frame: bounds) + picker.mouseDown(at: NSPoint(x: 20, y: 20)) + picker.mouseDragged(to: NSPoint(x: 120, y: 80)) + + let image = try render(picker, over: Self.white) + + let inside = pixel(image, at: NSPoint(x: 60, y: 60)) + XCTAssertTrue(inside.isClose(to: Self.white), "Inside the rect is untouched: \(inside)") + for point in [NSPoint(x: 5, y: 5), NSPoint(x: 160, y: 50), NSPoint(x: 60, y: 95)] { + let color = pixel(image, at: point) + XCTAssertTrue(color.isClose(to: Self.dimmedWhite), "\(point): \(color)") + } + } + + func testTheRectHasAWhiteBorder() throws { + let picker = RegionPicker(frame: bounds) + picker.mouseDown(at: NSPoint(x: 20, y: 20)) + picker.mouseDragged(to: NSPoint(x: 120, y: 80)) + + let image = try render(picker, over: Self.black) + + // The border runs just outside the rect's left and top edges. + for point in [NSPoint(x: 19, y: 50), NSPoint(x: 60, y: 80)] { + let color = pixel(image, at: point) + XCTAssertTrue(color.isClose(to: Self.white, tolerance: 40), "\(point): \(color)") + } + let inside = pixel(image, at: NSPoint(x: 60, y: 50)) + XCTAssertTrue(inside.isClose(to: Self.black), "\(inside)") + } + + func testTheSizeLabelShowsOnItsDarkBackground() throws { + let picker = RegionPicker(frame: bounds) + picker.mouseDown(at: NSPoint(x: 20, y: 20)) + picker.mouseDragged(to: NSPoint(x: 120, y: 80)) + let label = try sublayer(RegionPicker.LayerName.sizeLabel, of: picker) + XCTAssertFalse(label.isHidden) + XCTAssertEqual((label as? CATextLayer)?.string as? String, "100 × 60") + + let image = try render(picker, over: Self.white) + + // The label's corner, clear of its text, shows the dark background over white. + let corner = pixel(image, at: NSPoint(x: label.frame.minX + 2, y: label.frame.midY)) + XCTAssertLessThan(corner.r, 120, "\(corner)") + } + + func testAClickResetsTheDrawingToAFullDim() throws { + let picker = RegionPicker(frame: bounds) + picker.mouseDown(at: NSPoint(x: 20, y: 20)) + picker.mouseDragged(to: NSPoint(x: 120, y: 80)) + // Released as a click would, under the minimum size. + picker.mouseUp(at: NSPoint(x: 21, y: 21)) + + let image = try render(picker, over: Self.white) + + let formerlyInside = pixel(image, at: NSPoint(x: 60, y: 60)) + XCTAssertTrue(formerlyInside.isClose(to: Self.dimmedWhite), "\(formerlyInside)") + XCTAssertTrue(try sublayer(RegionPicker.LayerName.sizeLabel, of: picker).isHidden) + XCTAssertNil((try sublayer(RegionPicker.LayerName.border, of: picker) as? CAShapeLayer)?.path) + } +} From e9303baa3abe2cab7dcf80ade8a27637228a8a78 Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Tue, 3 Nov 2026 07:26:01 -0800 Subject: [PATCH 11/17] refactor(capture): Remove the unused CaptureDelivery.destination --- Annotate/Capture.swift | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Annotate/Capture.swift b/Annotate/Capture.swift index 9f5e5a5..3032ffb 100644 --- a/Annotate/Capture.swift +++ b/Annotate/Capture.swift @@ -119,13 +119,6 @@ struct Capture { enum CaptureDelivery: Equatable, Sendable { case file(URL) case clipboard - - var destination: CaptureDestination { - switch self { - case .file: return .file - case .clipboard: return .clipboard - } - } } /// The kinds of place a capture can go. From 3ce78a2bf05ba96fa02bfc27f62a4f70e7f78428 Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Tue, 3 Nov 2026 08:08:54 -0800 Subject: [PATCH 12/17] fix(capture): Show the crosshair while picking with a cursor style on The canvas owns the overlay's only cursor-update tracking area, so AppKit asks it, not the picker on top, for the cursor on every move. With the cursor style stood down for the picker, the canvas fell back to the arrow. The picker's own tracking area was never installed: AppKit didn't call its updateTrackingAreas while it was open. The canvas now takes a cursor override that wins over every tool and cursor style in cursorUpdate, updateCursor, and its cursor rects. Capture Area sets it to the crosshair while the picker is open. The picker's dead tracking-area code is gone. The new test sends cursor updates to whatever owns the cursor-update tracking areas, as AppKit does, and fails on the old code for every style. The stand-down test now asks the picking display's canvas directly, since with two displays the hidden overlay's refresh could run last and show the system cursor. --- Annotate/OverlayView.swift | 25 +++++++++- Annotate/OverlayWindow.swift | 10 ++-- Annotate/RegionPicker.swift | 15 +----- AnnotateTests/AnnotateCommandTests.swift | 59 +++++++++++++++++++++++- 4 files changed, 88 insertions(+), 21 deletions(-) diff --git a/Annotate/OverlayView.swift b/Annotate/OverlayView.swift index d4c4317..e04e723 100644 --- a/Annotate/OverlayView.swift +++ b/Annotate/OverlayView.swift @@ -379,7 +379,23 @@ class OverlayView: NSView, NSTextFieldDelegate { updateCursorTrackingArea() } + /// A cursor that replaces every tool and cursor-style cursor on this canvas while set, as + /// Capture Area's crosshair does while its picker is open. The canvas owns the window's + /// cursor-update tracking area, so it, not the picker on top, answers cursor updates; left + /// to itself it would fall back to the arrow. + var cursorOverride: NSCursor? { + didSet { + guard cursorOverride !== oldValue else { return } + window?.invalidateCursorRects(for: self) + updateCursor() + } + } + override func cursorUpdate(with event: NSEvent) { + if let cursorOverride { + cursorOverride.set() + return + } // Over a side handle, the label's width is what is about to change. if resizeHandle != nil || textResizeHandle(at: convert(event.locationInWindow, from: nil)) != nil { @@ -398,6 +414,11 @@ class OverlayView: NSView, NSTextFieldDelegate { } func updateCursor() { + if let cursorOverride { + CursorHighlightManager.shared.showSystemCursor() + cursorOverride.set() + return + } // Show I-beam cursor in text mode when no text field is active if currentTool == .text && activeTextField == nil { NSCursor.iBeam.set() @@ -415,7 +436,9 @@ class OverlayView: NSView, NSTextFieldDelegate { override func resetCursorRects() { super.resetCursorRects() - if currentTool == .text && activeTextField == nil { + if let cursorOverride { + addCursorRect(bounds, cursor: cursorOverride) + } else if currentTool == .text && activeTextField == nil { addCursorRect(bounds, cursor: .iBeam) } else if shouldShowActiveCursorForThisOverlay() { addCursorRect(bounds, cursor: Self.transparentCursor) diff --git a/Annotate/OverlayWindow.swift b/Annotate/OverlayWindow.swift index 8f49764..0a085c8 100644 --- a/Annotate/OverlayWindow.swift +++ b/Annotate/OverlayWindow.swift @@ -748,11 +748,10 @@ class OverlayWindow: NSPanel { toolbarPanel?.detach() // An active cursor style hides the system cursor and draws its own; the picker needs // the crosshair, so the style stands down on this display until the picker closes. - let cursorManager = CursorHighlightManager.shared - cursorManager.overlayVisibilityChanged() - cursorManager.showSystemCursor() + // The canvas answers the window's cursor updates, so it shows the crosshair too. + overlayView.cursorOverride = .crosshair + CursorHighlightManager.shared.overlayVisibilityChanged() invalidateCursorRects(for: picker) - NSCursor.crosshair.set() return true } @@ -764,9 +763,8 @@ class OverlayWindow: NSPanel { picker.removeFromSuperview() overlayView.resumeFade() updateToolbarVisibility() + overlayView.cursorOverride = nil CursorHighlightManager.shared.overlayVisibilityChanged() - invalidateCursorRects(for: overlayView) - overlayView.updateCursor() let onDismiss = regionPickerDismissHandler regionPickerDismissHandler = nil onDismiss?() diff --git a/Annotate/RegionPicker.swift b/Annotate/RegionPicker.swift index 6716264..4c9e709 100644 --- a/Annotate/RegionPicker.swift +++ b/Annotate/RegionPicker.swift @@ -147,23 +147,12 @@ final class RegionPicker: NSView { // MARK: - Cursor and layers + /// The canvas under the picker owns the window's cursor-update tracking area, so the + /// overlay also sets the crosshair there while the picker is open. override func resetCursorRects() { addCursorRect(bounds, cursor: .crosshair) } - override func updateTrackingAreas() { - super.updateTrackingAreas() - trackingAreas.forEach(removeTrackingArea) - addTrackingArea( - NSTrackingArea( - rect: bounds, options: [.cursorUpdate, .activeAlways, .inVisibleRect], owner: self, userInfo: nil)) - } - - /// The canvas under the picker sets its own cursor on these, so the picker answers first. - override func cursorUpdate(with event: NSEvent) { - NSCursor.crosshair.set() - } - override func layout() { super.layout() updateLayers() diff --git a/AnnotateTests/AnnotateCommandTests.swift b/AnnotateTests/AnnotateCommandTests.swift index e1eeac1..b6c9903 100644 --- a/AnnotateTests/AnnotateCommandTests.swift +++ b/AnnotateTests/AnnotateCommandTests.swift @@ -1140,9 +1140,12 @@ final class AnnotateCommandTests: XCTestCase { view.updateCursor() XCTAssertFalse(manager.isCursorHidden) - // Cancelling brings the style back. + // Cancelling brings the style back. The canvas is asked directly: a state change also + // refreshes hidden overlays on other displays, which show the system cursor, so with + // two displays the shared result depends on which overlay goes last. try pressEscape() XCTAssertTrue(manager.shouldShowActiveCursorOnScreen(screen)) + view.updateCursor() XCTAssertTrue(manager.isCursorHidden) // So does picking. @@ -1150,10 +1153,64 @@ final class AnnotateCommandTests: XCTestCase { XCTAssertFalse(manager.isCursorHidden) try drag(from: .zero, to: NSPoint(x: 80, y: 60)) XCTAssertTrue(manager.shouldShowActiveCursorOnScreen(screen)) + view.updateCursor() XCTAssertTrue(manager.isCursorHidden) await appDelegate.captureTask?.value } + /// Sends a cursor update the way AppKit does: to the owner of each cursor-update tracking + /// area in the overlay, which is the canvas, not the picker on top of it. + private func deliverCursorUpdate() throws { + let event = try XCTUnwrap( + NSEvent.enterExitEvent( + with: .cursorUpdate, + location: NSPoint(x: 300, y: 300), + modifierFlags: [], + timestamp: 0, + windowNumber: overlay.windowNumber, + context: nil, + eventNumber: 0, + trackingNumber: 0, + userData: nil)) + let views = [overlay.overlayView as NSView] + overlay.overlayView.subviews + let owners = views.flatMap(\.trackingAreas) + .filter { $0.options.contains(.cursorUpdate) } + .compactMap { $0.owner as? NSResponder } + XCTAssertFalse(owners.isEmpty, "Something must answer cursor updates") + owners.forEach { $0.cursorUpdate(with: event) } + } + + func testThePickerShowsTheCrosshairWithEveryCursorStyle() throws { + try useStubCapture() + let original = CursorHighlightManager.shared + let manager = CursorHighlightManager(userDefaults: testDefaults) + CursorHighlightManager.shared = manager + addTeardownBlock { @MainActor in + manager.showSystemCursor() + CursorHighlightManager.shared = original + } + run(.show) + let view = try XCTUnwrap(overlay.overlayView) + + for style in ActiveCursorStyle.allCases { + manager.activeCursorStyle = style + run(.capture(.area)) + NSCursor.arrow.set() + + // AppKit asks again on every move across the overlay; each answer must be the crosshair. + try deliverCursorUpdate() + XCTAssertTrue(NSCursor.current === NSCursor.crosshair, "\(style) while picking") + view.updateCursor() + XCTAssertTrue(NSCursor.current === NSCursor.crosshair, "\(style) after the canvas refreshes its cursor") + XCTAssertFalse(manager.isCursorHidden, "\(style)") + + try pressEscape() + try deliverCursorUpdate() + XCTAssertFalse(NSCursor.current === NSCursor.crosshair, "\(style): the tool's cursor is back") + XCTAssertEqual(manager.isCursorHidden, style != .none, "\(style)") + } + } + func testCaptureAreaFromAClosedOverlayStillClearsWithClearDrawingsOnStart() throws { try useStubCapture() testDefaults.settings[.clearDrawingsOnStart] = true From f26228c80d8ee21e28a10c2e1c321d3e45172e95 Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Tue, 3 Nov 2026 08:12:34 -0800 Subject: [PATCH 13/17] feat(capture): Add a debug switch that makes every capture save fail A debug build launched with --fail-capture-saves fails each save before any bytes land, so the save-failure report can be checked live: the HUD, or the alert with Hide Tool Feedback on. The clipboard copy still works, and the alert's detail names the switch so the failure can't pass for a real one. Release builds don't have the switch. The app's capture sinks now come from AppDelegate.captureSinks, which a test runs with and without the switch. --- AGENTS.md | 2 ++ Annotate/AppDelegate+Capture.swift | 17 +++++++++++++++++ Annotate/AppDelegate.swift | 4 +--- Annotate/CaptureSinks.swift | 29 +++++++++++++++++++++++++---- AnnotateTests/CaptureTests.swift | 28 ++++++++++++++++++++++++++++ 5 files changed, 73 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 72ab69a..23b9d9c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/Annotate/AppDelegate+Capture.swift b/Annotate/AppDelegate+Capture.swift index abab6ac..48492ae 100644 --- a/Annotate/AppDelegate+Capture.swift +++ b/Annotate/AppDelegate+Capture.swift @@ -13,6 +13,23 @@ extension AppDelegate { 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 diff --git a/Annotate/AppDelegate.swift b/Annotate/AppDelegate.swift index 8171716..57d58b5 100644 --- a/Annotate/AppDelegate.swift +++ b/Annotate/AppDelegate.swift @@ -34,9 +34,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem /// 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: [FileSink(folder: FileSink.defaultFolder), ClipboardSink()]) + 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? /// How long the Screen Recording HUD stays up before the overlay closes for Settings. diff --git a/Annotate/CaptureSinks.swift b/Annotate/CaptureSinks.swift index a4c64a7..6af0bc0 100644 --- a/Annotate/CaptureSinks.swift +++ b/Annotate/CaptureSinks.swift @@ -4,13 +4,16 @@ import AppKit /// screenshots: `Annotate 2026-11-01 at 10.23.45.png`, then ` (2)`, ` (3)` on collision. struct FileSink: CaptureSink { var folder: URL + /// Writes each capture's temporary file. Debug builds can make it fail on purpose; see + /// `failSavesArgument`. + var writeBytes: @Sendable (Data, URL) throws -> Void = writeWithoutOverwriting var destination: CaptureDestination { .file } /// `~/Pictures/Annotate`. Pictures is reachable through the app's Pictures entitlement /// and, unlike Desktop, Documents, and Downloads, has no first-access prompt that would /// open under the overlay. - static var defaultFolder: URL { + nonisolated static var defaultFolder: URL { realHomeDirectory .appendingPathComponent("Pictures", isDirectory: true) .appendingPathComponent("Annotate", isDirectory: true) @@ -18,7 +21,7 @@ struct FileSink: CaptureSink { /// The user's home folder. In the sandbox `homeDirectoryForCurrentUser` is the app's /// container, which would hide captures inside `~/Library/Containers`. - static var realHomeDirectory: URL { + nonisolated static var realHomeDirectory: URL { if let entry = getpwuid(getuid()), let directory = entry.pointee.pw_dir { return URL(fileURLWithPath: String(cString: directory), isDirectory: true) } @@ -27,7 +30,7 @@ struct FileSink: CaptureSink { func deliver(_ capture: Capture, png: Data) async throws -> CaptureDelivery { let baseName = Self.baseName(for: capture.capturedAt) - return .file(try await Self.write(png, baseName: baseName, in: folder)) + return .file(try await Self.write(png, baseName: baseName, in: folder, writeBytes: writeBytes)) } /// `Annotate 2026-11-01 at 10.23.45`, in the current time zone. @@ -53,7 +56,7 @@ struct FileSink: CaptureSink { /// partway. nonisolated static func write( _ data: Data, baseName: String, in folder: URL, - writeBytes: @Sendable (Data, URL) throws -> Void = { try $0.write(to: $1, options: .withoutOverwriting) } + writeBytes: @Sendable (Data, URL) throws -> Void = writeWithoutOverwriting ) async throws -> URL { let fileManager = FileManager.default try fileManager.createDirectory(at: folder, withIntermediateDirectories: true) @@ -73,6 +76,24 @@ struct FileSink: CaptureSink { } } + nonisolated static let writeWithoutOverwriting: @Sendable (Data, URL) throws -> Void = { + try $0.write(to: $1, options: .withoutOverwriting) + } + + #if DEBUG + /// Launch a debug build with this argument and every save fails before any bytes land, so + /// the save-failure report can be checked live: the overlay's HUD, or the alert with Hide + /// Tool Feedback on. The clipboard copy still works. + /// `open Annotate.app --args --fail-capture-saves` + nonisolated static let failSavesArgument = "--fail-capture-saves" + + /// What a save throws when `failSavesArgument` is set. The alert's detail names the switch, + /// so the failure is never mistaken for a real one. + struct ForcedSaveFailure: LocalizedError { + var errorDescription: String? { "This debug build was launched with \(FileSink.failSavesArgument)." } + } + #endif + /// A hidden name no capture uses, unique per write. nonisolated static func temporaryFileName() -> String { ".Annotate-\(UUID().uuidString).png.tmp" diff --git a/AnnotateTests/CaptureTests.swift b/AnnotateTests/CaptureTests.swift index 9337999..ca9a456 100644 --- a/AnnotateTests/CaptureTests.swift +++ b/AnnotateTests/CaptureTests.swift @@ -415,6 +415,34 @@ final class CaptureTests: XCTestCase { XCTAssertNotNil(pasteboard.data(forType: .png)) } + #if DEBUG + func testFailSavesSwitchFailsOnlyTheSave() async throws { + let source = StubDisplayCapturing(snapshotImage: CaptureTestImages.solid(width: 100, height: 50, Self.blue)) + let folder = try temporaryFolder() + let pasteboard = privatePasteboard() + + let forced = CaptureService( + source: source, + sinks: AppDelegate.captureSinks( + folder: folder, pasteboard: pasteboard, arguments: ["Annotate", FileSink.failSavesArgument])) + let result = try await forced.capture(request(display: display(), scene: nil)) + + XCTAssertNil(result.savedFile) + XCTAssertTrue(result.copiedToClipboard) + XCTAssertTrue(result.failure(of: .file) is FileSink.ForcedSaveFailure) + let detail = CaptureProblem.saveFailed(error: result.failure(of: .file)).detail + XCTAssertTrue(detail.contains(FileSink.failSavesArgument), detail) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: folder.path), [], "Not even a temporary file") + + // Without the switch, the same sinks save. + let normal = CaptureService( + source: source, sinks: AppDelegate.captureSinks(folder: folder, pasteboard: pasteboard, arguments: ["Annotate"])) + let saved = try await normal.capture(request(display: display(), scene: nil)) + XCTAssertNotNil(saved.savedFile) + XCTAssertTrue(saved.failures.isEmpty) + } + #endif + func testServiceSaysWhichDestinationFailed() async throws { let folder = try temporaryFolder() let service = CaptureService( From b49213369c5d63b6081ab8772c46a98d5060b08e Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Tue, 3 Nov 2026 08:19:43 -0800 Subject: [PATCH 14/17] fix(capture): Keep the crosshair when another display's overlay refreshes A cursor-state change refreshes every overlay's cursor, and each one sets the single system cursor whichever display it is on. In dictionary order, the overlay on another display could go after the picking one and replace the crosshair: with the Text tool its I-beam, and with a cursor style on a visible overlay, the hidden system cursor. An overlay with a cursor override now refreshes last. The new test picks on each of two displays in turn so both refresh orders run; it fails on the old order and skips with one display. The single-display crosshair test also checks the cursor as the picker opens and after a pointer move. --- Annotate/AppDelegate.swift | 7 +++++- AnnotateTests/AnnotateCommandTests.swift | 30 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/Annotate/AppDelegate.swift b/Annotate/AppDelegate.swift index 57d58b5..392c87b 100644 --- a/Annotate/AppDelegate.swift +++ b/Annotate/AppDelegate.swift @@ -1321,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) } diff --git a/AnnotateTests/AnnotateCommandTests.swift b/AnnotateTests/AnnotateCommandTests.swift index b6c9903..2c62e69 100644 --- a/AnnotateTests/AnnotateCommandTests.swift +++ b/AnnotateTests/AnnotateCommandTests.swift @@ -1195,6 +1195,7 @@ final class AnnotateCommandTests: XCTestCase { for style in ActiveCursorStyle.allCases { manager.activeCursorStyle = style run(.capture(.area)) + XCTAssertTrue(NSCursor.current === NSCursor.crosshair, "\(style) as the picker opens") NSCursor.arrow.set() // AppKit asks again on every move across the overlay; each answer must be the crosshair. @@ -1203,6 +1204,10 @@ final class AnnotateCommandTests: XCTestCase { view.updateCursor() XCTAssertTrue(NSCursor.current === NSCursor.crosshair, "\(style) after the canvas refreshes its cursor") XCTAssertFalse(manager.isCursorHidden, "\(style)") + // A move over the overlay leaves the system cursor showing. + manager.cursorPosition = NSPoint(x: screen.frame.midX, y: screen.frame.midY) + manager.updateCursorVisibility() + XCTAssertFalse(manager.isCursorHidden, "\(style) after a move") try pressEscape() try deliverCursorUpdate() @@ -1211,6 +1216,31 @@ final class AnnotateCommandTests: XCTestCase { } } + func testAnotherDisplaysOverlayLeavesThePickersCrosshair() throws { + // Every overlay's refresh sets the one system cursor. With the Text tool, the hidden + // overlay on the other display sets the I-beam, so the picking overlay has to go last. + // Picking on each display in turn covers both orders the overlays can refresh in. + let screens = NSScreen.screens + try XCTSkipUnless(screens.count > 1, "Needs a second display") + try useStubCapture() + run(.tool(.text)) + run(.hide) + + for target in screens.prefix(2) { + appDelegate.pointerLocationOverride = NSPoint(x: target.frame.midX, y: target.frame.midY) + run(.capture(.area)) + let picking = try XCTUnwrap(appDelegate.overlayWindows[target]) + XCTAssertTrue(picking.isRegionPickerOpen, "\(target.localizedName)") + XCTAssertTrue(NSCursor.current === NSCursor.crosshair, "\(target.localizedName) as the picker opens") + + appDelegate.cursorHighlightStateChanged() + XCTAssertTrue(NSCursor.current === NSCursor.crosshair, "\(target.localizedName) after every overlay refreshes") + + picking.cancelRegionPicker() + run(.hide) + } + } + func testCaptureAreaFromAClosedOverlayStillClearsWithClearDrawingsOnStart() throws { try useStubCapture() testDefaults.settings[.clearDrawingsOnStart] = true From 960d9f79cd2e2d269f71630de28aa5f233a3a139 Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Tue, 3 Nov 2026 09:39:26 -0800 Subject: [PATCH 15/17] fix(capture): Keep the cursor style's window in place while picking AppKit sets the arrow when the pointer leaves one of the app's windows, and that includes the click-through window that draws the cursor style. Opening the picker stands the style down, which ordered that window out from under the pointer. Its exit arrived about 40 ms after the picker set the crosshair, AppKit answered it with the arrow, and nothing set the crosshair again: moves inside the overlay cross no cursor rect, and the overlay never got an enter of its own. The crosshair only came back when something rebuilt the overlay's cursor rects, such as the tool feedback HUD's removal timer, which is why the first pick often recovered and later ones didn't. With the other display's overlay open and the style showing there, the window stayed in, which is why that display looked fine. While a picker is open, an effects window that is in stays in, and the style's cursor is cleared on it right away. One that is out stays out, so closing the picker doesn't order it out and replace the tool's cursor. The new test checks the window stays in and the style's cursor is gone for every style, and fails on the old ordering. XCTest can't put the pointer over a window, so it can't produce the exit itself. --- Annotate/CursorHighlightManager.swift | 5 ++ Annotate/CursorHighlightView.swift | 2 + Annotate/CursorHighlightWindow.swift | 14 ++++-- Annotate/OverlayWindow.swift | 4 +- AnnotateTests/AnnotateCommandTests.swift | 61 ++++++++++++++++++++---- 5 files changed, 73 insertions(+), 13 deletions(-) diff --git a/Annotate/CursorHighlightManager.swift b/Annotate/CursorHighlightManager.swift index 820cb04..d6f7e32 100644 --- a/Annotate/CursorHighlightManager.swift +++ b/Annotate/CursorHighlightManager.swift @@ -320,6 +320,11 @@ class CursorHighlightManager: @unchecked Sendable { AppDelegate.shared?.overlayWindows.keys.contains { shouldShowActiveCursorOnScreen($0) } ?? false } + /// Whether Capture Area's picker is open on any display. + var isRegionPickerOpenOnAnyScreen: Bool { + AppDelegate.shared?.overlayWindows.values.contains { $0.isRegionPickerOpen } ?? false + } + // MARK: - Excluded Applications Suppression /// Whether an excluded application currently has frontmost focus. diff --git a/Annotate/CursorHighlightView.swift b/Annotate/CursorHighlightView.swift index 18bfd36..710cc80 100644 --- a/Annotate/CursorHighlightView.swift +++ b/Annotate/CursorHighlightView.swift @@ -89,11 +89,13 @@ class CursorHighlightView: NSView { releaseRingLayer = releaseLayer let cursorOutline = CAShapeLayer() + cursorOutline.name = "activeCursorOutline" cursorOutline.opacity = 0 layer?.addSublayer(cursorOutline) activeCursorOutlineLayer = cursorOutline let cursorLayer = CAShapeLayer() + cursorLayer.name = "activeCursor" cursorLayer.opacity = 0 layer?.addSublayer(cursorLayer) activeCursorLayer = cursorLayer diff --git a/Annotate/CursorHighlightWindow.swift b/Annotate/CursorHighlightWindow.swift index c7bdf9e..beef76d 100644 --- a/Annotate/CursorHighlightWindow.swift +++ b/Annotate/CursorHighlightWindow.swift @@ -130,7 +130,7 @@ class CursorHighlightWindow: NSPanel { // MARK: - Visibility /// Orders the window in or out based on which effects are enabled, applying - /// the current spotlight/dimming state immediately rather than waiting for a frame. + /// the current spotlight/dimming/active cursor state immediately rather than waiting for a frame. func updateVisibility() { let manager = CursorHighlightManager.shared @@ -139,8 +139,16 @@ class CursorHighlightWindow: NSPanel { highlightView.updateSpotlightPosition() highlightView.updateDimming() highlightView.updateHoldRingPosition() - - if manager.isActive || manager.cursorHighlightAvailable || manager.shouldShowActiveCursorOnAnyScreen() { + highlightView.updateActiveCursor() + + let isNeeded = manager.isActive || manager.cursorHighlightAvailable + || manager.shouldShowActiveCursorOnAnyScreen() + // AppKit sets the arrow when the pointer leaves one of the app's windows, this + // click-through one included, and ordering it out from under the pointer counts. While + // Capture Area's picker is open nothing would put the crosshair back, so a window that + // is in stays in until the picker closes. One that is out stays out, or closing the + // picker would order it out again and replace the tool's cursor. + if isNeeded || (isVisible && manager.isRegionPickerOpenOnAnyScreen) { orderFront(nil) startAnimationLoop() } else { diff --git a/Annotate/OverlayWindow.swift b/Annotate/OverlayWindow.swift index 0a085c8..88e5dc7 100644 --- a/Annotate/OverlayWindow.swift +++ b/Annotate/OverlayWindow.swift @@ -748,7 +748,9 @@ class OverlayWindow: NSPanel { toolbarPanel?.detach() // An active cursor style hides the system cursor and draws its own; the picker needs // the crosshair, so the style stands down on this display until the picker closes. - // The canvas answers the window's cursor updates, so it shows the crosshair too. + // The canvas answers the window's cursor updates, so it shows the crosshair too. The + // window that drew the style stays ordered in, since ordering it out from under the + // pointer makes AppKit set the arrow (see `CursorHighlightWindow.updateVisibility`). overlayView.cursorOverride = .crosshair CursorHighlightManager.shared.overlayVisibilityChanged() invalidateCursorRects(for: picker) diff --git a/AnnotateTests/AnnotateCommandTests.swift b/AnnotateTests/AnnotateCommandTests.swift index 2c62e69..29aa966 100644 --- a/AnnotateTests/AnnotateCommandTests.swift +++ b/AnnotateTests/AnnotateCommandTests.swift @@ -1117,8 +1117,9 @@ final class AnnotateCommandTests: XCTestCase { XCTAssertEqual(view.rectangles.count, 1) } - func testActiveCursorStyleStandsDownWhilePicking() async throws { - try useStubCapture() + /// Swaps in a cursor manager on the test's defaults, and makes the cursor effects windows + /// again so they draw from it too: each one's view keeps the manager it was made with. + private func useTestCursorManager() -> CursorHighlightManager { let original = CursorHighlightManager.shared let manager = CursorHighlightManager(userDefaults: testDefaults) CursorHighlightManager.shared = manager @@ -1126,6 +1127,18 @@ final class AnnotateCommandTests: XCTestCase { manager.showSystemCursor() CursorHighlightManager.shared = original } + appDelegate.cursorHighlightWindows.values.forEach { + $0.stopAnimationLoop() + $0.close() + } + appDelegate.cursorHighlightWindows.removeAll() + appDelegate.setupCursorHighlightWindows() + return manager + } + + func testActiveCursorStyleStandsDownWhilePicking() async throws { + try useStubCapture() + let manager = useTestCursorManager() manager.activeCursorStyle = .circle run(.show) let view = try XCTUnwrap(overlay.overlayView) @@ -1182,13 +1195,7 @@ final class AnnotateCommandTests: XCTestCase { func testThePickerShowsTheCrosshairWithEveryCursorStyle() throws { try useStubCapture() - let original = CursorHighlightManager.shared - let manager = CursorHighlightManager(userDefaults: testDefaults) - CursorHighlightManager.shared = manager - addTeardownBlock { @MainActor in - manager.showSystemCursor() - CursorHighlightManager.shared = original - } + let manager = useTestCursorManager() run(.show) let view = try XCTUnwrap(overlay.overlayView) @@ -1216,6 +1223,42 @@ final class AnnotateCommandTests: XCTestCase { } } + func testTheCursorStyleWindowStaysInPlaceWhilePicking() throws { + // AppKit sets the arrow when the pointer leaves one of the app's windows, and that + // includes the click-through window that draws the cursor style. Standing the style + // down for the picker used to order that window out from under the pointer, so the + // arrow replaced the crosshair a moment after the picker opened, and nothing put it + // back. XCTest can't put the pointer over a window, so this checks the window stays. + try useStubCapture() + let manager = useTestCursorManager() + manager.clickEffectsEnabled = false + manager.cursorPosition = NSPoint(x: screen.frame.midX, y: screen.frame.midY) + run(.show) + let effects = try XCTUnwrap(appDelegate.cursorHighlightWindows[screen]) + let layers = try XCTUnwrap(effects.highlightView.layer?.sublayers) + let styleCursor = try XCTUnwrap(layers.first { $0.name == "activeCursor" }) + let styleOutline = try XCTUnwrap(layers.first { $0.name == "activeCursorOutline" }) + + for style in ActiveCursorStyle.allCases { + manager.activeCursorStyle = style + // With no style and no other effect the window is out, and it stays out: ordering + // it in for the pick would order it out again as the picker closes. + let drawsStyle = style != .none + XCTAssertEqual(effects.isVisible, drawsStyle, "\(style) before picking") + XCTAssertEqual(styleCursor.opacity, drawsStyle ? 1 : 0, "\(style) before picking") + + run(.capture(.area)) + XCTAssertTrue(overlay.isRegionPickerOpen, "\(style)") + XCTAssertEqual(effects.isVisible, drawsStyle, "\(style) while picking") + XCTAssertEqual(styleCursor.opacity, 0, "\(style): its cursor is gone while picking") + XCTAssertEqual(styleOutline.opacity, 0, "\(style): its cursor is gone while picking") + + try pressEscape() + XCTAssertEqual(effects.isVisible, drawsStyle, "\(style) after picking") + XCTAssertEqual(styleCursor.opacity, drawsStyle ? 1 : 0, "\(style) is back after picking") + } + } + func testAnotherDisplaysOverlayLeavesThePickersCrosshair() throws { // Every overlay's refresh sets the one system cursor. With the Text tool, the hidden // overlay on the other display sets the I-beam, so the picking overlay has to go last. From 2ffb545b7accd9f3f0066d21496b429eb03f8783 Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Tue, 3 Nov 2026 09:39:31 -0800 Subject: [PATCH 16/17] fix(capture): Set the crosshair on every pointer move while picking The picker set the crosshair only on a press, so anything that set the arrow mid-pick, as AppKit does whenever the pointer leaves one of the app's windows, lasted until the pick ended. The live check saw the arrow last through 35 moves. The overlay now forwards moves to the picker while it is open, taking them the way the quick picker does, and the picker sets the crosshair on every pointer event it handles. The new test sets the arrow before each move and press, and fails on the old routing for every style. --- Annotate/OverlayWindow.swift | 10 +++++++ Annotate/RegionPicker.swift | 5 +++- AnnotateTests/AnnotateCommandTests.swift | 38 ++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) diff --git a/Annotate/OverlayWindow.swift b/Annotate/OverlayWindow.swift index 88e5dc7..9e49586 100644 --- a/Annotate/OverlayWindow.swift +++ b/Annotate/OverlayWindow.swift @@ -512,6 +512,12 @@ class OverlayWindow: NSPanel { /// restores coalescing and must not commit geometry. The toolbar is a separate panel, /// so its clicks never reach this window at all. private func routeOverlayMouseEvent(_ event: NSEvent) -> Bool { + // The picker sets its crosshair again on every pointer event, moves included. + if event.type == .mouseMoved, let regionPicker { + regionPicker.handleMouseEvent(event) + return true + } + switch event.type { case .leftMouseDown, .leftMouseDragged, .leftMouseUp, .rightMouseDown, .rightMouseUp, .otherMouseDown, .otherMouseUp: @@ -729,6 +735,9 @@ class OverlayWindow: NSPanel { func beginRegionPicker(onDismiss: (() -> Void)? = nil, onPick: @escaping (CGRect) -> Void) -> Bool { guard regionPicker == nil, !overlayView.isReadOnlyMode else { return false } cancelQuickPicker() + // After the quick picker has put its own setting back. + acceptedMouseMovedBeforePicker = acceptsMouseMovedEvents + acceptsMouseMovedEvents = true if let activeField = overlayView.activeTextField { overlayView.finalizeTextAnnotation(activeField) } @@ -763,6 +772,7 @@ class OverlayWindow: NSPanel { guard let picker = regionPicker else { return } regionPicker = nil picker.removeFromSuperview() + acceptsMouseMovedEvents = acceptedMouseMovedBeforePicker overlayView.resumeFade() updateToolbarVisibility() overlayView.cursorOverride = nil diff --git a/Annotate/RegionPicker.swift b/Annotate/RegionPicker.swift index 4c9e709..b295506 100644 --- a/Annotate/RegionPicker.swift +++ b/Annotate/RegionPicker.swift @@ -95,6 +95,10 @@ final class RegionPicker: NSView { /// Handles a mouse event the overlay window forwards. Every mouse event belongs to the /// picker while it is open, so nothing reaches the canvas. func handleMouseEvent(_ event: NSEvent) { + // AppKit sets the arrow whenever the pointer leaves one of the app's windows, and a move + // inside this one crosses no cursor rect that would set the crosshair again. Setting it + // on every pointer event keeps it for the whole pick. + NSCursor.crosshair.set() let point = convert(event.locationInWindow, from: nil) switch event.type { case .leftMouseDown: mouseDown(at: point) @@ -106,7 +110,6 @@ final class RegionPicker: NSView { } func mouseDown(at point: NSPoint) { - NSCursor.crosshair.set() dragStart = point dragEnd = point updateLayers() diff --git a/AnnotateTests/AnnotateCommandTests.swift b/AnnotateTests/AnnotateCommandTests.swift index 29aa966..2138b1f 100644 --- a/AnnotateTests/AnnotateCommandTests.swift +++ b/AnnotateTests/AnnotateCommandTests.swift @@ -1259,6 +1259,44 @@ final class AnnotateCommandTests: XCTestCase { } } + func testEveryPointerMoveWhilePickingSetsTheCrosshair() throws { + // Something can still set the arrow mid-pick, as AppKit does whenever the pointer leaves + // one of the app's windows, and a move inside the overlay crosses no cursor rect that + // would set the crosshair again. The live check saw the arrow last through 35 moves. + try useStubCapture() + let manager = useTestCursorManager() + run(.show) + let acceptedMovesBefore = overlay.acceptsMouseMovedEvents + + for style in ActiveCursorStyle.allCases { + manager.activeCursorStyle = style + run(.capture(.area)) + XCTAssertTrue(overlay.acceptsMouseMovedEvents, "\(style): the picker needs every move") + + for step in 0..<3 { + NSCursor.arrow.set() + let point = NSPoint(x: 300 + CGFloat(step) * 10, y: 300) + overlay.sendEvent( + try XCTUnwrap( + TestEvents.createMouseEvent(type: .mouseMoved, location: point, windowNumber: overlay.windowNumber))) + XCTAssertTrue(NSCursor.current === NSCursor.crosshair, "\(style), move \(step)") + } + NSCursor.arrow.set() + for type in [NSEvent.EventType.leftMouseDown, .leftMouseDragged] { + overlay.sendEvent( + try XCTUnwrap( + TestEvents.createMouseEvent( + type: type, location: NSPoint(x: 320, y: 310), windowNumber: overlay.windowNumber))) + XCTAssertTrue(NSCursor.current === NSCursor.crosshair, "\(style), \(type)") + NSCursor.arrow.set() + } + + try pressEscape() + XCTAssertFalse(overlay.isRegionPickerOpen, "\(style)") + XCTAssertEqual(overlay.acceptsMouseMovedEvents, acceptedMovesBefore, "\(style)") + } + } + func testAnotherDisplaysOverlayLeavesThePickersCrosshair() throws { // Every overlay's refresh sets the one system cursor. With the Text tool, the hidden // overlay on the other display sets the I-beam, so the picking overlay has to go last. From 208f722756982b5c64b4b358e678e92ebd98adc2 Mon Sep 17 00:00:00 2001 From: Emmanuel Pilande Date: Tue, 3 Nov 2026 20:04:29 -0800 Subject: [PATCH 17/17] docs: Remove the screenshot capture design spec Design docs don't live in this repo. It was the only file in docs/, and nothing else in the tree refers to it. --- docs/screenshot-capture-spec.md | 93 --------------------------------- 1 file changed, 93 deletions(-) delete mode 100644 docs/screenshot-capture-spec.md diff --git a/docs/screenshot-capture-spec.md b/docs/screenshot-capture-spec.md deleted file mode 100644 index 02f7a1f..0000000 --- a/docs/screenshot-capture-spec.md +++ /dev/null @@ -1,93 +0,0 @@ -# Screenshot capture (#80): design spec - -Status: approved 2026-11-01, with the open questions settled under Decisions. Written against `main` at `8b0d70b` (v1.8.0 plus #135 to #140). - -## Verdict and scope - -Capture fits Annotate. It closes the "annotate, capture, share" loop the issue describes, and three quarters of the plumbing exists: `ScreenSampler` already takes ScreenCaptureKit screenshots of one display with Annotate's windows excluded, the command layer runs the same code from menus, Shortcuts, and `annotate://`, and every annotation already carries a monotonic creation time. - -**v1 ships:** Capture Screen and Capture Area for one display, PNG to a folder, a copy on the clipboard, an on-overlay confirmation plus a system notification with Show in Finder, a Capture pane in Settings (folder, after-capture destination, notification, Screen Recording status for Capture and Redact), both commands in Shortcuts (not `annotate://`, see Decisions), and an opt-in JSON sidecar. - -**Waits:** window crop, stitching several displays, global hotkeys for capture, sidecar on by default, session recording and bundles, and opening an image to annotate. - -## Answers 1 to 9 - -**1. Fit and smallest good v1.** As above. The one piece of scope that looks optional but is not: freezing fade while the area picker is up. Fade Mode is the default with a 0.625 s hold, so without a freeze, Capture Area in the default mode saves an empty region. Naming: "Capture Screen" and "Capture Area" rather than the issue's "Save Full Screen Screenshot", so the menu, shortcut, intent, and link share one short vocabulary. - -**2. Capturing screen plus annotations.** Take the ScreenCaptureKit screenshot of the display with Annotate excluded (what `ScreenSampler.capture` does today), then composite in process: board fill at its opacity if the board is on, then the annotations rendered from `OverlayDocument` into a `CGContext` at the snapshot's pixel scale. Not "capture our own window too": the HUD pill, quick picker, selection chrome, and the text field are all subviews of `overlayView`, so any capture that includes the window leaks chrome, and fade alpha becomes whatever the compositor had that frame. The composite path needs a new `AnnotationRenderer` extracted from `OverlayView`'s private draw primitives, which `OverlayView.draw` then calls. That extraction is the main engineering cost and the main seam for everything later. - -- Permission: reuse the cached `CGPreflightScreenCaptureAccess` state. Never prompt from the overlay, since the prompt lands under it. When access is missing, the capture command shows a HUD ("Screen Recording is off. Opening Settings…"), closes the interactive overlay, and opens Settings to the Capture pane, which asks the way the Redact row does today. That row moves out of the Tools pane (`ToolsSettingsView`) into the Capture pane, so Screen Recording status lives in one place, and the Redact section points there. Annotations persist across the close. One useful fallback: when the board is on at opacity 1.0 the screen pixels are fully covered, so capture skips ScreenCaptureKit and works without permission. Update `NSScreenCaptureUsageDescription`, which mentions only Pixelate and Blur. -- Retina: composite at the snapshot's native pixel size (`pointPixelScale`), scale the context by `snapshot.scale`, and write PNG DPI metadata of 72 times scale, matching `screencapture`. -- Which display: the screen of the key interactive overlay, else the display under the pointer (`getCurrentScreen()`), else `NSScreen.main`. Annotations are drawn only when that display's overlay is visible, interactive or Always-On. A link capture with the overlay hidden saves the plain screen, which is what is on screen. One display per capture. In Fade Mode a full-screen capture draws each annotation at its current fade, as shown on screen. -- Streaming later: `SCStream` uses the same `SCContentFilter` and configuration as `SCScreenshotManager`, so put the filter builder behind a `DisplayCapturing` protocol with `captureDisplay` now and room for a frame stream later. The renderer draws a document value into any `CGContext`, so a frame pipeline can reuse it unchanged. - -**3. Selected area.** #111 is a detector for the system's screenshot UI, not a picker, and the Select tool's marquee is tool state threaded through `OverlayWindow.mouseDown` and `mouseUp`. Reusing either would entangle capture with the Select tool. Build a small AppKit-only `RegionPicker` view that the overlay window installs over `overlayView` while picking, like the quick picker: crosshair, dimmed outside, size label, release to capture, Escape to cancel, no dependency on `OverlayView` or `OverlayDocument`. When Capture Area runs from a link, an intent, or the menu with no interactive overlay open, including in Always-On where overlays ignore the mouse, it opens the interactive overlay the way `showInteractiveOverlay` does and then shows the picker. The picker reports a rect in display-local points, which the capture crops using the existing `ScreenSampler.pixelRect` math. Window crop waits, but `CaptureRegion` is an enum (`.display`, `.rect`) so `.window(CGWindowID)` is a new case, not a redesign. - -**4. Output.** Always write the file. Settings offers "After capture: Save to folder, Copy to clipboard, Both", default Both: the file is saved and the image is also copied to the clipboard. File name `Annotate 2026-11-01 at 10.23.45.png`, mirroring macOS, with " (2)" on collision. Default folder `~/Pictures/Annotate` through `com.apple.security.assets.pictures.read-write`; Pictures has no first-access TCC prompt, while Desktop, Documents, and Downloads do, and that prompt would land under the overlay. Custom folder: switch the current `files.user-selected.read-only` entitlement to `read-write`, pick with `NSOpenPanel`, store a security-scoped bookmark as a `SettingKey`, resolve per save inside `startAccessingSecurityScopedResource`, and fall back to the default with a HUD when the bookmark is stale. Notification: the HUD pill always shows the file name on the overlay; a `UNUserNotificationCenter` notification with a thumbnail and a Show in Finder action is sent when authorized. Authorization is requested from the Capture pane only, same rule as Screen Recording. Notifications go behind a small protocol with a test stub, like `RedactionSampling`. Sidecar: ship the JSON format and writer in v1, off by default behind "Save annotation data next to screenshots". The format is the contract the later work needs, and writing it for every capture would clutter the folder for users who never use it. - -**5. Seams.** Four types, none touching `AppDelegate`, `BoardManager.shared`, or `OverlayView`: - -- `DisplayCapturing`: where pixels come from. `ScreenSampler` conforms; tests stub it. -- `Capture`: what a capture is. The composited `CGImage`, `DisplayInfo` (id, frame, scale), the region in display-local points, board state, the annotation records, `capturedAt` wall clock, and `hostTime`. -- `AnnotationRenderer`: draws a document value plus board state into a `CGContext` with options (fade policy, live previews off). Selection chrome stays in `OverlayView`, which paints it over the renderer's output, so the renderer never draws chrome. -- `CaptureSink`: where it goes. `FileSink` and `ClipboardSink` in v1, a bundle sink later. `CaptureService.capture(request) async throws` wires them; `AnnotateCommand.capture` starts it and returns `.ran`, and the intents await it to return an `IntentFile`. - -Timestamps and ids: `creationTime` is `CACurrentMediaTime`, mach host time, and ScreenCaptureKit stamps frames with host-time `displayTime`, so one clock covers both. The sidecar names the clock and records `hostTime` at capture plus ISO 8601 wall time, so a reader can align or convert. Add `id = UUID()` to the other annotation structs following `TextAnnotation` (not part of `==`, fresh on paste) in the sidecar PR. Numbered pins are the Counter tool; export them as `pin` with number, position, and time. Export through a DTO with sRGB hex colors and display-local top-left points, never `Codable` on the live structs, which hold `NSColor` and cached paths. - -**6. Edge cases.** - -- Fading strokes: full-screen capture renders what is on screen (current alpha, fully faded excluded). The area picker freezes `fadeClock` while open and captures at the frozen time. Fade resumes on dismiss. -- Active text edit: commit it first, as `hideOverlays` does. The capture shortcut works while a label is being typed when its binding has Command, which no typed character carries: it commits the label and captures, the same as the menu item. Every other overlay shortcut, and a capture binding without Command, still types into the label. -- Redactions: in a file the pixels under a redaction are permanent and the fresh snapshot holds the raw screen, so the renderer always lays the opaque placeholder and then the sample, never at fade alpha. Pixelate and Blur samples come from the capture's own snapshot through `ScreenSampler.makeSample`, not the stored `Rectangle.sample`, which can be stale against the fresh pixels. The `RedactionTests` leak assertions run against renderer output. -- Success HUD: respects `hideToolFeedback` like every other pill; the system notification is the channel for users who hide pills. -- Picker keys: the picker consumes Escape before `OverlayWindow.keyDown`, which otherwise closes the overlay. -- Toolbar, HUD, picker, cursor effects: never in the image, because Annotate's windows are excluded and the renderer draws only the document. `showsCursor` stays false. -- Always-On: Capture Screen works from the menu, a link, or an intent; the overlay is read-only but visible, so annotations render. Capture Area opens the interactive overlay first, as in answer 3. -- Board: fill at its opacity over the screen pixels, no 1 pt border. Redactions render solid, matching the screen. -- Full-screen Spaces: display capture sees the full-screen app; the overlay's `.canJoinAllSpaces` means annotations are there too. -- macOS 15 and later show a periodic ScreenCaptureKit reminder alert; it will sit under an open overlay until it closes. Already true for Redact; capture widens exposure. - -**7. Shortcuts and links.** Shortcuts yes, links no (see Decisions). `AnnotateCommand.capture(CaptureScope)` with `screen` and `area` has the paths `/capture/screen` and `/capture/area`, which the link parser rejects, plus Capture Screen and Capture Area intents returning the PNG as an `IntentFile`. Overlay shortcuts `captureScreen` (⌘S) and `captureArea` (⇧⌘S), rebindable, through `newlyEditable`; `s` is free of reserved keys and fixed key equivalents. Status menu items for both. "Open an image to annotate" needs a parameter the link parser rejects by design; when it comes, it is an intent with a file parameter. - -**8. Stacked PRs.** - -1. Renderer extraction. `AnnotationRenderer` from `OverlayView`'s draw code, `OverlayView.draw` delegates, zero behavior change. Tests: existing offscreen pixel tests pass unchanged; new renderer tests for chrome-off, fade policy, and redaction opacity. Cost: moving baselined SwiftLint violations surfaces them. Conflicts with any parallel `OverlayView` work. -2. Capture Screen. `DisplayCapturing`, `Capture`, `CaptureService`, `FileSink`, `ClipboardSink` (the default saves and copies), PNG encode off main, HUD, Capture pane with default folder and the Screen Recording row moved from Tools, `ShortcutKey.captureScreen`, menu item, `AnnotateCommand.capture(.screen)`. Tests: composite pixels against a stub snapshot (board on and off, scale 1 and 2), file naming and collisions, clipboard contents, display selection rule, command outcome. Mac: Retina plus external display, board, fade, Always-On, denied permission flow. -3. Capture Area. `RegionPicker`, fade freeze, crop, `captureArea`, opening the interactive overlay when none is open. Tests: picker geometry and keys, rect normalization, crop math, frozen clock, opening from a hidden or Always-On overlay. Mac: drag on each display, Escape, tiny rects, picker on a display whose overlay is not key, Always-On. -4. Folder, destinations, notification. Entitlement change, bookmark key and stale handling, the after-capture destination setting, notification protocol and stub. Tests: bookmark round trip in a temp directory, stale fallback, destination setting. Mac: a notarized build, pick a folder on an external volume, revoke it, click the notification. -5. Intents, README, AGENTS. Tests in `AnnotateCommandTests`, intent display representations. Links stay blocked (PR 3). -6. Sidecar and ids. `CaptureRecord` v1, ids on annotations, the toggle, a schema doc under `docs/`. Tests: golden JSON, coordinate transform, clock fields. - -**9. Risks.** The renderer extraction is the regression risk; pixel tests and a no-behavior-change rule contain it. Permission UX: the prompt and the macOS 15 reminder both hide under the overlay, so every prompt comes from Settings. Entitlement changes touch notarization; PR 4 needs a signed build check. 5K composites peak around 200 MB; encode off main. CI has no Screen Recording, so nothing in tests may call ScreenCaptureKit, which the protocol enforces. - -## Later work - -Keep `AnnotationRenderer`, `DisplayCapturing`, `Capture`, `CaptureRecord`, and `RegionPicker` free of app singletons and view types, so any of them can move without a rewrite. The JSON schema is versioned in `docs/`. - -For the session feature, v1 does differently because of it: a renderer that draws into any context, a region enum with room for windows, a `Capture` value with host time and display info, a sink protocol so a bundle is a new sink, and ids on every annotation. What v1 avoids: window-id coupling (overlays are recreated on display changes), rendering bound to `NSView`, and a JSON shape derived from the live structs. - -## Approve - -1. Composite path (ScreenCaptureKit minus Annotate, plus in-process render), not window capture. -2. One display per capture; annotations only when that overlay is visible. -3. Fade freeze during the area picker; full-screen capture is what you see, at each annotation's current fade. -4. Default folder `~/Pictures/Annotate` with the Pictures entitlement; custom folder by bookmark. -5. Save and copy to the clipboard by default; HUD plus system notification, authorization from Settings only. -6. Sidecar shipped off by default; ids on every annotation. -7. Names Capture Screen and Capture Area, ⌘S and ⇧⌘S. No `annotate://` links for capture (see Decisions). -8. A sixth Settings pane, Capture, which also takes the Screen Recording row from Tools. - -## Decisions - -Settled 2026-11-01 from the open questions. - -- After a capture: save the file and also copy it to the clipboard. "Both" is the default destination. -- Capture Area with no interactive overlay open, including Always-On: open the interactive overlay and show the picker. -- Full-screen capture in Fade Mode: annotations at their current fade, as shown on screen. -- The Redact Screen Recording permission row moves from the Tools pane into the Capture pane. -- Capture settings get their own Settings pane, Capture. - -Settled 2026-11-02 in the review of #142. - -- `annotate://` links never run a capture, Capture Screen or Capture Area. Any web page or app can open a link, and a capture reads the screen and writes the clipboard. The link parser rejects `/capture/...` with its own reason. Shortcuts, the menu, and the keyboard still capture. This replaces the link parts of answers 2, 3, 6, 7, and 8. -- When only the save or only the clipboard copy fails, Annotate says which. Failures show an alert when no overlay HUD can show them, including with Hide Tool Feedback on.