Compare commits

..
6 changed files with 923 additions and 4 deletions
+265
View File
@@ -0,0 +1,265 @@
import AppKit
import Carbon.HIToolbox
import Foundation
import Observation
import SwiftUI
import ShotdeckCore
@MainActor
public protocol SendCapable: AnyObject {
func send(anchor: NSView?) async
}
@MainActor
public protocol SettingsWindowPresenting: AnyObject {
func presentSettingsWindow()
}
@MainActor
public protocol ReturnsSectionProviding: AnyObject {
@ViewBuilder func returnsSection() -> AnyView
}
@MainActor
@Observable
public final class AppModel {
public private(set) var session: CaptureSession
public private(set) var region: CaptureRegion?
public private(set) var screenRecordingGranted: Bool
public private(set) var allReturns: [ReturnedDocument] = []
public private(set) var commentedReturns: [ReturnedDocument] = []
public private(set) var statusLine: String?
public private(set) var isCapturing: Bool = false
public private(set) var isSending: Bool = false
public private(set) var outboxDisplayName: String
public private(set) var watchFolderDisplayName: String
/// Live outbox; WP-4b reads this (not `paths.outbox`) so Settings folder changes take effect.
public private(set) var outboxURL: URL
/// Live watch folder; WP-4c updates this alongside `ReturnWatcher.updateWatchFolder`.
public private(set) var watchFolderURL: URL
let paths: AppSupportPaths
let spool: SpoolStore
let composer: PDFComposer
let capturer: ScreenCapturer
let hotkeys: HotkeyCenter
let picker: RegionPickerController
let ledger: ReturnLedger
let watcher: ReturnWatcher
public init(
paths: AppSupportPaths,
spool: SpoolStore,
composer: PDFComposer,
capturer: ScreenCapturer,
hotkeys: HotkeyCenter,
picker: RegionPickerController,
ledger: ReturnLedger,
watcher: ReturnWatcher
) {
self.paths = paths
self.spool = spool
self.composer = composer
self.capturer = capturer
self.hotkeys = hotkeys
self.picker = picker
self.ledger = ledger
self.watcher = watcher
self.session = CaptureSession(
id: UUID(),
createdAt: Date(),
state: .open,
captures: [],
pdfFileName: nil
)
self.region = nil
self.screenRecordingGranted = ScreenCapturer.isScreenRecordingGranted
// Seeded from FolderSettings.resolve() via resolvedAppSupportPaths never .standard().
let folders = FolderSettings.resolve()
self.outboxURL = folders.outbox
self.watchFolderURL = folders.watch
self.outboxDisplayName = folders.outbox.lastPathComponent
self.watchFolderDisplayName = folders.watch.lastPathComponent
}
// MARK: Seam mutators the only way a WP-4b/4c extension changes state.
func setStatus(_ text: String?) { statusLine = text }
func setSending(_ value: Bool) { isSending = value }
func setCapturing(_ value: Bool) { isCapturing = value }
func replaceSession(_ new: CaptureSession) { session = new }
func replaceRegion(_ new: CaptureRegion?) { region = new }
func setReturns(all: [ReturnedDocument], commented: [ReturnedDocument]) {
allReturns = all
commentedReturns = commented
}
func setFolderDisplayNames(outbox: String, watch: String) {
outboxDisplayName = outbox
watchFolderDisplayName = watch
}
func setFolderURLs(outbox: URL, watch: URL) {
outboxURL = outbox
watchFolderURL = watch
setFolderDisplayNames(outbox: outbox.lastPathComponent, watch: watch.lastPathComponent)
}
public var iconState: MenuIconState {
if !screenRecordingGranted { return .recordingMissing }
if isCapturing { return .capturing }
if region == nil { return .noRegion }
if session.captures.isEmpty { return .regionEmpty }
return .hasCaptures(session.captures.count)
}
public func bootstrap() async {
if let data = UserDefaults.standard.data(forKey: CaptureRegion.defaultsKey),
let decoded = try? JSONDecoder().decode(CaptureRegion.self, from: data),
decoded.isStillValid {
replaceRegion(decoded)
}
do {
let recovered = try await spool.currentSession()
replaceSession(recovered)
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not open the spool.")
}
do {
let initial = try await ledger.all()
let commented = try await ledger.commented()
setReturns(all: initial, commented: commented)
} catch {
// Empty ledger on first run is not an error.
}
do {
try await watcher.start { [weak self] _ in
Task { @MainActor in
guard let self else { return }
let all = (try? await self.ledger.all()) ?? []
let commented = (try? await self.ledger.commented()) ?? []
self.setReturns(all: all, commented: commented)
}
}
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not watch the return folder.")
}
let registered = hotkeys.register(
id: "capture",
keyCode: UInt32(kVK_ANSI_2),
modifiers: UInt32(optionKey | shiftKey)
) { [weak self] in
Task { await self?.captureNow() }
}
if !registered {
setStatus("⌥⇧2 is already used by another app — capture only works from the menu.")
}
}
public func captureNow() async {
guard !isCapturing else { return }
setCapturing(true)
defer { setCapturing(false) }
var target = region
if target == nil {
target = await withCheckedContinuation { (cont: CheckedContinuation<CaptureRegion?, Never>) in
picker.pick { picked in cont.resume(returning: picked) }
}
guard let picked = target else {
setStatus("No region selected.")
return
}
persistRegion(picked)
}
guard let region = target else { return }
do {
let image = try await capturer.capture(region)
let capture = try await spool.append(
pngData: image.pngData,
pixelWidth: image.pixelWidth,
pixelHeight: image.pixelHeight,
scale: image.scale,
capturedAt: Date()
)
replaceSession(try await spool.currentSession())
setStatus("Captured page \(capture.sequence).")
} catch {
screenRecordingGranted = ScreenCapturer.isScreenRecordingGranted
setStatus((error as? ShotdeckError)?.errorDescription ?? "The screenshot could not be taken.")
}
}
public func rePickRegion() async {
let picked = await withCheckedContinuation { (cont: CheckedContinuation<CaptureRegion?, Never>) in
picker.pick { cont.resume(returning: $0) }
}
guard let picked else { return }
persistRegion(picked)
setStatus("Region set: \(Int(picked.rect.width)) × \(Int(picked.rect.height)).")
}
public func removeCapture(id: UUID) async {
do {
// D-11: SpoolStore.remove MOVES the PNG to <session>/removed/; it is never unlinked.
replaceSession(try await spool.remove(captureID: id))
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not remove that capture.")
}
}
public func copyCommentedLinks() async {
do {
let text = try await ledger.clipboardText()
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.setString(text, forType: .string)
let count = commentedReturns.count
setStatus("Copied \(count) link\(count == 1 ? "" : "s").")
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Nothing to copy.")
}
}
public func openSpoolFolder() {
NSWorkspace.shared.open(paths.spool)
}
public func openScreenRecordingSettings() {
guard let url = URL(string:
"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture") else {
setStatus("Could not open System Settings.")
return
}
NSWorkspace.shared.open(url)
}
private func persistRegion(_ picked: CaptureRegion) {
replaceRegion(picked)
if let encoded = try? JSONEncoder().encode(picked) {
UserDefaults.standard.set(encoded, forKey: CaptureRegion.defaultsKey)
}
}
}
public enum MenuIconState: Equatable {
case noRegion, regionEmpty, hasCaptures(Int), capturing, recordingMissing
public var symbolName: String {
switch self {
case .noRegion: return "viewfinder"
case .regionEmpty: return "viewfinder.rectangular"
case .hasCaptures: return "viewfinder.rectangular"
case .capturing: return "viewfinder.circle.fill"
case .recordingMissing: return "exclamationmark.triangle"
}
}
public var countText: String? {
if case .hasCaptures(let n) = self { return "\(n)" }
return nil
}
}
+180
View File
@@ -0,0 +1,180 @@
import AppKit
import SwiftUI
import ShotdeckCore
struct MenuBarView: View {
@Environment(AppModel.self) private var model
var body: some View {
VStack(alignment: .leading, spacing: 8) {
statusRow
SessionStrip()
Divider()
actionsList
if !model.allReturns.isEmpty {
Divider()
returnsBlock
}
}
.padding(10)
.frame(width: 320, alignment: .leading)
.controlSize(.small)
}
@ViewBuilder
private var statusRow: some View {
if !model.screenRecordingGranted {
HStack(alignment: .top, spacing: 6) {
Image(systemName: "exclamationmark.triangle")
.foregroundStyle(.yellow)
VStack(alignment: .leading, spacing: 4) {
Text(
ShotdeckError.screenRecordingNotGranted.errorDescription
?? "Screen Recording is turned off."
)
.font(.caption)
.fixedSize(horizontal: false, vertical: true)
Button("Open Screen Recording settings") {
model.openScreenRecordingSettings()
}
}
}
} else {
Text(model.statusLine ?? defaultStatusText)
.font(.caption)
.foregroundStyle(.primary)
.fixedSize(horizontal: false, vertical: true)
}
}
private var defaultStatusText: String {
guard let region = model.region else {
return "No region yet — press ⌥⇧2 to pick one."
}
let w = Int(region.rect.width)
let h = Int(region.rect.height)
let display = displayName(for: region)
if model.session.isEmpty {
return "Region \(w) × \(h) on \(display) · Nothing captured yet."
}
let count = model.session.captures.count
return "\(count) captures · region \(w) × \(h) on \(display)"
}
private func displayName(for region: CaptureRegion) -> String {
for (index, screen) in NSScreen.screens.enumerated() {
let id = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?
.uint32Value
if id == region.displayID {
return "Display \(index + 1)"
}
}
return "Display 1"
}
private var actionsList: some View {
VStack(alignment: .leading, spacing: 2) {
Button {
let anchor = NSApp.keyWindow?.contentView
if let sender = model as? SendCapable {
Task { await sender.send(anchor: anchor) }
} else {
model.setStatus("Send is not available in this build.")
}
} label: {
actionLabel("Send…")
}
.disabled(model.session.isEmpty || model.isSending)
Button {
Task { await model.captureNow() }
} label: {
actionLabel("Capture now", trailing: "⌥⇧2")
}
.disabled(model.isCapturing)
Button {
Task { await model.rePickRegion() }
} label: {
actionLabel("Re-select area")
}
Button {
Task { await model.copyCommentedLinks() }
} label: {
actionLabel(
"Copy commented links",
trailing: model.commentedReturns.isEmpty ? nil : "\(model.commentedReturns.count)"
)
}
.disabled(model.commentedReturns.isEmpty)
Button {
model.openSpoolFolder()
} label: {
actionLabel("Open spool folder")
}
Button {
if let presenter = model as? SettingsWindowPresenting {
presenter.presentSettingsWindow()
} else {
model.setStatus("Settings is not available in this build.")
}
} label: {
actionLabel("Settings…")
}
Button {
NSApp.terminate(nil)
} label: {
actionLabel("Quit Shotdeck")
}
}
.buttonStyle(.plain)
}
private func actionLabel(_ title: String, trailing: String? = nil) -> some View {
HStack(spacing: 8) {
Text(title)
Spacer(minLength: 8)
if let trailing {
Text(trailing)
.foregroundStyle(.secondary)
.monospacedDigit()
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
.padding(.vertical, 3)
}
@ViewBuilder
private var returnsBlock: some View {
if let provider = model as? ReturnsSectionProviding {
provider.returnsSection()
} else {
VStack(alignment: .leading, spacing: 4) {
Text("Came back from your device")
.font(.caption)
.foregroundStyle(.secondary)
ForEach(newestReturns.prefix(8)) { doc in
HStack(spacing: 8) {
Text(doc.fileURL.lastPathComponent)
.lineLimit(1)
Spacer(minLength: 8)
Text(doc.isCommented
? "\(doc.annotatedPages.count) page\(doc.annotatedPages.count == 1 ? "" : "s") marked"
: "not marked")
.font(.caption)
.foregroundStyle(doc.isCommented ? .primary : .secondary)
}
}
}
}
}
private var newestReturns: [ReturnedDocument] {
model.allReturns.sorted { $0.detectedAt > $1.detectedAt }
}
}
+78
View File
@@ -0,0 +1,78 @@
import AppKit
import SwiftUI
import ShotdeckCore
struct SessionStrip: View {
@Environment(AppModel.self) private var model
var body: some View {
if model.session.captures.isEmpty {
Text("Nothing captured yet.")
.font(.caption)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, minHeight: 64, alignment: .leading)
} else {
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: 6) {
ForEach(model.session.captures) { capture in
SessionThumb(capture: capture)
}
}
}
.frame(height: 64)
}
}
}
private struct SessionThumb: View {
@Environment(AppModel.self) private var model
let capture: Capture
@State private var hovering = false
var body: some View {
ZStack(alignment: .topLeading) {
thumbnail
Text("\(capture.sequence)")
.font(.system(size: 9, weight: .bold))
.foregroundStyle(.white)
.padding(.horizontal, 4)
.padding(.vertical, 1)
.background(.black.opacity(0.65))
.clipShape(RoundedRectangle(cornerRadius: 2, style: .continuous))
.padding(3)
if hovering {
VStack {
Spacer()
Button("Remove") {
Task { await model.removeCapture(id: capture.id) }
}
.font(.system(size: 10, weight: .semibold))
.buttonStyle(.plain)
.foregroundStyle(.white)
.frame(maxWidth: .infinity)
.padding(.vertical, 3)
.background(.black.opacity(0.7))
}
}
}
.frame(height: 64)
.clipped()
.onHover { hovering = $0 }
.help(DubaiTime.stamp(capture.capturedAt))
}
@ViewBuilder
private var thumbnail: some View {
let url = model.paths.sessionDirectory(model.session.id).appendingPathComponent(capture.fileName)
if let image = NSImage(contentsOf: url) {
Image(nsImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 64)
} else {
Rectangle()
.fill(Color.secondary.opacity(0.2))
.frame(width: 64, height: 64)
}
}
}
+73 -4
View File
@@ -1,6 +1,75 @@
import AppKit import AppKit
import SwiftUI
import ShotdeckCore
// WP-4 replaces this body with the real menu-bar UI. // SwiftPM treats a file named main.swift as top-level code, which forbids `@main`.
let application = NSApplication.shared // App.main() is the equivalent entry point.
application.setActivationPolicy(.accessory) ShotdeckApp.main()
application.run()
struct ShotdeckApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
var body: some Scene {
MenuBarExtra {
MenuBarView()
.environment(appDelegate.model)
} label: {
let state = appDelegate.model.iconState
HStack(spacing: 4) {
Image(systemName: state.symbolName)
if let count = state.countText {
Text(count).font(.system(size: 11, weight: .semibold))
}
}
.accessibilityLabel("Shotdeck")
}
.menuBarExtraStyle(.window)
}
}
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
let model: AppModel
override init() {
NSApplication.shared.setActivationPolicy(.accessory)
model = AppDelegate.makeLaunchModel()
super.init()
}
func applicationDidFinishLaunching(_ notification: Notification) {
Task { await model.bootstrap() }
}
private static func makeLaunchModel() -> AppModel {
do {
let paths = try FolderSettings.resolvedAppSupportPaths()
return try makeModel(paths: paths)
} catch {
Log.ui.critical(
"AppModel init failed: \(String(describing: error), privacy: .public)"
)
let tmp = FileManager.default.temporaryDirectory
let fallbackRoot = tmp.appendingPathComponent("Shotdeck-fallback", isDirectory: true)
// Safe: temp-dir creation for a path this process controls cannot legitimately fail.
let fallback = try! AppSupportPaths(root: fallbackRoot, outbox: tmp, watchFolder: tmp)
let model = try! makeModel(paths: fallback)
model.setStatus("Shotdeck could not access its storage folder. Captures will not persist.")
return model
}
}
private static func makeModel(paths: AppSupportPaths) throws -> AppModel {
let ledger = try ReturnLedger(paths: paths)
return AppModel(
paths: paths,
spool: try SpoolStore(paths: paths),
composer: PDFComposer(),
capturer: ScreenCapturer(),
hotkeys: HotkeyCenter(),
picker: RegionPickerController(),
ledger: ledger,
watcher: ReturnWatcher(paths: paths, ledger: ledger)
)
}
}
@@ -0,0 +1,154 @@
import Foundation
import PDFKit
import CoreServices // FSEventStream* APIs; system framework, no Package.swift change needed
public actor ReturnWatcher {
private let ledger: ReturnLedger
private var watchFolder: URL
private var onChange: (@Sendable ([ReturnedDocument]) -> Void)?
private var stream: FSEventStreamRef?
private var bridge: FSEventBridge?
private var pendingScanTask: Task<Void, Never>?
private let eventQueue = DispatchQueue(label: "ai.flowmaster.shotdeck.returns.fsevents")
/// Watch folder is `paths.watchFolder`, which production constructs from
/// `FolderSettings.resolve().watch`. This type never calls FolderSettings;
/// `updateWatchFolder` is invoked by the UI layer only.
public init(paths: AppSupportPaths, ledger: ReturnLedger) {
self.ledger = ledger
self.watchFolder = paths.watchFolder // never a literal "~/Downloads" here
}
/// Starts watching paths.watchFolder for returned PDFs. Performs one immediate
/// scanNow() before returning, then calls onChange after every subsequent debounced
/// batch (even if that batch's result is empty the caller decides what to do).
public func start(onChange: @escaping @Sendable ([ReturnedDocument]) -> Void) async throws {
self.onChange = onChange
try startStream(on: watchFolder)
let found = try await scanNow()
onChange(found)
}
/// Idempotent. Stops and releases the FSEventStream if one is running; safe to call
/// when never started or already stopped. Cancels any pending debounced scan.
public func stop() {
// Idempotent: nil stream / already-stopped is a no-op; never started is the same.
pendingScanTask?.cancel()
pendingScanTask = nil
if let stream {
FSEventStreamStop(stream)
FSEventStreamInvalidate(stream)
FSEventStreamRelease(stream)
}
stream = nil
bridge = nil
}
/// Called by whoever owns the Settings "Choose..." folder action (WP-4c) after the user
/// picks a new watch folder. If the watcher was running, stops the old FSEventStream,
/// switches to the new folder, restarts, and performs one immediate scanNow (reporting
/// through the same onChange callback given to start()). If the watcher was never
/// started, only updates the stored folder for the next start() call.
public func updateWatchFolder(_ url: URL) async throws {
let wasRunning = stream != nil
stop()
watchFolder = url
guard wasRunning else { return }
try startStream(on: url)
let found = try await scanNow()
onChange?(found)
}
/// Scans the watch folder once, immediately, without waiting for an event. Every
/// recognized, stable, openable Shotdeck PDF present is (re-)inspected and (re-)recorded
/// into the ledger; returns exactly the documents processed in this call.
@discardableResult
public func scanNow() async throws -> [ReturnedDocument] {
let fm = FileManager.default
let candidates = (try? fm.contentsOfDirectory(
at: watchFolder, includingPropertiesForKeys: nil
)) ?? []
var results: [ReturnedDocument] = []
for url in candidates.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) {
let name = url.lastPathComponent
// ".pdf.inprogress" already fails hasSuffix(".pdf") -> naturally skipped.
guard name.hasSuffix(".pdf"), !name.hasPrefix(".") else { continue }
guard await isStableAndReadable(url) else { continue } // leave for next event
guard let document = PDFDocument(url: url),
AnnotationInspector.isShotdeckDocument(document) else { continue }
guard let inspected = try? AnnotationInspector.inspect(fileURL: url) else { continue }
try await ledger.record(inspected)
results.append(inspected)
}
return results
}
/// Size-stable: two equal byte counts 250 ms apart AND PDFDocument opens;
/// otherwise leave the file for the next event.
private func isStableAndReadable(_ url: URL) async -> Bool {
let fm = FileManager.default
guard let size1 = try? fm.attributesOfItem(atPath: url.path)[.size] as? Int else { return false }
try? await Task.sleep(for: .milliseconds(250))
guard let size2 = try? fm.attributesOfItem(atPath: url.path)[.size] as? Int else { return false }
guard size1 == size2, size1 > 0 else { return false }
return PDFDocument(url: url) != nil
}
private func startStream(on folder: URL) throws {
let bridge = FSEventBridge { [weak self] in
guard let self else { return }
Task { await self.scheduleDebouncedScan() }
}
self.bridge = bridge
var context = FSEventStreamContext()
context.version = 0
context.info = Unmanaged.passUnretained(bridge).toOpaque()
context.retain = nil
context.release = nil
context.copyDescription = nil
guard let stream = FSEventStreamCreate(
kCFAllocatorDefault, shotdeckFSEventsCallback, &context,
[folder.path] as CFArray, FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
0.0,
FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagNoDefer)
) else {
throw ShotdeckError.captureFailed(underlying: "could not create FSEventStream for \(folder.path)")
}
// Dispatch queue, not a run loop: this actor has no run loop of its own, and
// FSEventStreamSetDispatchQueue is the modern replacement for
// FSEventStreamScheduleWithRunLoop. One dedicated serial queue per watcher.
FSEventStreamSetDispatchQueue(stream, eventQueue)
guard FSEventStreamStart(stream) else {
FSEventStreamInvalidate(stream)
FSEventStreamRelease(stream)
throw ShotdeckError.captureFailed(underlying: "FSEventStreamStart failed for \(folder.path)")
}
self.stream = stream
}
private func scheduleDebouncedScan() async {
pendingScanTask?.cancel()
pendingScanTask = Task {
try? await Task.sleep(for: .milliseconds(400)) // coalesce AirDrop's write+rename burst
guard !Task.isCancelled else { return }
guard let found = try? await self.scanNow() else { return }
// One in-flight debounced callback may land after stop(); it is a
// harmless read-only rescan (ledger upsert, no watch-folder mutation).
self.onChange?(found)
}
}
}
/// Non-actor bridge because FSEventStreamCallback is a @convention(c) function pointer and
/// cannot capture actor-isolated state directly; it hops back onto the actor via Task.
private final class FSEventBridge: @unchecked Sendable {
// @unchecked is safe: `notify` is a let, set once at init, never mutated after the
// type is immutable for its entire lifetime.
let notify: @Sendable () -> Void
init(notify: @escaping @Sendable () -> Void) { self.notify = notify }
}
private let shotdeckFSEventsCallback: FSEventStreamCallback = { _, info, _, _, _, _ in
guard let info else { return }
Unmanaged<FSEventBridge>.fromOpaque(info).takeUnretainedValue().notify()
}
@@ -0,0 +1,173 @@
import AppKit
import Foundation
import PDFKit
import Testing
import ShotdeckCore
private let pageBounds = CGRect(x: 0, y: 0, width: 600, height: 800)
private func makeAnnotation(
_ subtype: PDFAnnotationSubtype,
bounds: CGRect = CGRect(x: 100, y: 100, width: 80, height: 40),
contents: String? = nil
) -> PDFAnnotation {
let annotation = PDFAnnotation(
bounds: bounds,
forType: subtype,
withProperties: nil
)
annotation.contents = contents
return annotation
}
private func makePDF(
at url: URL,
pageCount: Int,
creator: String? = "Shotdeck",
subject: String? = nil,
annotations: [(page: Int, annotation: PDFAnnotation)] = []
) throws {
let document = PDFDocument()
for index in 0..<pageCount {
let page = PDFPage()
page.setBounds(pageBounds, for: .mediaBox)
document.insert(page, at: index)
}
var attributes = [PDFDocumentAttribute: Any]()
if let creator { attributes[.creatorAttribute] = creator }
if let subject { attributes[.subjectAttribute] = subject }
document.documentAttributes = attributes
for item in annotations {
guard let page = document.page(at: item.page) else {
throw NSError(domain: "WP5Test", code: 1)
}
page.addAnnotation(item.annotation)
}
guard document.write(to: url) else {
throw NSError(domain: "WP5Test", code: 2)
}
}
private func makeCasePaths() throws -> (paths: AppSupportPaths, cleanup: URL) {
let cleanup = FileManager.default.temporaryDirectory
.appendingPathComponent("shotdeck-wp5b-\(UUID().uuidString)", isDirectory: true)
let paths = try AppSupportPaths(
root: cleanup.appendingPathComponent("root", isDirectory: true),
outbox: cleanup.appendingPathComponent("outbox", isDirectory: true),
watchFolder: cleanup.appendingPathComponent("watch", isDirectory: true)
)
return (paths, cleanup)
}
/// Guards `confirmation(expectedCount: 1)` against a create+rename double-event.
private final class ConfirmOnce: @unchecked Sendable {
private let lock = NSLock()
private var fired = false
func run(_ body: () -> Void) {
lock.lock()
defer { lock.unlock() }
guard !fired else { return }
fired = true
body()
}
}
@Test("W-25 Duplicate-name suffix is the normal AirDrop return (scanNow)")
func w25_duplicateNameSuffixIsRecognizedByScanNow() async throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
let pdfURL = paths.watchFolder.appendingPathComponent("Shotdeck-20260830-134205 2.pdf")
try makePDF(
at: pdfURL,
pageCount: 1,
creator: nil,
subject: "33333333-3333-3333-3333-333333333333",
annotations: [(page: 0, annotation: makeAnnotation(
.ink, bounds: CGRect(x: 100, y: 100, width: 120, height: 50)
))]
)
let found = try await watcher.scanNow()
#expect(found.count == 1)
let doc = try #require(found.first)
#expect(doc.fileURL.lastPathComponent == "Shotdeck-20260830-134205 2.pdf")
#expect(doc.fileURL.resolvingSymlinksInPath().path == pdfURL.resolvingSymlinksInPath().path)
#expect(doc.pageCount == 1)
#expect(doc.annotatedPages == [1])
#expect(doc.isCommented == true)
let commented = try await ledger.commented()
#expect(commented.count == 1)
#expect(commented[0].fileURL.lastPathComponent == pdfURL.lastPathComponent)
#expect(commented[0].fileURL.resolvingSymlinksInPath().path == pdfURL.resolvingSymlinksInPath().path)
}
@Test("W-26 Creator provenance negative at the scan level")
func w26_presentNonShotdeckCreatorIsIgnoredByScanNow() async throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
let pdfURL = paths.watchFolder.appendingPathComponent("Shotdeck-20260830-134218.pdf")
try makePDF(
at: pdfURL,
pageCount: 1,
creator: "Preview",
annotations: [(page: 0, annotation: makeAnnotation(
.ink, bounds: CGRect(x: 100, y: 100, width: 120, height: 50)
))]
)
let found = try await watcher.scanNow()
#expect(found.isEmpty)
let all = try await ledger.all()
#expect(all.isEmpty)
}
@Test("W-27 FSEvents live callback fires on a real file arrival")
func w27_fsEventsCallbackFiresOnRealArrival() async throws {
let (paths, cleanup) = try makeCasePaths()
defer { try? FileManager.default.removeItem(at: cleanup) }
let ledger = try ReturnLedger(paths: paths)
let watcher = ReturnWatcher(paths: paths, ledger: ledger)
let pdfURL = paths.watchFolder.appendingPathComponent("Shotdeck-20260830-140000.pdf")
let once = ConfirmOnce()
try await confirmation("watcher reports the arrived PDF", expectedCount: 1) { confirm in
do {
try await watcher.start { docs in
if docs.contains(where: { $0.fileURL.lastPathComponent == pdfURL.lastPathComponent }) {
once.run { confirm() }
}
}
// Simulate AirDrop's own write-then-rename so the watcher must survive that pattern.
let tmpURL = pdfURL.appendingPathExtension("inprogress")
try makePDF(
at: tmpURL, pageCount: 1, creator: "Shotdeck",
annotations: [(page: 0, annotation: makeAnnotation(
.ink, bounds: CGRect(x: 100, y: 100, width: 120, height: 50)
))]
)
try FileManager.default.moveItem(at: tmpURL, to: pdfURL)
} catch {
print("fsEventsCallbackFiresOnRealArrival error: \(error)")
await watcher.stop()
throw error
}
// Budget: 400ms debounce + FS latency + the 250ms stability re-read + PDFKit open.
// 5s is a generous, fixed ceiling never a "some time" wait.
try await Task.sleep(for: .seconds(5))
await watcher.stop()
await watcher.stop()
}
}