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/AnnotateCommand.swift b/Annotate/AnnotateCommand.swift index ec85a07..2624fbd 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 @@ -16,7 +16,8 @@ enum AnnotateCommand: Hashable, Sendable { case toolbar(CommandSwitch) case fade(CommandSwitch) case board(CommandSwitch) - /// Saves an image of the display with its annotations and copies it to the clipboard. + /// Saves an image of the display, or of an area the user drags out, with its annotations + /// and copies it to the clipboard. Never runs from a link. case capture(CaptureScope) /// Whether running a command changed anything. @@ -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`, @@ -142,7 +151,8 @@ enum AnnotateCommand: Hashable, Sendable { icon: board.currentBoardType == .blackboard ? "⬛" : "⬜") return enabled == current ? .noOp : .ran case .capture(let scope): - // The capture finishes later and reports itself on the overlay. + // The capture finishes later and reports itself on the overlay. Capture Area + // first waits for the user to drag out the area. appDelegate.capture(scope) return .ran } diff --git a/Annotate/AppDelegate+Capture.swift b/Annotate/AppDelegate+Capture.swift index 0b8a378..48492ae 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. @@ -12,15 +13,42 @@ 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 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 +60,86 @@ extension AppDelegate { return } let overlay = overlayWindows[screen] - let request = CaptureRequest( - display: display, - scene: overlay.flatMap { $0.isVisible ? captureScene(of: $0) : nil }, - hostTime: CACurrentMediaTime(), - date: Date()) + startCapture( + CaptureRequest( + display: display, + scene: overlay.flatMap { $0.isVisible ? captureScene(of: $0) : nil }, + hostTime: CACurrentMediaTime(), + date: Date()), + on: overlay) + } + + /// Lets the user drag out part of a display, then saves it with its board and annotations + /// and copies it, as Capture Screen does. The picker needs the interactive overlay, so with + /// none open, including in Always-On, this opens it first. The fade holds while picking, + /// and the capture shows each annotation at the fade the picker showed. + @objc func captureArea() { + // Without Screen Recording the drag would come to nothing, so ask before anything opens. + // From Always-On, the Screen Recording flow brings Always-On back afterwards, drawings + // and all. + let board = BoardManager.shared + if !captureService.source.canCapture, + !CaptureScene.boardCoversScreen(board.appearance, opacity: CGFloat(board.opacity)) + { + showScreenRecordingOff(on: areaTargetScreen.flatMap { overlayWindows[$0] }) + return + } + var heldAlwaysOnFade: OverlayWindow? + if !isInteractiveOverlayOpen { + // Always-On annotations are on screen, so the overlay opening over them keeps them, + // even with Clear Drawings on Start, and keeps Always-On's Persist fade until the + // picker closes, or leaving Always-On would expire the older ones at once. + if alwaysOnMode, let screen = getCurrentScreen(), let overlay = overlayWindows[screen] { + overlaysKeepingDrawings.insert(ObjectIdentifier(overlay)) + overlaysHoldingAlwaysOnFade.insert(ObjectIdentifier(overlay)) + heldAlwaysOnFade = overlay + } + showInteractiveOverlay() + } + let opened = beginAreaPicker(releasingHeldFadeOf: heldAlwaysOnFade) + if !opened, let heldAlwaysOnFade { + releaseHeldAlwaysOnFade(of: heldAlwaysOnFade) + } + } + + /// Opens the picker on the target display, and returns whether it opened. When it does, + /// closing it in any way releases `held`'s Always-On fade. + private func beginAreaPicker(releasingHeldFadeOf held: OverlayWindow?) -> Bool { + guard let screen = areaTargetScreen, let overlay = overlayWindows[screen], + let display = DisplayInfo(screen: screen) + else { + log.error("No overlay to pick an area on") + return false + } + guard !overlay.isRegionPickerOpen else { return false } + // The picker reads Escape from its own overlay, and another display's may be key. + overlay.makeKeyAndOrderFront(nil) + let onDismiss: () -> Void = { [weak self] in + guard let self, let held else { return } + self.releaseHeldAlwaysOnFade(of: held) + } + return overlay.beginRegionPicker(onDismiss: onDismiss) { [weak self, weak overlay] rect in + guard let self, let overlay else { return } + // Runs before the picker closes, so the scene's fade clock is still frozen. + self.startCapture( + CaptureRequest( + display: display, + region: .rect(fromViewRect: rect, displayHeight: display.frame.height), + scene: self.captureScene(of: overlay), + hostTime: CACurrentMediaTime(), + date: Date()), + on: overlay) + } + } + /// Gives an overlay Capture Area opened from Always-On its Fade Mode setting back. Back in + /// Always-On, as when its shortcut ended the pick, Persist stays as Always-On wants. + func releaseHeldAlwaysOnFade(of overlay: OverlayWindow) { + guard overlaysHoldingAlwaysOnFade.remove(ObjectIdentifier(overlay)) != nil, !alwaysOnMode else { return } + overlay.overlayView.fadeMode = settings[.fadeMode] + } + + private func startCapture(_ request: CaptureRequest, on overlay: OverlayWindow?) { // Each capture waits for the one before it, so captures finish in the order they were // asked for: an older image never replaces a newer one on the clipboard or in the HUD, // and every capture still gets its own file. The scene above is already taken, so the @@ -53,7 +155,7 @@ extension AppDelegate { self?.showScreenRecordingOff(on: overlay) } catch { log.error("Capture failed: \(error.localizedDescription)") - self?.reportCaptureProblem("Capture Failed", icon: "⚠️", on: overlay) + self?.reportCaptureProblem(.failed, on: overlay) } } } @@ -74,22 +176,29 @@ extension AppDelegate { now: view.fadeClock()) } + /// Success shows on the overlay, if it is open. When one destination failed, says which, + /// even with the overlay closed. private func reportCapture(_ result: CaptureResult, on overlay: OverlayWindow?) { if let file = result.savedFile { + if let copyError = result.failure(of: .clipboard) { + reportCaptureProblem(.copyFailed(savedAs: file, error: copyError), on: overlay) + return + } guard let overlay, overlay.isVisible else { return } overlay.showToggleFeedback("Saved \(file.lastPathComponent)", icon: "📸") } else if result.copiedToClipboard { - reportCaptureProblem("Couldn't Save. Copied to Clipboard", icon: "📋", on: overlay) + reportCaptureProblem(.saveFailed(error: result.failure(of: .file)), on: overlay) } } - /// On the overlay when it is open. Otherwise, as from the status menu with the overlay - /// closed, an alert, so a failed capture is never silent. - private func reportCaptureProblem(_ message: String, icon: String, on overlay: OverlayWindow?) { - if let overlay, overlay.isVisible { - overlay.showToggleFeedback(message, icon: icon) + /// On the overlay's HUD when it is open and showing feedback. Otherwise an alert: from the + /// status menu with the overlay closed, or with Hide Tool Feedback on, a failed capture is + /// never silent. + private func reportCaptureProblem(_ problem: CaptureProblem, on overlay: OverlayWindow?) { + if let overlay, overlay.isVisible, !settings[.hideToolFeedback] { + overlay.showToggleFeedback(problem.title, icon: problem.icon) } else { - showCaptureProblemAlert(message) + showCaptureProblemAlert(problem.title, problem.detail) } } @@ -170,6 +279,33 @@ extension AppDelegate { } } +/// A capture that went wrong, in whole or in part: a short title for the HUD and the alert, +/// and the alert's detail. +struct CaptureProblem: Equatable { + let title: String + let icon: String + let detail: String + + static let failed = CaptureProblem( + title: "Capture Failed", icon: "⚠️", detail: "Annotate couldn't finish the capture. Try again in a moment.") + + static func copyFailed(savedAs file: URL, error: Error) -> CaptureProblem { + CaptureProblem( + title: "Couldn't Copy. Saved \(file.lastPathComponent)", + icon: "⚠️", + detail: "The image was saved, but Annotate couldn't copy it to the clipboard. \(error.localizedDescription)") + } + + static func saveFailed(error: Error?) -> CaptureProblem { + CaptureProblem( + title: "Couldn't Save. Copied to Clipboard", + icon: "📋", + detail: ["The image is on the clipboard, but Annotate couldn't save it.", error?.localizedDescription] + .compactMap { $0 } + .joined(separator: " ")) + } +} + /// The macOS privacy prompt, which asks for Screen Recording among other permissions. Another /// process shows it, `universalAccessAuthWarn`, and its windows can be found by owner without /// any permission. diff --git a/Annotate/AppDelegate.swift b/Annotate/AppDelegate.swift index eace345..392c87b 100644 --- a/Annotate/AppDelegate.swift +++ b/Annotate/AppDelegate.swift @@ -32,22 +32,26 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem /// Created as launch starts, before launch or any link can activate the app. var linkFocusHandoff: LinkFocusHandoff? - /// Makes Capture Screen's images. Tests swap in one with a stub source, a temporary - /// folder, and a private pasteboard. - lazy var captureService = CaptureService( - source: ScreenSampler.shared, - sinks: [FileSink(folder: FileSink.defaultFolder), ClipboardSink()]) + /// Makes Capture Screen's and Capture Area's images. Tests swap in one with a stub source, + /// a temporary folder, and a private pasteboard. + lazy var captureService = CaptureService(source: ScreenSampler.shared, sinks: Self.captureSinks()) /// The latest capture. The next one waits for it, and tests await it. var captureTask: Task? /// 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. @@ -63,6 +67,10 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem /// Overlays closed by the app rather than the user, which keep their drawings the next /// time they open even with Clear Drawings on Start. var overlaysKeepingDrawings: Set = [] + /// 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. @@ -397,6 +405,11 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem title: "Capture Screen", action: #selector(captureScreen), keyEquivalent: "")) + menu.addItem( + NSMenuItem( + title: "Capture Area", + action: #selector(captureArea), + keyEquivalent: "")) menu.addItem(NSMenuItem.separator()) @@ -890,7 +903,8 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem overlayWindow.overlayView.isReadOnlyMode = false overlayWindow.updateToolbarVisibility() - overlayWindow.overlayView.fadeMode = settings[.fadeMode] + overlayWindow.overlayView.fadeMode = + overlaysHoldingAlwaysOnFade.contains(ObjectIdentifier(overlayWindow)) ? false : settings[.fadeMode] overlayWindow.overlayView.fadeDelay = settings[.fadeDelay] overlayWindow.overlayView.startFadeLoopIfNeeded() } @@ -1015,6 +1029,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem case #selector(toggleToolbar): action = .toggleToolbar case #selector(clearAllAnnotations): action = .clearAll case #selector(captureScreen): action = .captureScreen + case #selector(captureArea): action = .captureArea default: continue } @@ -1306,7 +1321,12 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuItem @objc func cursorHighlightStateChanged() { updateAllCursorHighlightWindows() CursorHighlightManager.shared.updateCursorVisibility() - overlayWindows.values.forEach { window in + // Every overlay sets the one system cursor, whichever display it is on, so the last + // one wins. An overlay with a cursor override, as Capture Area's picker sets, goes + // last: otherwise another display's I-beam or hidden cursor would replace the crosshair. + let windows = Array(overlayWindows.values) + let overriding = windows.filter { $0.overlayView.cursorOverride != nil } + for window in windows.filter({ $0.overlayView.cursorOverride == nil }) + overriding { window.overlayView.updateCursor() window.overlayView.window?.invalidateCursorRects(for: window.overlayView) } diff --git a/Annotate/Capture.swift b/Annotate/Capture.swift index 37400ba..3032ffb 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 @@ -108,12 +121,27 @@ enum CaptureDelivery: Equatable, Sendable { case 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. @@ -122,6 +150,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; @@ -129,13 +159,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, @@ -166,12 +201,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) @@ -181,16 +218,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) } } @@ -240,6 +277,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 b26ff57..25dd168 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,7 +37,14 @@ struct CaptureSettingsView: View { Button("Show in Finder", action: showFolder) } } - 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.") + 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, 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) @@ -43,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" ) } @@ -69,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) { @@ -87,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) @@ -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/Annotate/CaptureSinks.swift b/Annotate/CaptureSinks.swift index 745f766..6af0bc0 100644 --- a/Annotate/CaptureSinks.swift +++ b/Annotate/CaptureSinks.swift @@ -4,11 +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) @@ -16,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) } @@ -25,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. @@ -43,16 +48,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 = writeWithoutOverwriting + ) 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 +76,29 @@ 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" + } + nonisolated private static let maxAttempts = 1000 } @@ -67,6 +106,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/Annotate/CursorHighlightManager.swift b/Annotate/CursorHighlightManager.swift index 88dced6..d6f7e32 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) } @@ -318,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. @@ -442,7 +449,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/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/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..e04e723 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 @@ -375,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 { @@ -394,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() @@ -411,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) @@ -470,6 +497,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..9e49586 100644 --- a/Annotate/OverlayWindow.swift +++ b/Annotate/OverlayWindow.swift @@ -38,6 +38,9 @@ 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? + private var regionPickerDismissHandler: (() -> Void)? // Latched at mouseDown: currentTool can change mid-drag via tool shortcuts private var activeFreehandTool: ToolType? private var activeShapeTool: ToolType? @@ -361,6 +364,7 @@ class OverlayWindow: NSPanel { override func orderOut(_ sender: Any?) { cancelQuickPicker() + cancelRegionPicker() restoreMouseCoalescing() overlayView.discardRedactionSamples() super.orderOut(sender) @@ -382,15 +386,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 +434,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 +471,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) @@ -498,12 +512,18 @@ 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: break case .scrollWheel: - return quickPicker != nil + return quickPicker != nil || regionPicker != nil default: return false } @@ -514,6 +534,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 +636,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 +723,65 @@ 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. `onDismiss` + /// runs once the picker has closed, whether it picked or not. + @discardableResult + 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) + } + 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 + 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. + // 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) + return true + } + + /// 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() + acceptsMouseMovedEvents = acceptedMouseMovedBeforePicker + overlayView.resumeFade() + updateToolbarVisibility() + overlayView.cursorOverride = nil + CursorHighlightManager.shared.overlayVisibilityChanged() + let onDismiss = regionPickerDismissHandler + regionPickerDismissHandler = nil + onDismiss?() + } + override func mouseMoved(with event: NSEvent) { guard quickPicker != nil else { super.mouseMoved(with: event) @@ -894,16 +979,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 { @@ -1531,6 +1619,8 @@ class OverlayWindow: NSPanel { } func prepareForAlwaysOnMode() { + // Always-On is click-through, so a picker left open could never finish. + cancelRegionPicker() cancelQuickPicker() restoreMouseCoalescing() cancelFreehandStroke() @@ -1665,6 +1755,10 @@ class OverlayWindow: NSPanel { super.keyDown(with: event) return } + if let regionPicker { + regionPicker.handleKey(chord) + return + } if handleQuickPickerKeyDown(chord) { return } @@ -2315,6 +2409,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..b295506 --- /dev/null +++ b/Annotate/RegionPicker.swift @@ -0,0 +1,199 @@ +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 + + /// 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)? + + 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.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 + 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) { + // 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) + case .leftMouseDragged: mouseDragged(to: point) + case .leftMouseUp: mouseUp(at: point) + case .rightMouseDown, .otherMouseDown: cancel() + default: break + } + } + + func mouseDown(at point: NSPoint) { + 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 + + /// 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 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/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/AnnotateCommandTests.swift b/AnnotateTests/AnnotateCommandTests.swift index b6c512e..2138b1f 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() @@ -454,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() { @@ -496,7 +499,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), @@ -632,6 +639,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 @@ -806,6 +814,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 +858,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() { @@ -853,6 +912,496 @@ 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") + } + + /// 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) + } + + /// 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 + addTeardownBlock { @MainActor in + 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) + 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. 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. + run(.capture(.area)) + 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 manager = useTestCursorManager() + run(.show) + let view = try XCTUnwrap(overlay.overlayView) + + 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. + 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)") + // 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() + XCTAssertFalse(NSCursor.current === NSCursor.crosshair, "\(style): the tool's cursor is back") + XCTAssertEqual(manager.isCursorHidden, style != .none, "\(style)") + } + } + + 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 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. + // 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 + 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 1621cb4..ca9a456 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 @@ -140,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 { @@ -397,10 +409,166 @@ 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)) } + #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( + 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: - 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 { @@ -429,6 +597,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() { @@ -462,6 +674,35 @@ final class CaptureTests: XCTestCase { XCTAssertTrue(ShortcutKey.newlyEditable.contains(.captureScreen)) 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 { + // 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`. 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) + } +} 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/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 diff --git a/AnnotateTests/URLCommandTests.swift b/AnnotateTests/URLCommandTests.swift index 6ead3b4..8d0d6e1 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,9 @@ final class URLCommandTests: XCTestCase { ("annotate://nope", .unknownCommand), ("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 { guard case .failure(let rejection) = AnnotateCommand.parse(url: try link(string), scheme: "annotate") else { @@ -190,6 +193,22 @@ 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") + let overlay = try XCTUnwrap(overlay) + + XCTAssertNil(appDelegate.openCommandURL(try link("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 { launch() let colorBefore = appDelegate.currentColor 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 +