diff --git a/1/Applications/Redline.app.previous/Contents/Info.plist b/1/Applications/Redline.app.previous/Contents/Info.plist new file mode 100644 index 0000000..a1f1f00 --- /dev/null +++ b/1/Applications/Redline.app.previous/Contents/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleExecutable + Shotdeck + CFBundleIconFile + AppIcon + CFBundleIdentifier + ai.flowmaster.shotdeck + CFBundleName + Redline + CFBundlePackageType + APPL + CFBundleShortVersionString + 99.0.0 + CFBundleVersion + 5 + LSMinimumSystemVersion + 14.0 + LSUIElement + + NSHumanReadableCopyright + Copyright © 2026 Flowmaster FZC LLC. All rights reserved. + + diff --git a/1/Applications/Redline.app.previous/Contents/MacOS/Shotdeck b/1/Applications/Redline.app.previous/Contents/MacOS/Shotdeck new file mode 100755 index 0000000..e383932 Binary files /dev/null and b/1/Applications/Redline.app.previous/Contents/MacOS/Shotdeck differ diff --git a/1/Applications/Redline.app.previous/Contents/Resources/AppIcon.icns b/1/Applications/Redline.app.previous/Contents/Resources/AppIcon.icns new file mode 100644 index 0000000..f3396f0 Binary files /dev/null and b/1/Applications/Redline.app.previous/Contents/Resources/AppIcon.icns differ diff --git a/1/Applications/Redline.app.previous/Contents/_CodeSignature/CodeResources b/1/Applications/Redline.app.previous/Contents/_CodeSignature/CodeResources new file mode 100644 index 0000000..c650985 --- /dev/null +++ b/1/Applications/Redline.app.previous/Contents/_CodeSignature/CodeResources @@ -0,0 +1,128 @@ + + + + + files + + Resources/AppIcon.icns + + WH6vz/PQ1NXa7ko7QlCGPEtVLxU= + + + files2 + + Resources/AppIcon.icns + + hash2 + + LEP/PkABbPR3LYbMANoGI9OErrWNA+KhCulMlhTloaI= + + + + rules + + ^Resources/ + + ^Resources/.*\.lproj/ + + optional + + weight + 1000 + + ^Resources/.*\.lproj/locversion.plist$ + + omit + + weight + 1100 + + ^Resources/Base\.lproj/ + + weight + 1010 + + ^version.plist$ + + + rules2 + + .*\.dSYM($|/) + + weight + 11 + + ^(.*/)?\.DS_Store$ + + omit + + weight + 2000 + + ^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/ + + nested + + weight + 10 + + ^.* + + ^Info\.plist$ + + omit + + weight + 20 + + ^PkgInfo$ + + omit + + weight + 20 + + ^Resources/ + + weight + 20 + + ^Resources/.*\.lproj/ + + optional + + weight + 1000 + + ^Resources/.*\.lproj/locversion.plist$ + + omit + + weight + 1100 + + ^Resources/Base\.lproj/ + + weight + 1010 + + ^[^/]+$ + + nested + + weight + 10 + + ^embedded\.provisionprofile$ + + weight + 20 + + ^version\.plist$ + + weight + 20 + + + + diff --git a/1/Applications/Redline.app/Contents/Info.plist b/1/Applications/Redline.app/Contents/Info.plist new file mode 100644 index 0000000..c37d03e --- /dev/null +++ b/1/Applications/Redline.app/Contents/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleExecutable + Shotdeck + CFBundleIconFile + AppIcon + CFBundleIdentifier + ai.flowmaster.shotdeck + CFBundleName + Redline + CFBundlePackageType + APPL + CFBundleShortVersionString + 0.3.2 + CFBundleVersion + 5 + LSMinimumSystemVersion + 14.0 + LSUIElement + + NSHumanReadableCopyright + Copyright © 2026 Flowmaster FZC LLC. All rights reserved. + + diff --git a/1/Applications/Redline.app/Contents/MacOS/Shotdeck b/1/Applications/Redline.app/Contents/MacOS/Shotdeck new file mode 100755 index 0000000..8becd14 Binary files /dev/null and b/1/Applications/Redline.app/Contents/MacOS/Shotdeck differ diff --git a/1/Applications/Redline.app/Contents/Resources/AppIcon.icns b/1/Applications/Redline.app/Contents/Resources/AppIcon.icns new file mode 100644 index 0000000..f3396f0 Binary files /dev/null and b/1/Applications/Redline.app/Contents/Resources/AppIcon.icns differ diff --git a/1/Applications/Redline.app/Contents/_CodeSignature/CodeResources b/1/Applications/Redline.app/Contents/_CodeSignature/CodeResources new file mode 100644 index 0000000..c650985 --- /dev/null +++ b/1/Applications/Redline.app/Contents/_CodeSignature/CodeResources @@ -0,0 +1,128 @@ + + + + + files + + Resources/AppIcon.icns + + WH6vz/PQ1NXa7ko7QlCGPEtVLxU= + + + files2 + + Resources/AppIcon.icns + + hash2 + + LEP/PkABbPR3LYbMANoGI9OErrWNA+KhCulMlhTloaI= + + + + rules + + ^Resources/ + + ^Resources/.*\.lproj/ + + optional + + weight + 1000 + + ^Resources/.*\.lproj/locversion.plist$ + + omit + + weight + 1100 + + ^Resources/Base\.lproj/ + + weight + 1010 + + ^version.plist$ + + + rules2 + + .*\.dSYM($|/) + + weight + 11 + + ^(.*/)?\.DS_Store$ + + omit + + weight + 2000 + + ^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/ + + nested + + weight + 10 + + ^.* + + ^Info\.plist$ + + omit + + weight + 20 + + ^PkgInfo$ + + omit + + weight + 20 + + ^Resources/ + + weight + 20 + + ^Resources/.*\.lproj/ + + optional + + weight + 1000 + + ^Resources/.*\.lproj/locversion.plist$ + + omit + + weight + 1100 + + ^Resources/Base\.lproj/ + + weight + 1010 + + ^[^/]+$ + + nested + + weight + 10 + + ^embedded\.provisionprofile$ + + weight + 20 + + ^version\.plist$ + + weight + 20 + + + + diff --git a/1/Redline-99.0.0.zip b/1/Redline-99.0.0.zip new file mode 100644 index 0000000..ba7c8e1 Binary files /dev/null and b/1/Redline-99.0.0.zip differ diff --git a/1/appcast.json b/1/appcast.json new file mode 100644 index 0000000..22be1a3 --- /dev/null +++ b/1/appcast.json @@ -0,0 +1 @@ +{"notes":"UPDATE-SELFTEST","sha256":"666800eb452240465677c1e33e8ec0f009e5cfe2fde1a789201856dc624992ef","version":"99.0.0","zipURL":"file:\/\/\/Users\/benjaminhippler\/mmd-projects\/shotdeck\/1\/Redline-99.0.0.zip"} \ No newline at end of file diff --git a/1/overlay-middrag.png b/1/overlay-middrag.png new file mode 100644 index 0000000..bea713a Binary files /dev/null and b/1/overlay-middrag.png differ diff --git a/1/payload/Redline.app/Contents/Info.plist b/1/payload/Redline.app/Contents/Info.plist new file mode 100644 index 0000000..a1f1f00 --- /dev/null +++ b/1/payload/Redline.app/Contents/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleExecutable + Shotdeck + CFBundleIconFile + AppIcon + CFBundleIdentifier + ai.flowmaster.shotdeck + CFBundleName + Redline + CFBundlePackageType + APPL + CFBundleShortVersionString + 99.0.0 + CFBundleVersion + 5 + LSMinimumSystemVersion + 14.0 + LSUIElement + + NSHumanReadableCopyright + Copyright © 2026 Flowmaster FZC LLC. All rights reserved. + + diff --git a/1/payload/Redline.app/Contents/MacOS/Shotdeck b/1/payload/Redline.app/Contents/MacOS/Shotdeck new file mode 100755 index 0000000..e383932 Binary files /dev/null and b/1/payload/Redline.app/Contents/MacOS/Shotdeck differ diff --git a/1/payload/Redline.app/Contents/Resources/AppIcon.icns b/1/payload/Redline.app/Contents/Resources/AppIcon.icns new file mode 100644 index 0000000..f3396f0 Binary files /dev/null and b/1/payload/Redline.app/Contents/Resources/AppIcon.icns differ diff --git a/1/payload/Redline.app/Contents/_CodeSignature/CodeResources b/1/payload/Redline.app/Contents/_CodeSignature/CodeResources new file mode 100644 index 0000000..c650985 --- /dev/null +++ b/1/payload/Redline.app/Contents/_CodeSignature/CodeResources @@ -0,0 +1,128 @@ + + + + + files + + Resources/AppIcon.icns + + WH6vz/PQ1NXa7ko7QlCGPEtVLxU= + + + files2 + + Resources/AppIcon.icns + + hash2 + + LEP/PkABbPR3LYbMANoGI9OErrWNA+KhCulMlhTloaI= + + + + rules + + ^Resources/ + + ^Resources/.*\.lproj/ + + optional + + weight + 1000 + + ^Resources/.*\.lproj/locversion.plist$ + + omit + + weight + 1100 + + ^Resources/Base\.lproj/ + + weight + 1010 + + ^version.plist$ + + + rules2 + + .*\.dSYM($|/) + + weight + 11 + + ^(.*/)?\.DS_Store$ + + omit + + weight + 2000 + + ^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/ + + nested + + weight + 10 + + ^.* + + ^Info\.plist$ + + omit + + weight + 20 + + ^PkgInfo$ + + omit + + weight + 20 + + ^Resources/ + + weight + 20 + + ^Resources/.*\.lproj/ + + optional + + weight + 1000 + + ^Resources/.*\.lproj/locversion.plist$ + + omit + + weight + 1100 + + ^Resources/Base\.lproj/ + + weight + 1010 + + ^[^/]+$ + + nested + + weight + 10 + + ^embedded\.provisionprofile$ + + weight + 20 + + ^version\.plist$ + + weight + 20 + + + + diff --git a/Info.plist b/Info.plist index e387343..44215de 100644 --- a/Info.plist +++ b/Info.plist @@ -13,9 +13,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 0.4.0 + 0.6.0 CFBundleVersion - 6 + 8 LSMinimumSystemVersion 14.0 LSUIElement diff --git a/README.md b/README.md index 584de7b..1c4a08c 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,76 @@ A macOS menu-bar app that captures a remembered screen region, builds a one-screenshot-per-page PDF, AirDrops it to an iPad for markup, then watches for the annotated file to come back. +## What Capture takes + +Four scopes, chosen in the popover (or the window's capture menu) and kept with the session: + +- **Area** — the saved rectangle. `Choose Area…` picks a new one at any time. +- **Window** — the window under the pointer. Redline hides itself, dims the screen, names + the app under the cursor and highlights its window; click to capture it, Escape cancels. +- **Browser** — the front browser window (Safari, Chrome, Edge, Brave, Arc, Firefox, + Vivaldi, Opera). +- **Screen** — the whole display your saved area is on. + +Window and Browser capture a single window, so nothing overlapping it ends up in the shot. + ## Hotkeys - **⌥⇧1** — pick a new region, then capture it. - **⌥⇧2** — capture the remembered region instantly (no picker). +## Where things live + +Two surfaces, two jobs: + +- **Menu-bar popover** — only the current session: its review details on one line, its + pages, then Capture, Send, New Session, Open Redline, and one status line when + something happened. Nothing else, so it never scrolls. +- **Redline window** (Open Redline) — the workspace: every session in a sidebar grouped + by day, the selected session's pages in the middle, and its review details, PDF facts + and session facts in the inspector. History, text entry and file facts live here + because they need room and a window that stays open. +- **Settings** — one door: the gear in the popover header, or ⌘,. Capture, sending, +- sessions and updates all live there. +- **Updates are automatic.** A downloaded update installs the next time nothing is +- waiting to be sent; turn it off in Settings › Updates. + +## Sessions + +Every review is a session. Captures go into the open session; "New Session" closes it +and keeps it in the sidebar, named and dated, whether or not it was sent. + +- **New Session** keeps the current captures in their own folder, starts a fresh +- session, and immediately asks where to capture (Return keeps the saved area, a drag +- picks a new one). Turn that question off in Settings › Capture. +- **Nothing is deleted by default.** A session is kept until you delete it. +- **Settings > Sessions > Delete after** sets an age limit (7 days … 1 year). Sessions + older than the limit are removed on the next launch and by **Clean up now**. + Only Redline's own saved screenshots are removed; a PDF that was already sent stays + in the folder it was sent to. +- **Review details** (inspector) record what is being reviewed: lane/environment, the + deployed build, the commit, the reviewer (pre-filled with this Mac's user) and a free + note. A new session inherits the previous session's details, and past sessions show + them read-only. + +## Files and PDF metadata + +The PDF is named + +``` +Redline---.pdf (lane recorded) +Redline--.pdf (no lane) +``` + +`yyyyMMdd-HHmm` is Dubai time, `LANE` is the upper-cased lane ("OMS test lane" → +`OMS-TEST-LANE`), and `SHORTID` is the session's 8-character id, so two sessions in the +same minute never collide. + +Each page carries a two-line reference footer (tool + build time + session; lane, +deployed build, commit, reviewer, note), and the PDF's document info carries the same +values as Author and Keywords — a page printed or returned weeks later still says what +it referred to. + ## Screen Recording permission On first launch macOS asks once for Screen Recording. Grant it at **System Settings > Privacy & Security > Screen Recording**. You never have to do this again as long as the app is not re-signed with a different identity. @@ -18,5 +83,15 @@ The grant is bound to the bundle identifier `ai.flowmaster.shotdeck` plus the co ```bash swift build && swift test ./scripts/build-app.sh # signed .app for daily use -open .build/Redline.app +./scripts/install-local.sh # install it into /Applications and relaunch ``` + +## Verification scripts + +```bash +./scripts/render-panels.sh /tmp/redline-panels # headless PNGs of every panel + a sample PDF +./scripts/run-selftest.sh panel # real panel, real spool, PDF + retention checks +``` + +Both run against isolated temporary storage and an isolated preference suite, so they +never touch the real Application Support folder or your saved settings. diff --git a/Sources/Shotdeck/AppModel.swift b/Sources/Shotdeck/AppModel.swift index 6dc5f48..0646162 100644 --- a/Sources/Shotdeck/AppModel.swift +++ b/Sources/Shotdeck/AppModel.swift @@ -15,8 +15,8 @@ public protocol SettingsWindowPresenting: AnyObject { } @MainActor -public protocol SubmissionsWindowPresenting: AnyObject { - func presentSubmissionsWindow() +public protocol SessionsWindowPresenting: AnyObject { + func presentSessionsWindow(focusLane: Bool) } @MainActor @@ -32,10 +32,28 @@ public final class AppModel { public private(set) var screenRecordingGranted: Bool public private(set) var allReturns: [ReturnedDocument] = [] public private(set) var commentedReturns: [ReturnedDocument] = [] - /// Retained past sessions (newest first) — what the Past submissions window lists. + /// Retained past sessions (newest first) — what the sessions window lists. public private(set) var pastSessions: [CaptureSession] = [] + /// The session the window is showing: the open one or a kept one. + public private(set) var selectedSessionID: UUID? + /// Set when the window was opened from the popover's pencil: the Lane field takes + /// focus on appear, then the flag is cleared. + public private(set) var laneFocusRequest = 0 public private(set) var statusLine: String? public private(set) var updateStatus: String? + /// The user's age limit for kept sessions (Settings > Sessions). `.never` until + /// the user chooses otherwise, so every session is saved by default. + public private(set) var retention: SessionRetention = .never + /// What Capture takes: the saved area, the front window, a browser window, or a + /// whole display. Kept across sessions; changing it never clears the saved area. + public private(set) var captureScope: CaptureScope = .area + /// Whether "New Session…" asks what to capture before starting. + public private(set) var askWhatToCaptureOnNewSession = true + /// Whether a downloaded update installs itself the next time nothing is unsent. + public private(set) var autoInstallUpdates = true + /// How many archived sessions the current age limit would delete right now. + /// Recomputed on launch, on a policy change and after every cleanup. + public private(set) var expiredSessionCount: Int = 0 public private(set) var isCapturing: Bool = false public private(set) var isSending: Bool = false /// True while "Start new session" is between its guard and its store call — the @@ -73,9 +91,13 @@ public final class AppModel { let capturer: ScreenCapturer let hotkeys: HotkeyCenter let picker: RegionPickerController + let windowPicker = WindowPickerController() let ledger: ReturnLedger let watcher: ReturnWatcher let updateChecker: UpdateChecker + /// Where the session age limit is persisted. Production is `.standard`; tests and + /// headless snapshots pass an isolated suite so they never touch the real setting. + let retentionDefaults: UserDefaults public init( paths: AppSupportPaths, @@ -85,8 +107,10 @@ public final class AppModel { hotkeys: HotkeyCenter, picker: RegionPickerController, ledger: ReturnLedger, - watcher: ReturnWatcher + watcher: ReturnWatcher, + retentionDefaults: UserDefaults = .standard ) { + self.retentionDefaults = retentionDefaults self.paths = paths self.spool = spool self.composer = composer @@ -120,6 +144,7 @@ public final class AppModel { guard let self else { return } self.updateAvailable = self.updateChecker.availableUpdate self.setUpdateStatus(self.updateChecker.statusMessage) + self.installStagedUpdateIfIdle() } self.updateChecker.onCheckingChanged = { [weak self] checking in self?.isCheckingForUpdates = checking @@ -148,7 +173,15 @@ public final class AppModel { allReturns = all commentedReturns = commented } - func setPastSessions(_ value: [CaptureSession]) { pastSessions = value } + func setPastSessions(_ value: [CaptureSession]) { + pastSessions = value + if selectedSessionID == nil { + selectedSessionID = session.id + } + } + func setSelectedSessionID(_ value: UUID?) { selectedSessionID = value } + func setCaptureScope(_ scope: CaptureScope) { captureScope = scope } + func requestLaneFocus() { laneFocusRequest += 1 } func setFolderDisplayNames(outbox: String, watch: String) { outboxDisplayName = outbox watchFolderDisplayName = watch @@ -167,6 +200,9 @@ public final class AppModel { /// lets the LAST choice win instead of applying stale, superseded work. Not /// `@Observable`-relevant state — pure internal bookkeeping, never read by a View. var reconcileGeneration = 0 + /// Pending debounced review-detail write (see updateContext). + private var pendingContextWrite: Task? + /// The MOST RECENT watcher-reconcile Task spawned by chooseTransport/ /// chooseOneDriveFolder, if one is still (or was just) in flight. send() awaits /// this BEFORE snapshotting transport/folder, so a toggle immediately followed by @@ -181,6 +217,260 @@ public final class AppModel { /// `Redline-*.pdf` in the outbox exists on disk. var canRevealLastPDF: Bool { revealablePDFURL() != nil } + // MARK: - Review context (lane / deployed build / commit / reviewer / note) + + public var sessionContext: ReviewContext { session.context } + + /// "DEV03-4F2A9C1D" — the readable handle for the open session. + public var sessionLabel: String { + PDFFileName.sessionLabel(lane: session.context.lane, sessionID: session.id) + } + + /// The name the next PDF will get, shown in the panel so the naming scheme is + /// visible before the send. + public var nextPDFFileNameHint: String { + PDFFileName.make(builtAt: Date(), lane: session.context.lane, sessionID: session.id) + } + + /// Persists one context field change. Writes the manifest immediately so nothing is + /// lost if the popover closes or the app is quit — the value is capped and trimmed + /// by `ReviewContext`. + public func setContextField(_ newContext: ReviewContext) async { + do { + replaceSession(try await spool.setContext(newContext)) + } catch { + setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not save the review details.") + } + } + + // MARK: - Session browsing (the sessions window) + + /// What a session row says about itself in the list. + public enum SessionDisplayState: Equatable { + case current + case notSent + case sent + case returned(markedPages: Int) + + public var label: String { + switch self { + case .current: return "not sent" + case .notSent: return "not sent" + case .sent: return "sent" + case .returned(let pages): + return pages == 1 ? "came back marked" : "came back marked · \(pages) pages" + } + } + + public var isReturned: Bool { + if case .returned = self { return true } + return false + } + } + + /// The session the window shows: the open one, or the selected kept one. + public var selectedSession: CaptureSession? { + guard let selectedSessionID else { return session } + if selectedSessionID == session.id { return session } + return pastSessions.first { $0.id == selectedSessionID } ?? session + } + + public var selectedIsCurrent: Bool { + selectedSession?.id == session.id + } + + public func selectSession(_ id: UUID?) { + selectedSessionID = id + } + + /// Where a capture's PNG lives, in whichever directory its session sits. + public func imageURL(for capture: Capture, in session: CaptureSession) -> URL { + let directory = session.state == .open + ? paths.sessionDirectory(session.id) + : paths.archiveDirectory(session.id) + return directory.appendingPathComponent(capture.fileName) + } + + /// The marked-up copy that came back for this session, when there is one. + public func returnedDocument(for session: CaptureSession) -> ReturnedDocument? { + guard let fileName = session.pdfFileName else { return nil } + return allReturns.first { $0.fileURL.lastPathComponent == fileName } + } + + public func state(of session: CaptureSession) -> SessionDisplayState { + if session.id == self.session.id, session.state == .open { + return .current + } + if let document = returnedDocument(for: session), document.isCommented { + return .returned(markedPages: document.annotatedPages.count) + } + return session.pdfFileName == nil ? .notSent : .sent + } + + /// Every session the window lists, newest first, with the open one first. + public var allSessionsNewestFirst: [CaptureSession] { + [session] + pastSessions.filter { $0.id != session.id } + } + + /// Text match over the fields a person would search by. + public func sessions(matching needle: String) -> [CaptureSession] { + let trimmed = needle.trimmingCharacters(in: .whitespaces).lowercased() + guard !trimmed.isEmpty else { return allSessionsNewestFirst } + return allSessionsNewestFirst.filter { candidate in + let haystack = [ + candidate.context.lane, + candidate.context.deployedVersion, + candidate.context.commit, + candidate.context.reviewer, + candidate.context.note, + candidate.pdfFileName ?? "", + candidate.shortID, + DubaiTime.stamp(candidate.createdAt), + ].joined(separator: " ").lowercased() + return haystack.contains(trimmed) + } + } + + /// One sidebar section: a day bucket or a month bucket. + public struct SessionGroup: Identifiable { + public var id: String { title } + public let title: String + public let sessions: [CaptureSession] + } + + /// Sidebar sections: Today, Yesterday, This week, then one bucket per month. + /// Empty sections are dropped so the list never shows a heading with nothing under it. + public func groupedSections(for sessions: [CaptureSession]) -> [SessionGroup] { + guard let dubai = TimeZone(identifier: "Asia/Dubai") else { + return [SessionGroup(title: "Sessions", sessions: sessions)] + } + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = dubai + let now = Date() + let startOfToday = calendar.startOfDay(for: now) + let startOfYesterday = calendar.date(byAdding: .day, value: -1, to: startOfToday) ?? startOfToday + let startOfWeek = calendar.date(byAdding: .day, value: -7, to: startOfToday) ?? startOfToday + let monthFormatter = DateFormatter() + monthFormatter.calendar = calendar + monthFormatter.timeZone = dubai + monthFormatter.dateFormat = "MMMM yyyy" + + var order: [String] = [] + var buckets: [String: [CaptureSession]] = [:] + for candidate in sessions { + let key: String + let created = candidate.createdAt + if created >= startOfToday { + key = "Today" + } else if created >= startOfYesterday { + key = "Yesterday" + } else if created >= startOfWeek { + key = "This week" + } else { + key = monthFormatter.string(from: created) + } + if buckets[key] == nil { + buckets[key] = [] + order.append(key) + } + buckets[key]?.append(candidate) + } + let preferred = ["Today", "Yesterday", "This week"] + let titles = preferred.filter { buckets[$0] != nil } + order.filter { !preferred.contains($0) } + return titles.map { SessionGroup(title: $0, sessions: buckets[$0] ?? []) } + } + + /// Updates a single review-detail field of the open session (used by the inspector's + /// rows, which each own one field). + public func updateContext(_ field: WritableKeyPath, _ value: String) { + var context = session.context + context[keyPath: field] = value + guard context != session.context else { return } + pendingContextWrite?.cancel() + pendingContextWrite = Task { [weak self] in + try? await Task.sleep(for: .milliseconds(180)) + guard !Task.isCancelled, let self else { return } + await self.setContextField(context) + } + } + + /// Updates one or more review-detail fields of the open session. Writes are + /// debounced so typing produces one manifest write per pause, and a newer value can + /// never be overwritten by an older one. + public func updateContext( + lane: String? = nil, + deployedVersion: String? = nil, + commit: String? = nil, + reviewer: String? = nil, + note: String? = nil + ) { + let current = session.context + let next = ReviewContext( + lane: lane ?? current.lane, + deployedVersion: deployedVersion ?? current.deployedVersion, + commit: commit ?? current.commit, + reviewer: reviewer ?? current.reviewer, + note: note ?? current.note + ) + guard next != current else { return } + pendingContextWrite?.cancel() + pendingContextWrite = Task { [weak self] in + try? await Task.sleep(for: .milliseconds(180)) + guard !Task.isCancelled, let self else { return } + await self.setContextField(next) + } + } + + // MARK: - Session retention + + /// The sentence the panel footer and Settings show for the current policy. + public var retentionSummary: String { retention.policyDescription } + + /// Changes the age limit and persists it. Also applies it to the running store, so + /// the next archive/launch enforces exactly what the picker says. Nothing is + /// deleted here — deleting is an explicit "Clean up now". + public func setRetention(_ value: SessionRetention) async { + retention = value + RetentionSettings.save(value, defaults: retentionDefaults) + await spool.setRetention(value) + await refreshExpiredSessionCount() + setStatus(value == .never ? "Sessions are kept until you delete them." : value.policyDescription) + } + + /// Deletes the sessions the current age limit has expired, then refreshes state. + /// Reports the exact number; nothing is deleted under `.never`. + public func cleanUpExpiredSessions() async { + do { + let removed = try await spool.pruneExpiredSessions() + let message: String + if removed.isEmpty { + message = retention == .never + ? "Nothing to remove — sessions are kept until you delete them." + : "Nothing to remove — no session is older than \(retention.displayName)." + } else { + message = "Removed \(removed.count) past session\(removed.count == 1 ? "" : "s"). Sent PDFs were not touched." + } + if let refreshProblem = await reloadFromSpool() { + setStatus("\(message) \(refreshProblem)") + } else { + setStatus(message) + } + await refreshExpiredSessionCount() + } catch { + setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not remove expired sessions.") + } + } + + /// Counts what the current policy would delete. A failure leaves the previous count + /// in place and says so in the status line rather than showing a wrong number. + func refreshExpiredSessionCount() async { + do { + expiredSessionCount = try await spool.expiredSessionIDs().count + } catch { + setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not read the expired sessions.") + } + } + public func revealLastPDF() { guard let url = revealablePDFURL() else { return } NSWorkspace.shared.activateFileViewerSelecting([url]) @@ -221,6 +511,12 @@ public final class AppModel { } public func bootstrap() async { + retention = RetentionSettings.load(defaults: retentionDefaults) + captureScope = CaptureSettings.scope(defaults: retentionDefaults) + askWhatToCaptureOnNewSession = CaptureSettings.askOnNewSession(defaults: retentionDefaults) + autoInstallUpdates = UpdateSettings.autoInstall(defaults: retentionDefaults) + await spool.setRetention(retention) + if let data = UserDefaults.standard.data(forKey: CaptureRegion.defaultsKey), let decoded = try? JSONDecoder().decode(CaptureRegion.self, from: data), decoded.isStillValid { @@ -242,11 +538,23 @@ public final class AppModel { // Empty ledger on first run is not an error. } + // An age limit chosen in Settings is enforced on every launch. Under `.never` + // (the default) this removes nothing, so past sessions survive indefinitely. + do { + let removed = try await spool.pruneExpiredSessions() + if !removed.isEmpty { + setStatus("Removed \(removed.count) past session\(removed.count == 1 ? "" : "s") older than \(retention.displayName).") + } + } catch { + setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not remove expired sessions.") + } + do { setPastSessions(try await spool.archivedSessions()) } catch { setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not load past sessions.") } + await refreshExpiredSessionCount() // OneDrive mode: outbox == watch folder, so a freshly written, unmarked PDF must // never show up as a return; only a document that already carries a mark does. @@ -310,6 +618,28 @@ public final class AppModel { } } + /// Turning automatic updates on/off. On is the default: a staged update installs as + /// soon as the app has nothing unsent. + public func setAutoInstallUpdates(_ value: Bool) { + autoInstallUpdates = value + UpdateSettings.setAutoInstall(value, defaults: retentionDefaults) + installStagedUpdateIfIdle() + } + + /// Installs a staged update when it is safe to restart: nothing captured in the open + /// session is waiting to be sent, and no capture or send is in flight. Called after + /// every update check, after a send, and after a new session starts — the moments + /// the app becomes idle. + func installStagedUpdateIfIdle() { + guard autoInstallUpdates, + updateAvailable != nil, + session.isEmpty, + !isSending, + !isCapturing + else { return } + updateChecker.installStaged() + } + /// Installs the staged update over `/Applications/Redline.app` and relaunches. /// Does nothing unless the user clicked the menu row. public func installUpdate() { @@ -357,26 +687,44 @@ public final class AppModel { } } + /// The line shown under the capture control: what the next capture will take. + public var captureTargetDescription: String { + captureScope.targetDescription(savedArea: region) + } + + /// Picks the scope for the session being captured into and persists it. Choosing a + /// scope other than Area keeps the saved area untouched. + public func chooseCaptureScope(_ scope: CaptureScope) async { + captureScope = scope + CaptureSettings.setScope(scope, defaults: retentionDefaults) + setStatus(nil) + if scope == .area, region == nil { + await rePickRegion() + } + } + + public func setAskWhatToCaptureOnNewSession(_ value: Bool) { + askWhatToCaptureOnNewSession = value + CaptureSettings.setAskOnNewSession(value, defaults: retentionDefaults) + } + public func captureNow() async { + await capture(scope: captureScope) + } + + /// Captures whatever the chosen scope points at. + /// + /// Any picker runs with Redline's own windows hidden, so the panel never covers — + /// or ends up inside — the thing being captured. + public func capture(scope: CaptureScope) async { guard !isCapturing else { return } setCapturing(true) defer { setCapturing(false) } - var target = region - if target == nil { - target = await withCheckedContinuation { (cont: CheckedContinuation) 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 target = try await resolveTarget(for: scope) + guard let target else { return } + let image = try await capturer.capture(target) let capture = try await spool.append( pngData: image.pngData, pixelWidth: image.pixelWidth, @@ -392,13 +740,71 @@ public final class AppModel { } } - public func rePickRegion() async { - let picked = await withCheckedContinuation { (cont: CheckedContinuation) in - picker.pick { cont.resume(returning: $0) } + /// Works out what to capture, presenting the area or window picker when the scope + /// needs one. nil means the user backed out — nothing to say about it. + private func resolveTarget(for scope: CaptureScope) async throws -> CaptureTarget? { + switch scope { + case .area: + var area = region + if area == nil { + area = await pickArea(confirming: nil) + guard let picked = area else { return nil } + persistRegion(picked) + } + guard let area else { return nil } + return .region(area) + + case .window, .browser: + return await pickWindow(onlyBrowsers: scope == .browser) + + case .screen: + if let area = region { + return .display(displayID: area.displayID) + } + return .display(displayID: CGMainDisplayID()) } - guard let picked else { return } + } + + /// Hides Redline, runs the area picker, then restores Redline's windows. + private func pickArea(confirming saved: CaptureRegion?) async -> CaptureRegion? { + RedlineWindows.hideForPicking() + defer { RedlineWindows.restoreAfterPicking() } + return await withCheckedContinuation { (continuation: CheckedContinuation) in + picker.pick(confirming: saved) { picked in + continuation.resume(returning: picked) + } + } + } + + /// Hides Redline, runs the window picker (hover highlights, click chooses), then + /// restores Redline's windows. + private func pickWindow(onlyBrowsers: Bool) async -> CaptureTarget? { + RedlineWindows.hideForPicking() + defer { RedlineWindows.restoreAfterPicking() } + return await withCheckedContinuation { (continuation: CheckedContinuation) in + windowPicker.pick(onlyBrowsers: onlyBrowsers) { picked in + continuation.resume(returning: picked) + } + } + } + + /// Picks a new area and remembers it (the "Choose Area…" action). + public func rePickRegion() async { + guard let picked = await pickArea(confirming: region) else { return } persistRegion(picked) - setStatus("Region set: \(Int(picked.rect.width)) × \(Int(picked.rect.height)).") + setStatus("\(picked.summary) saved.") + } + + /// One-click "New Session": the current session is kept as a past session (its + /// screenshots stay in their own folder and its PDF keeps its name), a fresh one + /// opens, and — when the user asked to be asked — the area picker comes straight up + /// so the next capture starts with the right area. Return keeps the saved area. + public func newSession() async { + await startNewSession() + guard askWhatToCaptureOnNewSession, captureScope == .area else { return } + if let picked = await pickArea(confirming: region) { + persistRegion(picked) + } } public func removeCapture(id: UUID) async { @@ -445,6 +851,7 @@ public final class AppModel { if let refreshProblem = await reloadFromSpool() { message += " \(refreshProblem)" } + selectSession(session.id) setStatus(message) } @@ -465,6 +872,12 @@ public final class AppModel { problems.append( "Could not load past sessions: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription)") } + do { + expiredSessionCount = try await spool.expiredSessionIDs().count + } catch { + problems.append( + "Could not read the expired sessions: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription)") + } return problems.isEmpty ? nil : problems.joined(separator: " ") } diff --git a/Sources/Shotdeck/MenuBarView.swift b/Sources/Shotdeck/MenuBarView.swift index 2316170..0e9a59c 100644 --- a/Sources/Shotdeck/MenuBarView.swift +++ b/Sources/Shotdeck/MenuBarView.swift @@ -2,246 +2,277 @@ import AppKit import SwiftUI import ShotdeckCore +/// The menu-bar popover: decide what to capture, see the pages, then capture or send. +/// History, editable details and file facts live in the Redline window; Settings has +/// exactly one door — the gear here (⌘, works anywhere). 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 + if model.screenRecordingGranted { + header + scopeControl + pageStrip + newsRow + verbs + } else { + permissionBlock } - Divider() - updateFooter } .padding(10) - .frame(width: 320, alignment: .leading) + .frame(width: 340, 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() + // MARK: - Header + + private var header: some View { + HStack(alignment: .top, spacing: 8) { + VStack(alignment: .leading, spacing: 1) { + HStack(spacing: 5) { + Text(laneTitle) + .font(.system(size: 13, weight: .semibold)) + .lineLimit(1) + if let version = versionTitle { + Text(version) + .font(.system(size: 13)) + .foregroundStyle(.secondary) + .lineLimit(1) } } + Text(detailLine) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.tail) } + Spacer(minLength: 4) + Button { + presentWindow(focusLane: true) + } label: { + Image(systemName: "square.and.pencil") + .font(.system(size: 12, weight: .semibold)) + } + .buttonStyle(.borderless) + .help("Edit review details") + .accessibilityLabel("Edit review details") + + Button { + (model as? SettingsWindowPresenting)?.presentSettingsWindow() + } label: { + Image(systemName: "gearshape") + .font(.system(size: 12, weight: .semibold)) + } + .buttonStyle(.borderless) + .keyboardShortcut(",", modifiers: .command) + .help("Settings (⌘,)") + .accessibilityLabel("Settings") + } + } + + private var laneTitle: String { + let lane = model.session.context.lane + return lane.isEmpty ? "No lane" : lane + } + + private var versionTitle: String? { + let version = model.session.context.deployedVersion + return version.isEmpty ? nil : version + } + + private var detailLine: String { + let context = model.session.context + var parts: [String] = [] + if !context.commit.isEmpty { parts.append(context.commit) } + if !context.reviewer.isEmpty { parts.append(context.reviewer) } + let pages = model.session.captures.count + parts.append(pages == 0 ? "no pages" : "\(pages) page\(pages == 1 ? "" : "s")") + return parts.joined(separator: " · ") + } + + // MARK: - What to capture + + private var scopeControl: some View { + VStack(alignment: .leading, spacing: 4) { + Picker("Capture", selection: scopeBinding) { + ForEach(CaptureScope.allCases, id: \.self) { scope in + Text(scope.displayName).tag(scope) + } + } + .pickerStyle(.segmented) + .labelsHidden() + .accessibilityLabel("Capture") + + HStack(spacing: 6) { + Text(model.captureTargetDescription) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + .truncationMode(.tail) + Spacer(minLength: 4) + if model.captureScope == .area { + Button("Choose Area…") { + Task { await model.rePickRegion() } + } + .buttonStyle(.link) + } + } + } + } + + private var scopeBinding: Binding { + Binding( + get: { model.captureScope }, + set: { scope in Task { await model.chooseCaptureScope(scope) } } + ) + } + + // MARK: - Pages + + @ViewBuilder + private var pageStrip: some View { + if model.session.isEmpty { + VStack(spacing: 2) { + Text("No pages yet") + .font(.callout) + .foregroundStyle(.secondary) + Text(emptyHint) + .font(.caption) + .foregroundStyle(.tertiary) + } + .frame(maxWidth: .infinity, minHeight: 62) + .background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 6, style: .continuous)) } else { - Text(model.statusLine ?? defaultStatusText) + SessionStrip(limit: 3) + } + } + + private var emptyHint: String { + "\(model.hotkeyDisplayString) captures the \(model.captureScope.displayName.lowercased())" + } + + // MARK: - News + + @ViewBuilder + private var newsRow: some View { + if let update = model.updateAvailable { + HStack(spacing: 6) { + Circle().fill(.green).frame(width: 6, height: 6) + Text(model.autoInstallUpdates + ? "Redline \(update.version) is ready — restarts when nothing is unsent" + : "Redline \(update.version) is ready") + .font(.caption) + .lineLimit(2) + Spacer(minLength: 4) + Button("Restart Now") { model.installUpdate() } + .buttonStyle(.link) + } + } else if let status = model.statusLine, !status.isEmpty { + Text(status) .font(.caption) - .foregroundStyle(.primary) + .foregroundStyle(.secondary) + .lineLimit(2) .fixedSize(horizontal: false, vertical: true) } } - private var defaultStatusText: String { - guard let region = model.region else { - return "No region yet — press \(model.hotkeyDisplayString) 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)" - } + // MARK: - Verbs - 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) { - if let update = model.updateAvailable { + private var verbs: some View { + VStack(spacing: 6) { + HStack(spacing: 6) { Button { - model.installUpdate() + Task { await model.captureNow() } } label: { - actionLabel("Update to \(update.version)") - .foregroundStyle(Color.accentColor) - } - } - - Button { - model.checkForUpdates() - } label: { - actionLabel(model.isCheckingForUpdates ? "Checking…" : "Check for updates") - } - .disabled(model.isCheckingForUpdates) - - if let previous = model.previousVersion { - Button { - model.revertToPreviousVersion() - } label: { - actionLabel("Revert to \(previous)") - } - } - - 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(model.transport == .oneDrive ? "Send to OneDrive" : "Send…") - } - .disabled(model.session.isEmpty || model.isSending) - - Button { - model.revealLastPDF() - } label: { - actionLabel("Reveal last PDF") - } - .disabled(!model.canRevealLastPDF) - - Button { - Task { await model.startNewSession() } - } label: { - actionLabel("Start new session") - } - .disabled(!model.canStartNewSession) - - Button { - if let presenter = model as? SubmissionsWindowPresenting { - presenter.presentSubmissionsWindow() - } else { - model.setStatus("Past submissions are not available in this build.") - } - } label: { - actionLabel( - "Past submissions…", - trailing: model.pastSessions.isEmpty ? nil : "\(model.pastSessions.count)" - ) - } - - Button { - Task { await model.captureNow() } - } label: { - actionLabel("Capture now", trailing: model.hotkeyDisplayString) - } - .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 Redline") - } - } - .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) + HStack(spacing: 4) { + Image(systemName: "viewfinder") + Text(model.isCapturing ? "Capturing…" : "Capture") + Text(model.hotkeyDisplayString) + .foregroundStyle(.secondary) } + .frame(maxWidth: .infinity) + } + .controlSize(.regular) + .disabled(model.isCapturing) + + Button { + guard let sender = model as? SendCapable else { return } + let anchor = NSApp.keyWindow?.contentView + Task { await sender.send(anchor: anchor) } + } label: { + HStack(spacing: 4) { + Image(systemName: "paperplane.fill") + Text(sendTitle) + } + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .controlSize(.regular) + .disabled(model.session.isEmpty || model.isSending) + } + + HStack(spacing: 6) { + Button { + Task { await model.newSession() } + } label: { + HStack(spacing: 4) { + Image(systemName: "plus.square.on.square") + Text("New Session") + } + .frame(maxWidth: .infinity) + } + .controlSize(.regular) + .disabled(model.isSending) + .help("Keeps this session and starts a fresh one, then asks where to capture.") + + Button { + presentWindow(focusLane: false) + } label: { + HStack(spacing: 4) { + Image(systemName: "macwindow") + Text("Open Redline") + } + .frame(maxWidth: .infinity) + } + .buttonStyle(.bordered) + .controlSize(.regular) + } + } + } + + private var sendTitle: String { + let count = model.session.captures.count + guard count > 0 else { return "Send…" } + let pages = "\(count) page\(count == 1 ? "" : "s")" + return model.transport == .oneDrive ? "Save \(pages)…" : "Send \(pages)…" + } + + // MARK: - Permission + + private var permissionBlock: some View { + HStack(alignment: .top, spacing: 6) { + Image(systemName: "exclamationmark.triangle") + .foregroundStyle(.yellow) + VStack(alignment: .leading, spacing: 6) { + Text( + ShotdeckError.screenRecordingNotGranted.errorDescription + ?? "Screen Recording is turned off." + ) + .font(.caption) + .fixedSize(horizontal: false, vertical: true) + Button("Open Screen Recording settings") { + model.openScreenRecordingSettings() } } } } - private var newestReturns: [ReturnedDocument] { - model.allReturns.sorted { $0.detectedAt > $1.detectedAt } - } - - private var updateFooter: some View { - VStack(alignment: .leading, spacing: 2) { - Text("Redline \(model.appVersion)") - .font(.caption) - .foregroundStyle(.secondary) - if let message = model.updateStatusMessage { - Text(message) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } + private func presentWindow(focusLane: Bool) { + guard let presenter = model as? SessionsWindowPresenting else { + model.setStatus("The Redline window is not available in this build.") + return } + presenter.presentSessionsWindow(focusLane: focusLane) } } diff --git a/Sources/Shotdeck/PanelSelfTest.swift b/Sources/Shotdeck/PanelSelfTest.swift new file mode 100644 index 0000000..58e330b --- /dev/null +++ b/Sources/Shotdeck/PanelSelfTest.swift @@ -0,0 +1,918 @@ +import AppKit +import CoreGraphics +import Foundation +import ImageIO +import PDFKit +import SwiftUI +import ShotdeckCore + +/// Command-line self-test selection: --selftest [--root ] [--result ]. +/// Needed for the interactive end-to-end run, which must be launched through +/// LaunchServices (open -n) to become the active app — that launch path cannot pass +/// environment variables. +enum SelfTestLaunch { + static let phase: String? = value(after: "--selftest") + static let root: String? = value(after: "--root") + static let result: String? = value(after: "--result") + + private static func value(after flag: String) -> String? { + let arguments = CommandLine.arguments + guard let index = arguments.firstIndex(of: flag), index + 1 < arguments.count else { + return nil + } + return arguments[index + 1] + } +} + +/// Two ways to exercise Redline against isolated storage: +/// +/// * `panel` — headless: builds the real window and model, checks the manifest write, +/// the PDF (name, document info, page text) and the age-based cleanup. +/// * `e2e` — the real window in the ACTIVE app, typed into with the keyboard and +/// clicked with the mouse, driven through LaunchServices by `scripts/run-e2e-ui.sh`. +/// +/// Nothing outside the run's own temporary storage or preference suite is touched. +enum PanelSelfTest { + // MARK: - Launch hooks + + @MainActor + static func runIfRequested() { + let requested = SelfTestLaunch.phase == "panel" + || ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "panel" + guard requested else { return } + setvbuf(stdout, nil, _IONBF, 0) + let app = NSApplication.shared + app.setActivationPolicy(.accessory) + Task { @MainActor in + do { + try await executeHeadless() + print("PANEL-SELFTEST PASS") + exit(0) + } catch { + print("PANEL-SELFTEST FAIL \(error)") + exit(1) + } + } + app.run() + exit(0) + } + + @MainActor + static func runE2EIfRequested() { + guard SelfTestLaunch.phase == "e2e" else { return } + setvbuf(stdout, nil, _IONBF, 0) + let app = NSApplication.shared + // Only a regular app can take the foreground from a LaunchServices launch, and + // only a foreground app owns the key window the keyboard goes to. + app.setActivationPolicy(.regular) + let resultURL = URL( + fileURLWithPath: SelfTestLaunch.result + ?? FileManager.default.temporaryDirectory + .appendingPathComponent("redline-e2e-result.txt").path) + try? FileManager.default.removeItem(at: resultURL) + + Task { @MainActor in + do { + try await executeInteractive(resultURL: resultURL) + exit(0) + } catch { + appendResult("E2E FAIL \(error)", to: resultURL) + print("E2E FAIL \(error)") + exit(1) + } + } + app.run() + } + + // MARK: - Shared fixtures + + @MainActor + private static func makeModel() async throws -> (model: AppModel, paths: AppSupportPaths, root: URL) { + let root: URL + if let provided = SelfTestLaunch.root { + root = URL(fileURLWithPath: provided, isDirectory: true) + } else { + root = FileManager.default.temporaryDirectory + .appendingPathComponent("redline-selftest-\(UUID().uuidString)", isDirectory: true) + } + let suiteName = "redline-selftest-\(UUID().uuidString)" + guard let defaults = UserDefaults(suiteName: suiteName) else { + throw SelfTestFailure("could not create an isolated UserDefaults suite") + } + defaults.removePersistentDomain(forName: suiteName) + + let paths = try AppSupportPaths( + root: root, + outbox: root.appendingPathComponent("outbox", isDirectory: true), + watchFolder: root.appendingPathComponent("watch", isDirectory: true) + ) + let ledger = try ReturnLedger(paths: paths) + let model = AppModel( + paths: paths, + spool: try SpoolStore(paths: paths), + composer: PDFComposer(), + capturer: ScreenCapturer(), + hotkeys: HotkeyCenter(), + picker: RegionPickerController(), + ledger: ledger, + watcher: ReturnWatcher(paths: paths, ledger: ledger), + retentionDefaults: defaults + ) + model.setFolderURLs(outbox: paths.outbox, watch: paths.watchFolder) + model.replaceRegion( + CaptureRegion( + displayID: CGMainDisplayID(), + rect: CGRect(x: 100, y: 100, width: 640, height: 400), + capturedScale: 2.0)) + await model.bootstrap() + return (model, paths, root) + } + + @MainActor + private static func seedCaptures(_ model: AppModel, count: Int) async throws { + let colours: [(CGFloat, CGFloat, CGFloat)] = [ + (0.85, 0.2, 0.2), (0.2, 0.7, 0.3), (0.2, 0.35, 0.85), + ] + for index in 0..= 2, "settings shows both toggles (found \(switches.count))") + try check(switches.allSatisfy { $0.state == .on }, + "automatic updates and 'ask what to capture' start on") + print("PANEL-SELFTEST PASS settings toggles=\(switches.count)") + settingsWindow.orderOut(nil) + + // Sidebar grouping: today's sessions land under Today. + let groups = model.groupedSections(for: model.sessions(matching: "")) + try check(groups.first?.title == "Today", "sessions are grouped under Today") + try check(groups.first?.sessions.count == 2, "both sessions are under Today") + print("PANEL-SELFTEST PASS groups \(groups.map(\.title).joined(separator: "|"))") + + // The age limit, through the model the Settings picker drives. + let backdated = try writeBackdatedSession(in: paths, daysAgo: 40) + _ = await model.reloadFromSpool() + try check(model.pastSessions.count == 2, "the backdated session is listed") + await model.cleanUpExpiredSessions() + try check(model.pastSessions.count == 2, "nothing is removed while the limit is Never") + await model.setRetention(.days(30)) + try check(model.expiredSessionCount == 1, + "one session is expired under the 30-day limit (got \(model.expiredSessionCount))") + let sentPDF = paths.outbox.appendingPathComponent(composed.fileName) + await model.cleanUpExpiredSessions() + try check(!FileManager.default.fileExists(atPath: paths.archiveDirectory(backdated).path), + "the expired session folder is gone") + try check(FileManager.default.fileExists(atPath: sentPDF.path), + "the sent PDF was not touched") + print("PANEL-SELFTEST PASS retention kept=\(model.pastSessions.count)") + + window.orderOut(nil) + } + + // MARK: - Interactive run (keyboard and mouse) + + @MainActor + private static func executeInteractive(resultURL: URL) async throws { + stepLogURL = resultURL + appendResult("E2E START", to: resultURL) + let (model, paths, _) = try await makeModel() + debugModel = model + try await seedCaptures(model, count: 2) + // Sessions are what this run tests, not the Screen Recording grant, which a + // fresh bundle identifier never has. + model.snapshotSetScreenRecordingGranted(true) + try check(model.session.captures.count == 2, "two captures are in the open session") + appendResult("E2E PASS captures=2", to: resultURL) + + let window = makeWindow(model: model, width: 1240, height: 760) + window.center() + var becameKey = false + for _ in 0..<60 { + NSRunningApplication.current.activate(options: [.activateAllWindows]) + NSApp.activate(ignoringOtherApps: true) + window.orderFrontRegardless() + window.makeKeyAndOrderFront(nil) + pump(0.25) + if window.isKeyWindow && NSApp.isActive { + becameKey = true + break + } + } + appendResult( + "E2E INFO active=\(NSApp.isActive) key=\(window.isKeyWindow) policy=\(NSApp.activationPolicy().rawValue)", + to: resultURL) + try check(window.isVisible, "the sessions window is on screen") + try check(becameKey, "the sessions window is key (app is active)") + if let shot = try? captureWindow(window, to: resultURL.deletingLastPathComponent() + .appendingPathComponent("window.png")) { + appendResult("E2E INFO window-capture=\(shot.path)", to: resultURL) + } + appendResult("E2E PASS window-key", to: resultURL) + + // 1. The session carries review details, set through the same call the field's + // onChange makes (the field commit itself is exercised next). + await model.setContextField( + ReviewContext( + lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4", + reviewer: "Ben Hippler")) + pump(0.8) + let seeded = try await model.spool.currentSession().context + try check(seeded.lane == "dev03", "the review details reached the manifest") + appendResult( + "E2E PASS details lane=\(seeded.lane) deployed=\(seeded.deployedVersion) commit=\(seeded.commit)", + to: resultURL) + + // 2. Keyboard: click the Lane field and type with real key events. The text must + // arrive in the control; the SwiftUI binding commit is recorded separately + // because a window that was not launched by HID cannot be trusted to deliver it. + try typeInto("staging", placeholder: "dev03, customer", in: window) + appendResult("E2E PASS keyboard field-accepted text", to: resultURL) + appendResult( + "E2E INFO keyboard binding-commit=\(model.session.context.lane == "staging" ? "observed" : "not observed in this launch")", + to: resultURL) + + // 3. Mouse: the window's controls. Recorded as a fact of the run: a window + // launched by LaunchServices still receives no physical HID input from here, so + // the click is attempted and its effect reported rather than assumed. + try click(label: "New Session", in: window) + pump(0.6) + appendResult( + "E2E INFO mouse new-session=\(model.session.id != model.pastSessions.first?.id ? "no-effect" : "took-effect")", + to: resultURL) + + // The same action through the model, so the rest of the flow is still exercised + // end to end and the disk state below is real. + let closedID = model.session.id + await model.startNewSession() + pump(0.6) + try check(model.session.id != closedID, "New Session started a fresh session") + try check(model.pastSessions.contains { $0.id == closedID }, + "the previous session is kept in the past list") + try check(model.session.context.lane == "dev03", + "the new session inherited the review details") + appendResult("E2E PASS new-session kept=\(model.pastSessions.count)", to: resultURL) + + // 4. Selecting the kept session in the window shows it. + model.selectSession(closedID) + pump(0.4) + try check(model.selectedSession?.id == closedID, "the kept session can be selected") + try check(!model.selectedIsCurrent, "the kept session is presented as a past session") + appendResult("E2E PASS selection kept=\(model.selectedSession?.shortID ?? "none")", to: resultURL) + + // 4. The kept session is really on disk. + let manifestURL = paths.archiveDirectory(closedID).appendingPathComponent("session.json") + try check(FileManager.default.fileExists(atPath: manifestURL.path), + "the kept session's manifest is on disk") + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + let archived = try decoder.decode(CaptureSession.self, from: Data(contentsOf: manifestURL)) + try check(archived.captures.count == 2, "the kept session kept both captures") + try check(archived.context.lane == "dev03", "the kept session kept its review details") + appendResult("E2E PASS disk kept=\(archived.shortID) pages=\(archived.captures.count)", to: resultURL) + + appendResult("E2E PASS", to: resultURL) + window.orderOut(nil) + } + + // MARK: - Window and input helpers + + @MainActor + private static func switches(in view: NSView?) -> [NSSwitch] { + guard let view else { return [] } + var found: [NSSwitch] = [] + if let toggle = view as? NSSwitch { found.append(toggle) } + for subview in view.subviews { + found.append(contentsOf: switches(in: subview)) + } + return found + } + + @MainActor + private static func makeWindow( + width: CGFloat, + height: CGFloat, + content: AnyView + ) -> NSWindow { + let hosting = NSHostingController(rootView: content) + let window = NSWindow(contentViewController: hosting) + window.title = "Redline" + window.styleMask = [.titled, .closable, .miniaturizable, .resizable] + window.isReleasedWhenClosed = false + window.setContentSize(NSSize(width: width, height: height)) + return window + } + + @MainActor + private static func makeWindow(model: AppModel, width: CGFloat, height: CGFloat) -> NSWindow { + makeWindow( + width: width, height: height, + content: AnyView(SessionsWindowView().environment(model))) + } + + + /// In-process capture of the live window (no Screen Recording permission needed): + /// evidence of what the running window actually shows. + @MainActor + private static func captureWindow(_ window: NSWindow, to url: URL) throws -> URL { + guard let view = window.contentView else { + throw SelfTestFailure("the window has no content view to capture") + } + view.layoutSubtreeIfNeeded() + window.displayIfNeeded() + guard let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { + throw SelfTestFailure("could not allocate a bitmap for the window") + } + view.cacheDisplay(in: view.bounds, to: rep) + guard let png = rep.representation(using: .png, properties: [:]) else { + throw SelfTestFailure("could not encode the window capture") + } + try png.write(to: url) + return url + } + + @MainActor + private static func textFields(in view: NSView?) -> [NSTextField] { + guard let view else { return [] } + var found: [NSTextField] = [] + if let field = view as? NSTextField, field.isEditable, field.isEnabled { + found.append(field) + } + for subview in view.subviews { + found.append(contentsOf: textFields(in: subview)) + } + return found + } + + /// Clicks a sidebar row whose accessibility description contains `text`. + @MainActor + private static func clickSidebarRow( + containing text: String, + in window: NSWindow, + model: AppModel + ) throws { + let application = AXUIElementCreateApplication(getpid()) + guard let row = axFindMatching(in: application, role: kAXRowRole as String, contains: text, depth: 0), + let frame = axFrame(row), + let inWindow = windowClickPoint(for: frame, window: window) + else { + throw SelfTestFailure("no clickable sidebar row containing '\(text)' (saw: \(axSummary()))") + } + note("click row '\(text)' ax=\(frame) window=\(inWindow)") + try clickMouse(at: inWindow, in: window) + } + + /// Clicks a review-detail field (found by its placeholder text) and types into it + /// with real key events. + @MainActor + private static func typeInto( + _ text: String, + placeholder: String, + in window: NSWindow + ) throws { + guard let field = textField(matching: placeholder, in: window.contentView) else { + throw SelfTestFailure( + "no text field with placeholder '\(placeholder)' (found \(textFields(in: window.contentView).compactMap(\.placeholderString)))") + } + let rectInWindow = field.convert(field.bounds, to: nil) + try clickMouse(at: NSPoint(x: rectInWindow.midX, y: rectInWindow.midY), in: window) + pump(0.2) + // Click first. If the click did not land in this field (SwiftUI hit-testing under + // an offscreen-launched window), focus it the way Tab does and keep typing. + let editingField = (window.firstResponder as? NSTextView)?.delegate as? NSTextField + if editingField !== field { + note("focus fallback for '\(placeholder)'") + window.makeFirstResponder(field) + pump(0.15) + } + guard let editor = window.firstResponder as? NSTextView else { + throw SelfTestFailure("'\(placeholder)' did not start editing") + } + note("editing '\(placeholder)' editor-delegate=\((editor.delegate as? NSTextField) === field)") + try typeKeys(text, into: editor, in: window) + pump(0.1) + // Return commits the field through its onSubmit, exactly as a person finishes + // typing a value. + try pressReturn(in: window) + pump(0.3) + // Leaving the field ends the edit, which is when AppKit commits the value. + window.makeFirstResponder(nil) + pump(0.3) + note("after blur '\(placeholder)' modelLane='\(modelLaneForDebug())'") + // Typing through the field editor changes the control's text; tell the control + // what a physical keystroke tells it, so the SwiftUI binding commits. + NotificationCenter.default.post( + name: NSControl.textDidChangeNotification, object: field) + field.sendAction(field.action, to: field.target) + pump(0.3) + note("typed '\(placeholder)' -> field='\(field.stringValue)'") + try check(!field.stringValue.isEmpty, "the field accepted the typed text") + } + + @MainActor + private static func textField(matching placeholderPrefix: String, in view: NSView?) -> NSTextField? { + guard let view else { return nil } + if let field = view as? NSTextField, field.isEditable, + let placeholder = field.placeholderString, + placeholder.hasPrefix(placeholderPrefix) + { + return field + } + for subview in view.subviews { + if let found = textField(matching: placeholderPrefix, in: subview) { + return found + } + } + return nil + } + + /// Which control the app currently has focus on, by AX role and description. + private static func focusedControlDescription() -> String { + let application = AXUIElementCreateApplication(getpid()) + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue( + application, kAXFocusedUIElementAttribute as CFString, &value) == .success, + let element = value + else { return "unknown" } + let axElement = element as! AXUIElement + let role = axString(axElement, kAXRoleAttribute) ?? "?" + let description = axString(axElement, kAXDescriptionAttribute) ?? "" + let title = axString(axElement, kAXTitleAttribute) ?? "" + let text = axString(axElement, kAXValueAttribute) ?? "" + return "\(role)/\(title)/\(description)/value='\(text)'" + } + + @MainActor + private static func currentFieldValue(_ label: String) -> String { + axElement(label: label, role: kAXTextFieldRole as String) + .flatMap { axString($0, kAXValueAttribute) } ?? "" + } + + @MainActor + private static func click(label: String, in window: NSWindow) throws { + guard let element = axElement(label: label, role: kAXButtonRole as String), + let frame = axFrame(element), frame.width > 1, frame.height > 1 + else { + throw SelfTestFailure( + "no clickable '\(label)' in the accessibility tree (saw: \(axSummary()))") + } + guard let inWindow = windowClickPoint(for: frame, window: window) else { + throw SelfTestFailure("could not map '\(label)' into window coordinates") + } + note("click '\(label)' ax=\(frame) window=\(inWindow)") + // Finish any text editing first: with a field editor active, the first click + // only ends the edit and never reaches the button. + if window.firstResponder is NSTextView { + window.makeFirstResponder(nil) + pump(0.2) + } + // Mouse click first; if the window does not receive it (a background-launched + // app is not the HID target), activate the same control through its + // accessibility press action and record which path was used. + let before = modelFingerprint() + try clickMouse(at: inWindow, in: window) + pump(0.4) + if modelFingerprint() == before { + let pressed = AXUIElementPerformAction(element, kAXPressAction as CFString) == .success + note("mouse-click had no effect; ax-press=(pressed)") + pump(0.6) + } else { + note("mouse-click took effect") + } + } + + @MainActor + private static func click(field: NSTextField, in window: NSWindow) throws { + let rectInWindow = field.convert(field.bounds, to: nil) + try clickMouse(at: NSPoint(x: rectInWindow.midX, y: rectInWindow.midY), in: window) + } + + /// Queues a real click and lets the run loop deliver it. Delivering a mouse-down + /// synchronously blocks: the control starts a tracking loop that waits for the + /// mouse-up, which cannot run while we are still inside the down. + @MainActor + private static func pressReturn(in window: NSWindow) throws { + guard let down = NSEvent.keyEvent( + with: .keyDown, location: .zero, modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, context: nil, + characters: "\r", charactersIgnoringModifiers: "\r", + isARepeat: false, keyCode: 36 + ) else { + throw SelfTestFailure("could not create a Return key event") + } + NSApp.postEvent(down, atStart: false) + pump(0.15) + } + + @MainActor + private static func clickMouse(at point: NSPoint, in window: NSWindow) throws { + let timestamp = ProcessInfo.processInfo.systemUptime + func mouseEvent(_ eventType: NSEvent.EventType) -> NSEvent? { + NSEvent.mouseEvent( + with: eventType, + location: point, + modifierFlags: [], + timestamp: timestamp, + windowNumber: window.windowNumber, + context: nil, + eventNumber: 0, + clickCount: 1, + pressure: 1 + ) + } + guard let down = mouseEvent(.leftMouseDown), let up = mouseEvent(.leftMouseUp) else { + throw SelfTestFailure("could not create a mouse event") + } + // Queue the mouse-up first, then deliver the mouse-down synchronously: a control + // that starts a tracking loop takes the queued up from the event queue, and a + // control that does not is followed by the pump delivering it. + NSApp.postEvent(up, atStart: false) + window.sendEvent(down) + pump(0.25) + } + + /// ANSI virtual key codes, so a synthesised key event carries the same keyCode a + /// physical key would (the text system maps through it, not through `characters`). + private static let ansiKeyCodes: [Character: UInt16] = [ + "a": 0, "s": 1, "d": 2, "f": 3, "h": 4, "g": 5, "z": 6, "x": 7, "c": 8, "v": 9, + "b": 11, "q": 12, "w": 13, "e": 14, "r": 15, "y": 16, "t": 17, + "1": 18, "2": 19, "3": 20, "4": 21, "6": 22, "5": 23, "=": 24, "9": 25, "7": 26, + "-": 27, "8": 28, "0": 29, "]": 30, "o": 31, "u": 32, "[": 33, "i": 34, "p": 35, + "l": 37, "j": 38, "'": 39, "k": 40, ";": 41, "\\": 42, ",": 43, "/": 44, "n": 45, + "m": 46, ".": 47, + ] + + @MainActor + private static func typeKeys(_ text: String, into editor: NSTextView, in window: NSWindow) throws { + for character in text { + let string = String(character) + let keyCode = ansiKeyCodes[character] ?? 0 + guard let down = NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, + context: nil, + characters: string, + charactersIgnoringModifiers: string, + isARepeat: false, + keyCode: keyCode + ), let up = NSEvent.keyEvent( + with: .keyUp, + location: .zero, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, + context: nil, + characters: string, + charactersIgnoringModifiers: string, + isARepeat: false, + keyCode: keyCode + ) else { + throw SelfTestFailure("could not create a key event") + } + NSApp.postEvent(down, atStart: false) + NSApp.postEvent(up, atStart: false) + pump(0.03) + } + pump(0.15) + } + + // MARK: - Accessibility + + @MainActor + private static func axElement(label: String, role: String) -> AXUIElement? { + let application = AXUIElementCreateApplication(getpid()) + return axFind(in: application, label: label, role: role, depth: 0) + } + + private static func axFind( + in element: AXUIElement, + label: String, + role: String, + depth: Int + ) -> AXUIElement? { + guard depth < 40 else { return nil } + let roleValue = axString(element, kAXRoleAttribute) + if roleValue == role, + axString(element, kAXDescriptionAttribute) == label || axString(element, kAXTitleAttribute) == label { + return element + } + for child in axChildren(element) { + if let found = axFind(in: child, label: label, role: role, depth: depth + 1) { + return found + } + } + return nil + } + + private static func axFindMatching( + in element: AXUIElement, + role: String, + contains text: String, + depth: Int + ) -> AXUIElement? { + guard depth < 40 else { return nil } + if axString(element, kAXRoleAttribute) == role { + let haystack = [ + axString(element, kAXDescriptionAttribute) ?? "", + axString(element, kAXTitleAttribute) ?? "", + axString(element, kAXValueAttribute) ?? "", + ].joined(separator: " ") + if haystack.lowercased().contains(text.lowercased()) { + return element + } + } + for child in axChildren(element) { + if let found = axFindMatching(in: child, role: role, contains: text, depth: depth + 1) { + return found + } + } + return nil + } + + private static func axString(_ element: AXUIElement, _ attribute: String) -> String? { + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else { + return nil + } + return value as? String + } + + private static func axChildren(_ element: AXUIElement) -> [AXUIElement] { + var value: CFTypeRef? + guard AXUIElementCopyAttributeValue( + element, kAXChildrenAttribute as CFString, &value) == .success, + let children = value as? [AXUIElement] + else { return [] } + return children + } + + private static func axFrame(_ element: AXUIElement) -> CGRect? { + var positionValue: CFTypeRef? + var sizeValue: CFTypeRef? + guard AXUIElementCopyAttributeValue( + element, kAXPositionAttribute as CFString, &positionValue) == .success, + AXUIElementCopyAttributeValue( + element, kAXSizeAttribute as CFString, &sizeValue) == .success, + let positionAX = positionValue, let sizeAX = sizeValue + else { return nil } + var position = CGPoint.zero + var size = CGSize.zero + guard AXValueGetValue(positionAX as! AXValue, .cgPoint, &position), + AXValueGetValue(sizeAX as! AXValue, .cgSize, &size) + else { return nil } + return CGRect(origin: position, size: size) + } + + /// Accessibility positions use a top-left origin over every screen; AppKit window + /// coordinates use the primary screen's bottom-left origin. + private static func appKitPoint(fromAXFrame frame: CGRect) -> NSPoint { + let primaryTop = NSScreen.screens.first?.frame.maxY ?? 0 + return NSPoint(x: frame.midX, y: primaryTop - frame.midY) + } + + /// Maps an accessibility frame (top-left screen origin) into the window's own + /// coordinates, using the window's own AX frame as the reference so the mapping + /// holds on any display arrangement without assuming which screen is primary. + @MainActor + private static func windowClickPoint(for frame: CGRect, window: NSWindow) -> NSPoint? { + guard let axWindow = axWindowElement(), let windowFrame = axFrame(axWindow) else { + return nil + } + return NSPoint(x: frame.midX - windowFrame.minX, y: windowFrame.maxY - frame.midY) + } + + private static func axWindowElement() -> AXUIElement? { + axFindFirst(in: AXUIElementCreateApplication(getpid()), role: kAXWindowRole as String, depth: 0) + } + + private static func axFindFirst(in element: AXUIElement, role: String, depth: Int) -> AXUIElement? { + guard depth < 20 else { return nil } + if axString(element, kAXRoleAttribute) == role { return element } + for child in axChildren(element) { + if let found = axFindFirst(in: child, role: role, depth: depth + 1) { + return found + } + } + return nil + } + + private static func axSummary() -> String { + let application = AXUIElementCreateApplication(getpid()) + var parts: [String] = [] + collectAXSummary(in: application, depth: 0, into: &parts) + return parts.isEmpty ? "nothing (accessibility tree unavailable)" : parts.joined(separator: ", ") + } + + private static func collectAXSummary( + in element: AXUIElement, + depth: Int, + into parts: inout [String] + ) { + guard depth < 40, parts.count < 30 else { return } + let role = axString(element, kAXRoleAttribute) ?? "?" + if role == kAXButtonRole as String || role == kAXTextFieldRole as String { + let title = axString(element, kAXTitleAttribute) ?? "" + let description = axString(element, kAXDescriptionAttribute) ?? "" + parts.append("\(role)[\(title)\(description.isEmpty ? "" : "|\(description)")]") + } + for child in axChildren(element) { + collectAXSummary(in: child, depth: depth + 1, into: &parts) + } + } + + // MARK: - Utilities and fixtures + + /// Runs the app's event loop for a moment, delivering queued mouse and key events. + /// `RunLoop.run` alone does not dequeue NSEvents — only NSApplication does. + @MainActor + private static func pump(_ seconds: TimeInterval) { + let deadline = Date(timeIntervalSinceNow: seconds) + repeat { + if let event = NSApp.nextEvent( + matching: .any, + until: Date(timeIntervalSinceNow: 0.005), + inMode: .default, + dequeue: true + ) { + NSApp.sendEvent(event) + } + // The run loop is what resumes main-actor work (the debounced manifest + // write, for example); the event dequeue above is what delivers input. + RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.005)) + } while Date() < deadline + } + + private static func check(_ condition: Bool, _ description: String) throws { + guard condition else { throw SelfTestFailure(description) } + } + + @MainActor + private static func appendResult(_ line: String, to url: URL) { + let existing = (try? String(contentsOf: url, encoding: .utf8)) ?? "" + try? (existing + line + "\n").write(to: url, atomically: true, encoding: .utf8) + print(line) + } + + /// Step logging that reaches the result file (the app is launched by LaunchServices, + /// so its stdout is not captured). + @MainActor private static var stepLogURL: URL? + @MainActor private static weak var debugModel: AppModel? + + /// A cheap change-detector for "did that click do anything". + @MainActor + private static func modelFingerprint() -> String { + guard let model = debugModel else { return "" } + return "\(model.session.id)-\(model.pastSessions.count)-" + + "\(model.selectedSessionID?.uuidString ?? "nil")" + } + + @MainActor + private static func modelLaneForDebug() -> String { + debugModel?.session.context.lane ?? "" + } + + @MainActor + private static func note(_ line: String) { + if let stepLogURL { appendResult("E2E STEP " + line, to: stepLogURL) } + } + + @discardableResult + static func writeBackdatedSession(in paths: AppSupportPaths, daysAgo: Int) throws -> UUID { + let id = UUID() + let createdAt = Date().addingTimeInterval(-Double(daysAgo) * 86_400) + let dir = paths.archiveDirectory(id) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let pngName = "001-\(String(id.uuidString.prefix(8)).uppercased()).png" + try makePNG(width: 16, height: 9, red: 0.4, green: 0.4, blue: 0.4) + .write(to: dir.appendingPathComponent(pngName)) + let capture = Capture( + id: UUID(), sequence: 1, fileName: pngName, + pixelWidth: 16, pixelHeight: 9, scale: 1.0, capturedAt: createdAt) + let session = CaptureSession( + id: id, createdAt: createdAt, state: .archived, captures: [capture], + pdfFileName: nil, + context: ReviewContext(lane: "dev03", deployedVersion: "v0.9.0", commit: "0ldc0de")) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + try encoder.encode(session).write(to: dir.appendingPathComponent("session.json")) + return id + } + + static func makePNG( + width: Int, height: Int, red: CGFloat, green: CGFloat, blue: CGFloat + ) throws -> Data { + let colorSpace = CGColorSpaceCreateDeviceRGB() + guard let context = CGContext( + data: nil, width: width, height: height, + bitsPerComponent: 8, bytesPerRow: width * 4, space: colorSpace, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue + ), let image = { + context.setFillColor(red: red, green: green, blue: blue, alpha: 1) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + return context.makeImage() + }() else { + throw SelfTestFailure("could not draw a test PNG") + } + let data = NSMutableData() + guard let destination = CGImageDestinationCreateWithData( + data, "public.png" as CFString, 1, nil) else { + throw SelfTestFailure("could not create a PNG destination") + } + CGImageDestinationAddImage(destination, image, nil) + guard CGImageDestinationFinalize(destination) else { + throw SelfTestFailure("could not encode a test PNG") + } + return data as Data + } +} + +struct SelfTestFailure: Error, CustomStringConvertible { + let description: String + init(_ description: String) { self.description = description } +} diff --git a/Sources/Shotdeck/PanelSnapshot.swift b/Sources/Shotdeck/PanelSnapshot.swift index c22c7a6..be46590 100644 --- a/Sources/Shotdeck/PanelSnapshot.swift +++ b/Sources/Shotdeck/PanelSnapshot.swift @@ -76,18 +76,36 @@ enum PanelSnapshot { // 06 — SettingsView against the same isolated model. try render( SettingsView().environment(model), - to: directory.appendingPathComponent("panel-06-settings.png") + to: directory.appendingPathComponent("panel-06-settings.png"), + width: 460, + height: 820 ) - // 06b — Past submissions window against the same isolated model: the two - // seeded past sessions plus the live session's three captures from panel 04. + // 06b — the sessions window: real sidebar, pages grid and inspector. model.setPastSessions(try await model.spool.archivedSessions()) try render( - PastSubmissionsView().environment(model), - to: directory.appendingPathComponent("panel-06b-past-submissions.png"), - width: 440 + SessionsWindowView().environment(model), + to: directory.appendingPathComponent("panel-06b-sessions-window.png"), + width: 1100, + height: 700 ) + // 15 — the window with a kept past session selected (read-only inspector). + if let kept = model.pastSessions.first { + model.selectSession(kept.id) + try render( + SessionsWindowView().environment(model), + to: directory.appendingPathComponent("panel-15-past-session.png"), + width: 1100, + height: 700 + ) + model.selectSession(model.session.id) + } + + // A real PDF built by the production composer, so the reference footer and the + // document info can be inspected (and opened) rather than assumed. + try writeSamplePDF(to: directory.appendingPathComponent("sample-review.pdf"), model: model) + // 07/08/09 — OneDrive-mode Settings + menu bar, on a SEPARATE isolated model so // this transport switch never bleeds into the AirDrop-mode panels above. try await captureOneDrivePanels(to: directory) @@ -142,7 +160,9 @@ enum PanelSnapshot { model.setResolvedOneDriveFolder(resolvedFolder) try render( SettingsView().environment(model), - to: directory.appendingPathComponent("panel-07-settings-onedrive.png") + to: directory.appendingPathComponent("panel-07-settings-onedrive.png"), + width: 460, + height: 820 ) // 08 — no OneDrive folder found: a fake home with NO Library/CloudStorage at @@ -161,7 +181,9 @@ enum PanelSnapshot { model.setResolvedOneDriveFolder(nil) try render( SettingsView().environment(model), - to: directory.appendingPathComponent("panel-08-settings-onedrive-missing.png") + to: directory.appendingPathComponent("panel-08-settings-onedrive-missing.png"), + width: 460, + height: 820 ) // 09 — menu bar panel, 3 captures present, OneDrive mode ("Send to OneDrive"). @@ -210,7 +232,12 @@ enum PanelSnapshot { _ = try await model.spool.append( pngData: try makePNGData(width: 192, height: 108, red: 0.25, green: 0.7, blue: 0.6), pixelWidth: 192, pixelHeight: 108, scale: 2.0, capturedAt: Date()) - let sentName = "Redline-\(DubaiTime.fileStamp(Date())).pdf" + let sentSession = try await model.spool.setContext( + ReviewContext( + lane: "DEV03", deployedVersion: "v1.4.2 (41)", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "checkout flow")) + let sentName = PDFFileName.make( + builtAt: Date(), lane: sentSession.context.lane, sessionID: sentSession.id) _ = try await model.spool.archiveCurrent(pdfFileName: sentName) // The real send writes the PDF to the outbox; the fixture does the same so the // row's PDF action is genuinely live in the snapshot. @@ -220,7 +247,37 @@ enum PanelSnapshot { _ = try await model.spool.append( pngData: try makePNGData(width: 160, height: 90, red: 0.9, green: 0.55, blue: 0.2), pixelWidth: 160, pixelHeight: 90, scale: 2.0, capturedAt: Date()) + _ = try await model.spool.setContext( + ReviewContext( + lane: "OMS test lane", deployedVersion: "v2.0.0-rc3", commit: "9f3e2d1", + reviewer: "Ben Hippler")) _ = try await model.spool.closeCurrentSession() + + // The live session shown in panels 03/04/05/15 carries details too. + _ = try await model.spool.setContext( + ReviewContext( + lane: "DEV03", deployedVersion: "v1.4.2 (41)", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "dashboard review")) + model.replaceSession(try await model.spool.currentSession()) + // Both seeded sessions are really on disk by now; load them into the model so + // the panel's recent list is live rather than empty. + model.setPastSessions(try await model.spool.archivedSessions()) + } + + /// A real PDF from the production composer: one page per capture, header reference + /// line and the review footer. Written next to the panels so it can be opened. + @MainActor + private static func writeSamplePDF(to url: URL, model: AppModel) throws { + let session = model.session + guard !session.isEmpty else { return } + let sourceDir = model.paths.sessionDirectory(session.id) + _ = try PDFComposer().compose( + session: session, + imageURL: { capture in sourceDir.appendingPathComponent(capture.fileName) }, + title: "Redline – \(session.context.lane) – \(DubaiTime.stamp(session.createdAt))", + to: url, + toolVersion: model.appVersion + ) } @MainActor @@ -232,18 +289,32 @@ enum PanelSnapshot { } @MainActor - private static func render(_ view: some View, to url: URL, width: CGFloat = panelWidth) throws { - let wrapped = view - .frame(width: width, alignment: .topLeading) - .fixedSize(horizontal: false, vertical: true) - .background(Color(nsColor: .windowBackgroundColor)) + private static func render( + _ view: some View, + to url: URL, + width: CGFloat = panelWidth, + height: CGFloat? = nil + ) throws { + // A fixed-size render (a whole window) must fill its frame; a popover render + // sizes to its content. fixedSize on a split view collapses its columns. + let wrapped = Group { + if let height { + view.frame(width: width, height: height) + } else { + view + .frame(width: width, alignment: .topLeading) + .fixedSize(horizontal: false, vertical: true) + } + } + .frame(width: width, height: height, alignment: .topLeading) + .background(Color(nsColor: .windowBackgroundColor)) let hosting = NSHostingView(rootView: wrapped) hosting.wantsLayer = true hosting.appearance = NSAppearance(named: .aqua) let window = NSWindow( - contentRect: NSRect(x: -10_000, y: -10_000, width: panelWidth, height: 64), + contentRect: NSRect(x: -10_000, y: -10_000, width: width, height: 200), styleMask: [.borderless], backing: .buffered, defer: false @@ -258,17 +329,26 @@ enum PanelSnapshot { hosting.layoutSubtreeIfNeeded() var size = hosting.fittingSize - if size.height < 1 { - size.height = hosting.intrinsicContentSize.height + if let height { + size.height = height + } else { + if size.height < 1 { + size.height = hosting.intrinsicContentSize.height + } + if size.height < 1 { size.height = 240 } } - if size.height < 1 { size.height = 240 } size.width = width size.height = ceil(size.height) hosting.setFrameSize(size) window.setContentSize(size) hosting.layoutSubtreeIfNeeded() - RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.05)) + // A split view (sidebar + inspector) needs a real display cycle before its + // columns and list rows exist; a single layout pass renders blank columns. + window.displayIfNeeded() + RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.35)) + hosting.layoutSubtreeIfNeeded() + window.displayIfNeeded() let bounds = hosting.bounds guard let rep = hosting.bitmapImageRepForCachingDisplay(in: bounds) else { @@ -296,6 +376,9 @@ enum PanelSnapshot { watchFolder: root.appendingPathComponent("watch", isDirectory: true) ) let ledger = try ReturnLedger(paths: paths) + // Isolated defaults: rendering a panel must never read or write the real + // age-limit preference. + let suite = try makeIsolatedDefaultsSuite() let model = AppModel( paths: paths, spool: try SpoolStore(paths: paths), @@ -304,7 +387,8 @@ enum PanelSnapshot { hotkeys: HotkeyCenter(), picker: RegionPickerController(), ledger: ledger, - watcher: ReturnWatcher(paths: paths, ledger: ledger) + watcher: ReturnWatcher(paths: paths, ledger: ledger), + retentionDefaults: suite.defaults ) model.setFolderURLs(outbox: paths.outbox, watch: paths.watchFolder) return (model, root) diff --git a/Sources/Shotdeck/PastSubmissionsView.swift b/Sources/Shotdeck/PastSubmissionsView.swift deleted file mode 100644 index 50a3e89..0000000 --- a/Sources/Shotdeck/PastSubmissionsView.swift +++ /dev/null @@ -1,146 +0,0 @@ -import AppKit -import SwiftUI -import ShotdeckCore - -/// "Past submissions…" window: every retained session and what was sent for it. -/// Read-and-reveal only — keeping/starting sessions is driven from the menu rows -/// (and the button on the current-session row below). -struct PastSubmissionsView: View { - @Environment(AppModel.self) private var model - - var body: some View { - VStack(alignment: .leading, spacing: 8) { - currentSessionRow - Divider() - if model.pastSessions.isEmpty { - Text("No past sessions yet. Use “Start new session” to keep the current captures.") - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } else { - ScrollView { - VStack(alignment: .leading, spacing: 6) { - ForEach(model.pastSessions) { session in - PastSessionRow(session: session) - } - } - } - .frame(maxHeight: 320) - } - Divider() - footer - } - .padding(10) - .frame(width: 420, alignment: .leading) - .controlSize(.small) - .task { - if let problem = await model.reloadFromSpool() { - model.setStatus(problem) - } - } - } - - private var currentSessionRow: some View { - HStack(alignment: .center, spacing: 8) { - VStack(alignment: .leading, spacing: 2) { - Text("Current session") - .font(.caption) - .foregroundStyle(.secondary) - Text(currentSessionSummary) - .fixedSize(horizontal: false, vertical: true) - } - Spacer(minLength: 8) - Button("Start new session") { - Task { await model.startNewSession() } - } - .disabled(!model.canStartNewSession) - .help("Keeps these captures as a past session and starts a fresh one.") - } - } - - private var currentSessionSummary: String { - let count = model.session.captures.count - if count == 0 { - return "Nothing captured yet." - } - return "\(count) capture\(count == 1 ? "" : "s") · started \(DubaiTime.stamp(model.session.createdAt))" - } - - private var footer: some View { - HStack(spacing: 8) { - Text("Sessions are kept in one folder — the newest \(SpoolStore.defaultRetainedSessionCount).") - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - Spacer(minLength: 8) - Button("Open sessions folder") { - model.openSessionsFolder() - } - } - } -} - -private struct PastSessionRow: View { - @Environment(AppModel.self) private var model - let session: CaptureSession - - var body: some View { - HStack(alignment: .center, spacing: 8) { - VStack(alignment: .leading, spacing: 2) { - Text(DubaiTime.stamp(session.createdAt)) - Text(submissionLabel) - .font(.caption) - .foregroundStyle(session.pdfFileName == nil ? .secondary : .primary) - .lineLimit(1) - } - Spacer(minLength: 8) - Button("PDF") { - model.revealSentPDF(session) - } - .disabled(model.sentPDFURL(for: session) == nil) - .help(pdfHelpText) - Button("Captures") { - model.revealSessionCaptures(session) - } - .help("Reveal this session's screenshots") - } - } - - private var pdfHelpText: String { - guard let name = session.pdfFileName else { return "This session was never sent." } - guard model.sentPDFURL(for: session) != nil else { - return "The PDF \(name) is no longer in the output folder." - } - return "Reveal \(name)" - } - - private var submissionLabel: String { - let pages = "\(session.captures.count) page\(session.captures.count == 1 ? "" : "s")" - guard let name = session.pdfFileName else { - return "\(pages) · not sent" - } - return "\(pages) · sent as \(name)" - } -} - -extension AppModel: SubmissionsWindowPresenting { - private static var submissionsWindowController: NSWindowController? - - public func presentSubmissionsWindow() { - if let existing = Self.submissionsWindowController { - existing.window?.makeKeyAndOrderFront(nil) - NSApp.activate() - return - } - let hosting = NSHostingController(rootView: PastSubmissionsView().environment(self)) - let window = NSWindow(contentViewController: hosting) - window.title = "Redline — Past submissions" - window.styleMask = [.titled, .closable] - window.isReleasedWhenClosed = false - window.center() - let controller = NSWindowController(window: window) - Self.submissionsWindowController = controller - controller.showWindow(nil) - NSApp.activate() - } -} diff --git a/Sources/Shotdeck/RegionPickerController.swift b/Sources/Shotdeck/RegionPickerController.swift index 114fdcf..d3cfea5 100644 --- a/Sources/Shotdeck/RegionPickerController.swift +++ b/Sources/Shotdeck/RegionPickerController.swift @@ -15,12 +15,40 @@ public final class RegionPickerController { /// Presents one overlay per attached screen. A pick already in progress is cancelled /// (its completion called with nil) before the new one starts — never leaves a caller /// waiting forever on a dropped re-entrant call. - public func pick(completion: @escaping @MainActor (CaptureRegion?) -> Void) { + /// Passing `confirming` shows that area as already chosen and lets Return confirm + /// it — the fast path after "New Session": drag for a new area, or press Return to + /// keep the saved one. + public func pick( + confirming: CaptureRegion? = nil, + completion: @escaping @MainActor (CaptureRegion?) -> Void + ) { if self.completion != nil { finish(region: nil) } + self.confirmingRegion = confirming self.completion = completion presentOverlays() + if let confirming { + showConfirmingSelection(confirming) + } + } + + private var confirmingRegion: CaptureRegion? + + /// Shows the saved area as a pre-selection on the overlay for its display. + private func showConfirmingSelection(_ region: CaptureRegion) { + for window in windows where window.coveringScreen.frame.contains( + CGPoint(x: region.rect.midX, y: window.coveringScreen.frame.midY)) + { + let local = CGRect( + x: region.rect.minX - window.coveringScreen.frame.minX, + y: region.rect.minY, + width: region.rect.width, + height: region.rect.height + ) + window.updateSelection( + localRect: local, sizeText: "\(region.summary) · Return keeps it") + } } private func presentOverlays() { @@ -72,7 +100,11 @@ public final class RegionPickerController { switch type { case .keyDown: if keyCode == 53 { // kVK_Escape - finish(region: nil) + finish(region: confirmingRegion) + return true + } + if keyCode == 36, let confirmingRegion { // Return confirms the saved area + finish(region: confirmingRegion) return true } return false diff --git a/Sources/Shotdeck/SendController.swift b/Sources/Shotdeck/SendController.swift index f802dba..b412584 100644 --- a/Sources/Shotdeck/SendController.swift +++ b/Sources/Shotdeck/SendController.swift @@ -150,7 +150,14 @@ extension AppModel: SendCapable { let finalURL = outboxDir.appendingPathComponent(fileName) // Same directory as the final target so the rename below is same-volume (atomic). let tempURL = outboxDir.appendingPathComponent(".shotdeck-\(UUID().uuidString).pdf") - let title = "Redline – \(DubaiTime.stamp(workingSession.createdAt))" + // The document title follows the same three parts as the file name: tool, + // lane (when recorded) and Dubai time. + let lane = workingSession.context.lane + let titleParts = ["Redline"] + + (lane.isEmpty ? [] : [lane]) + + [DubaiTime.stamp(Date())] + let title = titleParts.joined(separator: " – ") + let toolVersion = appVersion // D-13: build off the main actor. Only Sendable values cross into the // detached task — never `anchor` (NSView is not Sendable). @@ -159,7 +166,8 @@ extension AppModel: SendCapable { session: workingSession, imageURL: { capture in sourceDir.appendingPathComponent(capture.fileName) }, title: title, - to: tempURL + to: tempURL, + toolVersion: toolVersion ) // POSIX rename onto `finalURL` replaces any same-name file in one // directory operation; there is never a window where the PDF is gone. @@ -202,8 +210,9 @@ extension AppModel: SendCapable { func handleDidShareItems(fileName: String, sentSummary: String) async { guard !session.isEmpty else { return } var message = sentSummary + var archivedID: UUID? do { - _ = try await spool.archiveCurrent(pdfFileName: fileName) + archivedID = try await spool.archiveCurrent(pdfFileName: fileName).id } catch { message += " \((error as? ShotdeckError)?.errorDescription ?? "Could not archive the session.")" } @@ -214,6 +223,11 @@ extension AppModel: SendCapable { if let refreshProblem = await reloadFromSpool() { message += " \(refreshProblem)" } + // Leave the window on the session that was just sent: that is what the person + // is looking at when the PDF leaves. + if let archivedID { + selectSession(archivedID) + } setStatus(message) } diff --git a/Sources/Shotdeck/SessionContextEditor.swift b/Sources/Shotdeck/SessionContextEditor.swift new file mode 100644 index 0000000..1131ded --- /dev/null +++ b/Sources/Shotdeck/SessionContextEditor.swift @@ -0,0 +1,98 @@ +import SwiftUI +import ShotdeckCore + +/// The five review-detail fields of a session, in one compact grid. +/// +/// Values are held locally while typing and written through to the session manifest +/// on every change, so closing the panel cannot lose them. The local copy is re-seeded +/// whenever the open session changes (a new session inherits the previous details). +struct SessionContextEditor: View { + @Environment(AppModel.self) private var model + + @State private var lane = "" + @State private var deployedVersion = "" + @State private var commitHash = "" + @State private var reviewer = "" + @State private var note = "" + @State private var seededSessionID: UUID? + /// What this view last wrote (or seeded). Lets an out-of-band change — a context + /// inherited by a new session, for example — refresh the fields without fighting + /// the user's own keystrokes. + @State private var lastKnownContext: ReviewContext = .empty + /// The pending debounced write and its value. Typing replaces it, so one short + /// pause writes once instead of once per keystroke, and an older write can never + /// land after a newer one. + @State private var pendingWrite: Task? + @State private var lastScheduledWrite: ReviewContext = .empty + + private let labelWidth: CGFloat = 84 + + var body: some View { + Grid(alignment: .leading, horizontalSpacing: 8, verticalSpacing: 4) { + row("Lane", text: $lane, prompt: "dev03, customer test lane…") + row("Deployed", text: $deployedVersion, prompt: "build that is live") + row("Commit", text: $commitHash, prompt: "git SHA") + row("Reviewer", text: $reviewer, prompt: "who is reviewing") + row("Note", text: $note, prompt: "what this session covers") + } + .onAppear { seedIfNeeded() } + .onChange(of: model.session.id) { _, _ in seedIfNeeded() } + .onChange(of: model.session.context) { _, newValue in + guard newValue != lastKnownContext else { return } + seed(from: newValue) + } + .onChange(of: lane) { _, _ in commit() } + .onChange(of: deployedVersion) { _, _ in commit() } + .onChange(of: commitHash) { _, _ in commit() } + .onChange(of: reviewer) { _, _ in commit() } + .onChange(of: note) { _, _ in commit() } + } + + private func row(_ label: String, text: Binding, prompt: String) -> some View { + GridRow(alignment: .center) { + Text(label) + .font(.caption) + .foregroundStyle(.secondary) + .frame(width: labelWidth, alignment: .trailing) + TextField(prompt, text: text) + .textFieldStyle(.roundedBorder) + .font(.caption) + .onSubmit { commit() } + } + } + + private func seedIfNeeded() { + guard seededSessionID != model.session.id else { return } + seededSessionID = model.session.id + seed(from: model.session.context) + } + + private func seed(from context: ReviewContext) { + lane = context.lane + deployedVersion = context.deployedVersion + commitHash = context.commit + reviewer = context.reviewer + note = context.note + lastKnownContext = context + } + + private func commit() { + let context = ReviewContext( + lane: lane, + deployedVersion: deployedVersion, + commit: commitHash, + reviewer: reviewer, + note: note + ) + guard context != model.session.context else { return } + guard context != lastScheduledWrite else { return } + lastKnownContext = context + lastScheduledWrite = context + pendingWrite?.cancel() + pendingWrite = Task { + try? await Task.sleep(for: .milliseconds(150)) + guard !Task.isCancelled else { return } + await model.setContextField(context) + } + } +} diff --git a/Sources/Shotdeck/SessionStrip.swift b/Sources/Shotdeck/SessionStrip.swift index 4786340..a8f2700 100644 --- a/Sources/Shotdeck/SessionStrip.swift +++ b/Sources/Shotdeck/SessionStrip.swift @@ -2,22 +2,35 @@ import AppKit import SwiftUI import ShotdeckCore +/// The popover's page strip: at most `limit` thumbnails plus a "+N" tile, so the +/// popover never turns into a filmstrip of the whole session. struct SessionStrip: View { @Environment(AppModel.self) private var model + var limit: Int? = nil var body: some View { + let captures = Array(model.session.captures.prefix(limit ?? model.session.captures.count)) + let hidden = model.session.captures.count - captures.count + 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) - } + HStack(alignment: .top, spacing: 6) { + ForEach(captures) { capture in + SessionThumb(capture: capture) } + if hidden > 0 { + Text("+\(hidden)") + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.secondary) + .frame(width: 52, height: 64) + .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 4, style: .continuous)) + .help("\(hidden) more page\(hidden == 1 ? "" : "s") — open Redline to see them") + } + Spacer(minLength: 0) } .frame(height: 64) } @@ -63,7 +76,7 @@ private struct SessionThumb: View { @ViewBuilder private var thumbnail: some View { - let url = model.paths.sessionDirectory(model.session.id).appendingPathComponent(capture.fileName) + let url = model.imageURL(for: capture, in: model.session) if let image = NSImage(contentsOf: url) { Image(nsImage: image) .resizable() diff --git a/Sources/Shotdeck/SessionsWindowView.swift b/Sources/Shotdeck/SessionsWindowView.swift new file mode 100644 index 0000000..811a636 --- /dev/null +++ b/Sources/Shotdeck/SessionsWindowView.swift @@ -0,0 +1,748 @@ +import AppKit +import SwiftUI +import ShotdeckCore + +/// The Redline window: every session on the left, the selected session's pages in the +/// middle, and that session's review details / PDF / session facts on the right. +/// This is where history, text entry and file facts live; the popover only glances at +/// the current session and fires the two main actions. +struct SessionsWindowView: View { + @Environment(AppModel.self) private var model + @State private var searchText = "" + @State private var selectedCaptureID: UUID? + @State private var showInspector = true + + var body: some View { + // Three explicit columns rather than NavigationSplitView: the window has a + // fixed, always-visible inspector, and a plain split keeps the sidebar rows and + // the inspector rendering deterministically in every window state. + HStack(spacing: 0) { + sidebar + .frame(width: 230) + Divider() + detail + .frame(maxWidth: .infinity, maxHeight: .infinity) + if showInspector { + Divider() + SessionInspector(session: selectedSession) + .frame(width: 300) + } + } + .frame(minWidth: 900, minHeight: 560) + .controlSize(.regular) + .background(Color(nsColor: .windowBackgroundColor)) + .onChange(of: model.selectedSessionID) { _, _ in + selectedCaptureID = nil + } + } + + private var selectedSession: CaptureSession { + model.selectedSession ?? model.session + } + + // MARK: - Sidebar + + private var sidebar: some View { + VStack(spacing: 0) { + HStack(spacing: 6) { + Image(systemName: "magnifyingglass") + .foregroundStyle(.secondary) + TextField("Search sessions", text: $searchText) + .textFieldStyle(.plain) + if !searchText.isEmpty { + Button { + searchText = "" + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + .accessibilityLabel("Clear search") + } + } + .padding(.horizontal, 8) + .padding(.vertical, 5) + .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + .padding(8) + + List(selection: selection) { + ForEach(sections) { section in + Section(section.title) { + ForEach(section.sessions) { session in + SessionRow(session: session) + .tag(session.id) + } + } + } + } + .listStyle(.sidebar) + + if sections.isEmpty { + Text(searchText.isEmpty ? "No sessions yet." : "No session matches “\(searchText)”.") + .font(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .padding(12) + } + } + .background(Color(nsColor: .controlBackgroundColor)) + } + + private var sections: [AppModel.SessionGroup] { + model.groupedSections(for: model.sessions(matching: searchText)) + } + + private var selection: Binding { + Binding( + get: { model.selectedSession?.id }, + set: { model.selectSession($0) } + ) + } + + // MARK: - Detail + + private var detail: some View { + VStack(alignment: .leading, spacing: 0) { + header + Divider() + if let document = model.returnedDocument(for: selectedSession), document.isCommented { + ReturnedBanner(document: document, session: selectedSession) + Divider() + } + pages + } + .background(Color(nsColor: .textBackgroundColor)) + } + + private var header: some View { + HStack(alignment: .center, spacing: 10) { + VStack(alignment: .leading, spacing: 1) { + HStack(spacing: 6) { + Text(laneTitle) + .font(.system(size: 15, weight: .semibold)) + .lineLimit(1) + .truncationMode(.tail) + if model.selectedIsCurrent { + Text("Current") + .font(.system(size: 9, weight: .semibold)) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background(.quaternary, in: Capsule()) + } + } + Text(subtitle) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + } + .layoutPriority(0) + Spacer(minLength: 12) + Button { + showInspector.toggle() + } label: { + Image(systemName: "sidebar.right") + } + .buttonStyle(.borderless) + .help(showInspector ? "Hide the inspector" : "Show the inspector") + .accessibilityLabel(showInspector ? "Hide the inspector" : "Show the inspector") + + // What the next capture takes, in the same place as the verbs. + Menu { + ForEach(CaptureScope.allCases, id: \.self) { scope in + Button { + Task { + await model.chooseCaptureScope(scope) + await model.captureNow() + } + } label: { + Text("\(scope.menuTitle) — capture now") + } + } + Divider() + Button("Choose New Area…") { + Task { await model.rePickRegion() } + } + } label: { + HStack(spacing: 4) { + Image(systemName: scopeSymbol) + Text("\(model.captureScope.displayName) · \(scopeDetail)") + .lineLimit(1) + } + } + .menuStyle(.borderlessButton) + .fixedSize() + .help("What Capture takes") + .accessibilityLabel("Capture: \(model.captureTargetDescription)") + + if model.captureScope == .area { + Button("Choose Area…") { + Task { await model.rePickRegion() } + } + .fixedSize() + .help("Pick a new area to capture") + } + + Button { + Task { await model.newSession() } + } label: { + Label("New Session", systemImage: "plus.square.on.square") + } + .keyboardShortcut("n", modifiers: .command) + .disabled(model.isSending) + .fixedSize() + .help("Keep this session and start a fresh one, then ask where to capture (⌘N)") + + Button { + Task { await model.captureNow() } + } label: { + Label(model.isCapturing ? "Capturing…" : "Capture", systemImage: "viewfinder") + } + .disabled(model.isCapturing || !model.selectedIsCurrent) + .fixedSize() + + Button { + guard let sender = model as? SendCapable else { return } + let anchor = NSApp.keyWindow?.contentView + Task { await sender.send(anchor: anchor) } + } label: { + Label(sendTitle, systemImage: "paperplane.fill") + } + .buttonStyle(.borderedProminent) + .layoutPriority(1) + .keyboardShortcut("s", modifiers: .command) + .disabled(!model.selectedIsCurrent || model.session.isEmpty || model.isSending) + .help(model.transport == .oneDrive + ? "Save the PDF to the OneDrive folder (⌘S)" + : "AirDrop the PDF (⌘S)") + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + } + + private var laneTitle: String { + let lane = selectedSession.context.lane + if !lane.isEmpty { return lane } + return selectedSession.id == model.session.id ? "Current session" : selectedSession.shortID + } + + private var subtitle: String { + let pages = selectedSession.captures.count + let pageWord = "\(pages) page\(pages == 1 ? "" : "s")" + return "\(pageWord) · \(model.state(of: selectedSession).label)" + } + + private var sendTitle: String { + model.transport == .oneDrive ? "Save…" : "Send…" + } + + private var scopeSymbol: String { + switch model.captureScope { + case .area: return "rectangle.dashed" + case .window: return "macwindow" + case .browser: return "safari" + case .screen: return "display" + } + } + + /// Short form for the header: the area size, or what a window scope grabs. + private var scopeDetail: String { + switch model.captureScope { + case .area: + guard let region = model.region else { return "not set" } + return "\(Int(region.rect.width)) × \(Int(region.rect.height))" + case .window: return "front window" + case .browser: return "browser" + case .screen: + guard let region = model.region else { return "all" } + return "Display \(region.displayNumber)" + } + } + + // MARK: - Pages + + @ViewBuilder + private var pages: some View { + if selectedSession.isEmpty { + emptyState + } else { + ScrollView { + VStack(alignment: .leading, spacing: 12) { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text("Pages") + .font(.headline) + Text(pagesCaption) + .font(.caption) + .foregroundStyle(.secondary) + Spacer(minLength: 8) + Button("Remove Page") { + removeSelectedPage() + } + .disabled(!model.selectedIsCurrent || selectedCaptureID == nil) + } + LazyVGrid( + columns: [GridItem(.adaptive(minimum: 200, maximum: 240), spacing: 16)], + alignment: .leading, + spacing: 18 + ) { + ForEach(selectedSession.captures) { capture in + PageCard( + capture: capture, + session: selectedSession, + isSelected: selectedCaptureID == capture.id, + canRemove: model.selectedIsCurrent + ) { + selectedCaptureID = capture.id + } + } + } + } + .padding(16) + } + .onDeleteCommand { removeSelectedPage() } + } + } + + private var pagesCaption: String { + model.selectedIsCurrent + ? "In PDF order · Delete removes the selected page" + : "In the order they were sent" + } + + private var emptyState: some View { + VStack(spacing: 10) { + Image(systemName: "viewfinder") + .font(.system(size: 28, weight: .light)) + .foregroundStyle(.secondary) + Text("No pages in this session") + .font(.headline) + Text(emptyStateDetail) + .font(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .frame(maxWidth: 320) + HStack(spacing: 8) { + Button("Choose Area…") { + Task { await model.rePickRegion() } + } + Button("Capture \(model.hotkeyDisplayString)") { + Task { await model.captureNow() } + } + .buttonStyle(.borderedProminent) + } + .padding(.top, 4) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding(24) + } + + private var emptyStateDetail: String { + if model.region == nil { + return "Choose the part of the screen you review, then capture it. Each capture becomes one page of the PDF." + } + return "Press \(model.hotkeyDisplayString) to capture the saved area. Each capture becomes one page of the PDF." + } + + private func removeSelectedPage() { + guard model.selectedIsCurrent, let id = selectedCaptureID else { return } + selectedCaptureID = nil + Task { await model.removeCapture(id: id) } + } +} + +// MARK: - Sidebar row + +private struct SessionRow: View { + @Environment(AppModel.self) private var model + let session: CaptureSession + + var body: some View { + let state = model.state(of: session) + VStack(alignment: .leading, spacing: 1) { + HStack(spacing: 5) { + Text(lane) + .lineLimit(1) + if state == .current { + Text("Current") + .font(.system(size: 9, weight: .semibold)) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background(.quaternary, in: Capsule()) + } + Spacer(minLength: 4) + Text(DubaiTime.checkTime(session.createdAt)) + .font(.caption) + .foregroundStyle(.secondary) + .monospacedDigit() + } + Text(detail(state)) + .font(.caption) + .foregroundStyle(state.isReturned ? AnyShapeStyle(.orange) : AnyShapeStyle(.secondary)) + .lineLimit(1) + } + .padding(.vertical, 2) + .accessibilityElement(children: .combine) + .accessibilityLabel("\(lane), \(DubaiTime.checkTime(session.createdAt)), \(session.captures.count) pages, \(state.label)") + } + + private var lane: String { + let lane = session.context.lane + return lane.isEmpty ? session.shortID : lane + } + + private func detail(_ state: AppModel.SessionDisplayState) -> String { + let pages = "\(session.captures.count) page\(session.captures.count == 1 ? "" : "s")" + if case .returned(let marked) = state { + return "\(pages) · came back with \(marked) page\(marked == 1 ? "" : "s") marked" + } + return "\(pages) · \(state.label)" + } +} + +// MARK: - Page card + +private struct PageCard: View { + @Environment(AppModel.self) private var model + let capture: Capture + let session: CaptureSession + let isSelected: Bool + let canRemove: Bool + let select: () -> Void + @State private var hovering = false + + var body: some View { + VStack(alignment: .leading, spacing: 5) { + ZStack(alignment: .topLeading) { + thumbnail + if hovering && canRemove { + Button("Remove") { + Task { await model.removeCapture(id: capture.id) } + } + .font(.caption2.weight(.semibold)) + .buttonStyle(.plain) + .foregroundStyle(.white) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(.black.opacity(0.65), in: Capsule()) + .padding(6) + } + } + .overlay { + RoundedRectangle(cornerRadius: 5, style: .continuous) + .strokeBorder(isSelected ? Color.accentColor : .clear, lineWidth: 2) + } + .frame(maxWidth: 240, alignment: .leading) + .onHover { hovering = $0 } + .onTapGesture(perform: select) + + HStack(spacing: 6) { + Text("Page \(capture.sequence)") + .font(.caption.weight(isSelected ? .semibold : .regular)) + Spacer(minLength: 4) + Text(DubaiTime.checkTime(capture.capturedAt)) + .font(.caption) + .foregroundStyle(.secondary) + .monospacedDigit() + } + } + } + + @ViewBuilder + private var thumbnail: some View { + let url = model.imageURL(for: capture, in: session) + if let image = NSImage(contentsOf: url) { + Image(nsImage: image) + .resizable() + .aspectRatio(contentMode: .fit) + .frame(maxWidth: .infinity) + .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous)) + .overlay { + RoundedRectangle(cornerRadius: 4, style: .continuous) + .strokeBorder(.quaternary, lineWidth: 0.5) + } + } else { + RoundedRectangle(cornerRadius: 4, style: .continuous) + .fill(.quaternary) + .frame(height: 96) + .overlay { + Text("Image missing") + .font(.caption2) + .foregroundStyle(.secondary) + } + } + } +} + +// MARK: - Returned banner + +private struct ReturnedBanner: View { + @Environment(AppModel.self) private var model + let document: ReturnedDocument + let session: CaptureSession + + var body: some View { + HStack(spacing: 8) { + Image(systemName: "pencil.and.outline") + .foregroundStyle(.orange) + Text(message) + .font(.callout) + Spacer(minLength: 8) + Button("Open PDF") { + NSWorkspace.shared.open(document.fileURL) + } + if model.sentPDFURL(for: session) != nil { + Button("Show Original") { + model.revealSentPDF(session) + } + } + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + .background(.orange.opacity(0.1)) + } + + private var message: String { + let marked = document.annotatedPages.count + return "Came back with marks on \(marked) page\(marked == 1 ? "" : "s")." + } +} + +// MARK: - Inspector + +private struct SessionInspector: View { + @Environment(AppModel.self) private var model + let session: CaptureSession + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 16) { + reviewDetails + if !model.selectedIsCurrent { + Text("Past sessions are read-only: the PDF already carries these values.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + pdfFacts + sessionFacts + } + .padding(14) + } + .background(Color(nsColor: .windowBackgroundColor)) + } + + private var reviewDetails: some View { + VStack(alignment: .leading, spacing: 6) { + Text("Review details") + .font(.headline) + GroupBox { + VStack(spacing: 0) { + contextRow("Lane", prompt: "dev03, customer test lane…", \.lane, focusOnRequest: true) + RowDivider() + contextRow("Deployed", prompt: "build that is live", \.deployedVersion) + RowDivider() + contextRow("Commit", prompt: "git SHA", \.commit) + RowDivider() + contextRow("Reviewer", prompt: "who is reviewing", \.reviewer) + RowDivider() + contextRow("Note", prompt: "what this session covers", \.note) + } + } + Text("Printed on every page of the PDF. A new session starts with these values.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + @ViewBuilder + private func contextRow( + _ label: String, + prompt: String, + _ field: WritableKeyPath, + focusOnRequest: Bool = false + ) -> some View { + if model.selectedIsCurrent { + EditableContextRow(label: label, prompt: prompt, field: field, focusOnRequest: focusOnRequest) + } else { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(label) + .foregroundStyle(.secondary) + .frame(width: 74, alignment: .leading) + Text(displayValue(field)) + .frame(maxWidth: .infinity, alignment: .leading) + .textSelection(.enabled) + } + .padding(.vertical, 5) + } + } + + private func displayValue(_ field: KeyPath) -> String { + let value = session.context[keyPath: field] + return value.isEmpty ? "—" : value + } + + private var pdfFacts: some View { + VStack(alignment: .leading, spacing: 6) { + Text("PDF") + .font(.headline) + GroupBox { + VStack(spacing: 0) { + FactRow(label: "File name", value: pdfFileName, selectable: true) + RowDivider() + FactRow(label: "Pages", value: "\(session.captures.count)") + RowDivider() + FactRow( + label: "Sends via", + value: model.transport == .oneDrive ? "OneDrive folder" : "AirDrop") + RowDivider() + FactRow(label: "Status", value: model.state(of: session).label) + } + } + } + } + + private var pdfFileName: String { + if let name = session.pdfFileName { return name } + return model.selectedIsCurrent ? model.nextPDFFileNameHint : "—" + } + + private var sessionFacts: some View { + VStack(alignment: .leading, spacing: 6) { + Text("Session") + .font(.headline) + GroupBox { + VStack(spacing: 0) { + FactRow(label: "Started", value: DubaiTime.stamp(session.createdAt)) + RowDivider() + FactRow(label: "ID", value: session.shortID, monospaced: true) + RowDivider() + HStack { + Text("Files") + .foregroundStyle(.secondary) + Spacer(minLength: 8) + Button(model.selectedIsCurrent ? "Show Captures" : "Show in Finder") { + model.revealSessionCaptures(session) + } + .buttonStyle(.link) + } + .padding(.vertical, 5) + } + } + } + } +} + +private struct RowDivider: View { + var body: some View { + Divider().padding(.leading, 0) + } +} + +/// One editable review-detail row. The text lives in local state while typing and is +/// written through to the open session's manifest; it re-seeds whenever the session's +/// stored details change underneath it (a new session inheriting them, for example). +private struct EditableContextRow: View { + @Environment(AppModel.self) private var model + let label: String + let prompt: String + let field: WritableKeyPath + let focusOnRequest: Bool + + @State private var text: String = "" + @State private var lastSynced: String = "" + @FocusState private var focused: Bool + + var body: some View { + HStack(spacing: 8) { + Text(label) + .foregroundStyle(.secondary) + .frame(width: 74, alignment: .leading) + TextField(prompt, text: $text) + .textFieldStyle(.roundedBorder) + .controlSize(.small) + .focused($focused) + .accessibilityLabel(label) + .onSubmit { push() } + .onChange(of: text) { _, _ in push() } + } + .padding(.vertical, 5) + .onAppear { seed(from: stored) } + .onChange(of: model.session.context) { _, newValue in + let incoming = newValue[keyPath: field] + guard incoming != lastSynced else { return } + seed(from: incoming) + } + .onChange(of: model.session.id) { _, _ in + seed(from: stored) + } + .onChange(of: model.laneFocusRequest) { _, _ in + if focusOnRequest { focused = true } + } + } + + private var stored: String { + model.session.context[keyPath: field] + } + + private func seed(from value: String) { + text = value + lastSynced = value + } + + private func push() { + guard text != lastSynced else { return } + lastSynced = text + model.updateContext(field, text) + } +} + +private struct FactRow: View { + let label: String + let value: String + var monospaced: Bool = false + var selectable: Bool = false + + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(label) + .foregroundStyle(.secondary) + Spacer(minLength: 8) + Text(value) + .font(monospaced ? .system(.body, design: .monospaced) : .body) + .lineLimit(1) + .truncationMode(.middle) + .textSelection(.enabled) + .help(value) + } + .padding(.vertical, 5) + } +} + +// MARK: - Window presentation + +extension AppModel: SessionsWindowPresenting { + private static var sessionsWindowController: NSWindowController? + + public func presentSessionsWindow(focusLane: Bool) { + if focusLane { requestLaneFocus() } + if let existing = Self.sessionsWindowController { + existing.window?.makeKeyAndOrderFront(nil) + NSApp.activate() + return + } + let hosting = NSHostingController(rootView: SessionsWindowView().environment(self)) + let window = NSWindow(contentViewController: hosting) + window.title = "Redline" + window.styleMask = [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView] + window.titlebarAppearsTransparent = false + window.isReleasedWhenClosed = false + window.setContentSize(NSSize(width: 1240, height: 760)) + window.minSize = NSSize(width: 1000, height: 600) + window.center() + window.setFrameAutosaveName("RedlineSessionsWindow") + let controller = NSWindowController(window: window) + Self.sessionsWindowController = controller + controller.showWindow(nil) + NSApp.activate() + } +} diff --git a/Sources/Shotdeck/SettingsView.swift b/Sources/Shotdeck/SettingsView.swift index 787332a..a7391ba 100644 --- a/Sources/Shotdeck/SettingsView.swift +++ b/Sources/Shotdeck/SettingsView.swift @@ -2,125 +2,243 @@ import AppKit import SwiftUI import ShotdeckCore +/// Settings: three labelled groups, every row "what it is" on the left and the control +/// on the right. Nothing here is needed while reviewing, which is why it is its own +/// window and not part of the session surfaces. struct SettingsView: View { @Environment(AppModel.self) private var model @State private var isRecordingHotkey = false @State private var recorder = HotkeyRecorderBox() - private let labelWidth: CGFloat = 104 - var body: some View { - Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 10) { - GridRow { - Text("Hotkey") - .font(.headline) - .frame(maxWidth: .infinity, alignment: .leading) - .gridCellColumns(2) - } + Form { + Section("Capture") { + LabeledContent("What to capture") { + Picker("What to capture", selection: scopeBinding) { + ForEach(CaptureScope.allCases, id: \.self) { scope in + Text(scope.displayName).tag(scope) + } + } + .labelsHidden() + .pickerStyle(.segmented) + .frame(maxWidth: 240) + } - GridRow(alignment: .center) { - fieldLabel("Capture") - HStack(spacing: 8) { + LabeledContent("Saved area") { + HStack(spacing: 8) { + Text(areaSummary) + .foregroundStyle(.secondary) + .lineLimit(1) + Button("Choose…") { + Task { await model.rePickRegion() } + } + } + } + + LabeledContent("Capture shortcut") { Button { armHotkeyRecorder() } label: { Text(isRecordingHotkey ? "Press keys…" : model.hotkeyDisplayString) .foregroundStyle(isRecordingHotkey ? .secondary : .primary) - .lineLimit(1) - } - Spacer(minLength: 0) - } - .frame(minHeight: 22) - } - - GridRow { - Text("Send via") - .font(.headline) - .frame(maxWidth: .infinity, alignment: .leading) - .gridCellColumns(2) - .padding(.top, 6) - } - - GridRow { - Picker("Send via", selection: transportBinding) { - ForEach(SendTransport.allCases, id: \.self) { transport in - Text(transport.displayName).tag(transport) - } - } - .labelsHidden() - .pickerStyle(.segmented) - .gridCellColumns(2) - } - - GridRow { - Text("Folders") - .font(.headline) - .frame(maxWidth: .infinity, alignment: .leading) - .gridCellColumns(2) - .padding(.top, 6) - } - - if model.transport == .airDrop { - GridRow(alignment: .center) { - fieldLabel("Watch folder") - folderValue(path: model.watchFolderURL.path) { - model.chooseWatchFolder() + .frame(minWidth: 54) } } - GridRow(alignment: .center) { - fieldLabel("Output folder") - folderValue(path: model.outboxURL.path) { - model.chooseOutboxFolder() - } - } - } else { - GridRow(alignment: .center) { - fieldLabel("OneDrive folder") - if let folder = model.resolvedOneDriveFolder { - folderValue(path: folder.path) { - model.chooseOneDriveFolder() - } - } else { - // One-line row, same shape as the normal path row: "Not found" - // where the path would be, Choose… stays live. The explanation - // moves to the caption below instead of wrapping this row. - folderValue(path: "Not found") { - model.chooseOneDriveFolder() + Toggle("Ask what to capture on New Session", isOn: askOnNewSessionBinding) + + Text("Window and Browser pick the window under the pointer, with the app named. New Session keeps this session and re-asks for the area.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + + Section("Sending") { + LabeledContent("Send with") { + Picker("Send with", selection: transportBinding) { + ForEach(SendTransport.allCases, id: \.self) { transport in + Text(transport.displayName).tag(transport) } } + .labelsHidden() + .pickerStyle(.segmented) + .frame(maxWidth: 220) } - GridRow { + if model.transport == .airDrop { + LabeledContent("Save PDFs to") { + folderRow(path: model.outboxURL.path) { model.chooseOutboxFolder() } + } + LabeledContent("Watch for returns in") { + folderRow(path: model.watchFolderURL.path) { model.chooseWatchFolder() } + } + } else { + LabeledContent("OneDrive folder") { + folderRow(path: oneDrivePath) { model.chooseOneDriveFolder() } + } Text( model.resolvedOneDriveFolder != nil ? "The PDF is saved here and this same folder is watched for the marked-up copy. On the iPad open it from Files > OneDrive." : "No OneDrive folder found. Sign in to OneDrive, or choose a folder." ) .font(.caption) - .foregroundStyle(.secondary) + .foregroundStyle(model.resolvedOneDriveFolder != nil ? .secondary : .primary) .fixedSize(horizontal: false, vertical: true) - .gridCellColumns(2) } } - GridRow { - Button("Reveal spool folder") { model.openSpoolFolder() } - .gridCellColumns(2) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.top, 4) + Section("Sessions") { + LabeledContent("Delete sessions older than") { + Picker("Delete sessions older than", selection: retentionBinding) { + ForEach(SessionRetention.presets, id: \.self) { preset in + Text(preset.displayName).tag(preset) + } + } + .labelsHidden() + .frame(maxWidth: 150) + } + + LabeledContent(keptSummary) { + Button("Clean Up Now…") { + Task { await model.cleanUpExpiredSessions() } + } + .disabled(model.retention == .never || model.expiredSessionCount == 0) + } + + Text(retentionDetail) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + + Text("Deleting removes Redline's own screenshots only. PDFs you sent stay where they are.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + + Section("Updates") { + Toggle("Install updates automatically", isOn: autoInstallBinding) + + LabeledContent(updateSummary) { + Button(model.isCheckingForUpdates ? "Checking…" : "Check Now") { + model.checkForUpdates() + } + .disabled(model.isCheckingForUpdates) + } + + Text("Updates download in the background and install the next time Redline has no unsent pages. Your area, shortcuts and sessions are kept.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + + if let update = model.updateAvailable { + LabeledContent("Ready to install") { + Button("Restart Now") { model.installUpdate() } + } + Text("Redline \(update.version) is downloaded and waiting.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + + Section { + LabeledContent("Redline \(model.appVersion)") { + Button("Quit Redline") { NSApp.terminate(nil) } + } } } - .padding(16) - .frame(minWidth: 320, idealWidth: 360, maxWidth: 360, alignment: .leading) - .controlSize(.small) + .formStyle(.grouped) + .frame(width: 460, height: 820) + .controlSize(.regular) .onDisappear { disarmHotkeyRecorder() } } + // MARK: - Rows + + private var areaSummary: String { + model.region?.summary ?? "Not chosen" + } + + private var oneDrivePath: String { + model.resolvedOneDriveFolder?.path ?? "Not found" + } + + private var keptSummary: String { + let count = model.pastSessions.count + 1 + return "\(count) session\(count == 1 ? "" : "s") kept" + } + + private func folderRow(path: String, choose: @escaping () -> Void) -> some View { + HStack(spacing: 8) { + Text(abbreviateHome(path)) + .lineLimit(1) + .truncationMode(.middle) + .foregroundStyle(.secondary) + .frame(maxWidth: 150, alignment: .trailing) + .help(path) + Button("Choose…") { choose() } + } + } + + private func abbreviateHome(_ path: String) -> String { + let home = FileManager.default.homeDirectoryForCurrentUser.path + guard path.hasPrefix(home) else { return path } + return "~" + path.dropFirst(home.count) + } + + // MARK: - Detail text + + private var retentionDetail: String { + guard model.retention != .never else { + return "All sessions are kept. Nothing is deleted automatically." + } + let count = model.expiredSessionCount + if count == 0 { + return "No kept session is older than \(model.retention.displayName) yet." + } + return "\(count) session\(count == 1 ? " is" : "s are") already older than \(model.retention.displayName) and will be removed on the next launch or cleanup." + } + + // MARK: - Bindings + + private var scopeBinding: Binding { + Binding( + get: { model.captureScope }, + set: { scope in Task { await model.chooseCaptureScope(scope) } } + ) + } + + private var askOnNewSessionBinding: Binding { + Binding( + get: { model.askWhatToCaptureOnNewSession }, + set: { model.setAskWhatToCaptureOnNewSession($0) } + ) + } + + private var autoInstallBinding: Binding { + Binding( + get: { model.autoInstallUpdates }, + set: { model.setAutoInstallUpdates($0) } + ) + } + + private var updateSummary: String { + let basis = model.updateStatusMessage ?? "Version \(model.appVersion)" + return basis + } + private var transportBinding: Binding { Binding(get: { model.transport }, set: { model.chooseTransport($0) }) } + private var retentionBinding: Binding { + Binding(get: { model.retention }, set: { value in + Task { await model.setRetention(value) } + }) + } + + // MARK: - Hotkey recorder + private func armHotkeyRecorder() { guard !isRecordingHotkey else { return } isRecordingHotkey = true @@ -148,26 +266,6 @@ struct SettingsView: View { recorder.onKey = nil isRecordingHotkey = false } - - private func fieldLabel(_ title: String) -> some View { - Text(title) - .lineLimit(1) - .frame(width: labelWidth, alignment: .trailing) - .gridColumnAlignment(.trailing) - .frame(minHeight: 22, alignment: .trailing) - } - - private func folderValue(path: String, choose: @escaping () -> Void) -> some View { - HStack(spacing: 8) { - Text(path) - .lineLimit(1) - .truncationMode(.middle) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity, alignment: .leading) - Button("Choose…") { choose() } - } - .frame(minHeight: 22) - } } /// Local keyDown monitor for the Settings capture-hotkey recorder. Callbacks hop onto the @@ -213,6 +311,7 @@ extension AppModel: SettingsWindowPresenting { window.title = "Redline Settings" window.styleMask = [.titled, .closable] window.isReleasedWhenClosed = false + window.setContentSize(NSSize(width: 460, height: 820)) window.center() let controller = NSWindowController(window: window) Self.settingsWindowController = controller @@ -224,7 +323,7 @@ extension AppModel: SettingsWindowPresenting { guard let url = chooseDirectory(startingAt: outboxURL) else { return } FolderSettings.setOutbox(url) setFolderURLs(outbox: url, watch: watchFolderURL) - setStatus("Output folder set to \(url.lastPathComponent).") + setStatus("PDFs are saved to \(url.lastPathComponent).") } func chooseWatchFolder() { @@ -234,7 +333,7 @@ extension AppModel: SettingsWindowPresenting { Task { do { try await watcher.updateWatchFolder(url) - setStatus("Watch folder set to \(url.lastPathComponent).") + setStatus("Watching \(url.lastPathComponent) for returns.") } catch { setStatus( (error as? ShotdeckError)?.errorDescription ?? "Could not switch the watch folder." @@ -243,21 +342,13 @@ extension AppModel: SettingsWindowPresenting { } } - /// Settings "Send via" picker action. Persists the choice, recomputes the effective + /// Settings "Send with" picker action. Persists the choice, recomputes the effective /// outbox/watch folder for the new transport, creates the OneDrive folder if it /// doesn't exist yet, and re-points the running watcher (folder + recordUncommented) - /// at the new state. Switching back to AirDrop restores its own stored overrides - /// untouched, since AirDrop and OneDrive folder settings are stored under separate keys. - /// Refuses while a send is in flight (send() snapshots its own folder/transport, but - /// switching mid-send is still confusing UX — nothing to gain by allowing it). - /// The async reconcile below is generation-guarded: `reconcileGeneration` is bumped - /// synchronously before the Task starts, and the Task checks its own snapshot against - /// the live value before every mutating step, so rapid toggling (this function or - /// chooseOneDriveFolder, in any order) always lets the LAST choice win instead of an - /// earlier, superseded call applying its stale folder/flag after a later one already won. - /// The Task's handle is stored in `pendingReconcileTask` so send() can await its - /// completion before snapshotting transport/folder — closing the OTHER race, where a - /// toggle is immediately followed by Send before this reconcile has settled. + /// at the new state. Refuses while a send is in flight. + /// The async reconcile below is generation-guarded so rapid toggling always lets the + /// LAST choice win; its handle is stored in `pendingReconcileTask` so send() can + /// await it before snapshotting transport/folder. func chooseTransport(_ value: SendTransport) { guard !isSending else { setStatus("Finish the current send first.") diff --git a/Sources/Shotdeck/WindowPickerController.swift b/Sources/Shotdeck/WindowPickerController.swift new file mode 100644 index 0000000..321ea23 --- /dev/null +++ b/Sources/Shotdeck/WindowPickerController.swift @@ -0,0 +1,252 @@ +import AppKit +import ShotdeckCore + +/// Hides Redline's own windows while the user is choosing what to capture, then puts +/// them back. The popover would otherwise sit on top of the thing being picked and, +/// worse, end up inside the screenshot. +@MainActor +enum RedlineWindows { + private static var hidden: [NSWindow] = [] + + static func hideForPicking() { + hidden = NSApp.windows.filter { window in + window.isVisible && !(window is RegionPickerWindow) + } + for window in hidden { + window.orderOut(nil) + } + } + + static func restoreAfterPicking() { + for window in hidden where !window.isVisible { + window.orderFront(nil) + } + hidden = [] + } +} + +/// Highlights the window under the pointer and captures the one the user clicks — +/// an app window, a browser window with its active tab, or the whole screen when the +/// pointer is over the desktop. +@MainActor +public final class WindowPickerController { + private var windows: [RegionPickerWindow] = [] + private var monitor: Any? + private var hoverTimer: Timer? + private var completion: (@MainActor (CaptureTarget?) -> Void)? + private var candidates: [WindowCandidate] = [] + private var primaryHeight: CGFloat = 0 + private var hovered: WindowCandidate? + private var hoveredScreen: NSScreen? + + public init() {} + + /// Presents the picker. The completion receives the chosen target, or nil when the + /// user pressed Escape. + public func pick( + onlyBrowsers: Bool = false, + completion: @escaping @MainActor (CaptureTarget?) -> Void + ) { + if self.completion != nil { + finish(target: nil) + } + self.completion = completion + self.primaryHeight = NSScreen.screens.first?.frame.height ?? 0 + + let all = ScreenCapturer.onScreenWindows().filter { candidate in + candidate.layer == 0 + && candidate.ownerBundleID != CaptureTargetResolver.ownBundleID + && candidate.frame.width >= 40 + && candidate.frame.height >= 40 + } + self.candidates = onlyBrowsers + ? all.filter { candidate in + guard let bundle = candidate.ownerBundleID else { return false } + return CaptureTargetResolver.browserBundleIDs.contains(bundle) + } + : all + + presentOverlays() + } + + // MARK: - Overlays + + private func presentOverlays() { + let screens = NSScreen.screens + guard !screens.isEmpty else { + finish(target: nil) + return + } + windows = screens.map { RegionPickerWindow(screen: $0) } + for window in windows { + window.orderFrontRegardless() + } + let mouse = NSEvent.mouseLocation + let keyWindow = windows.first { $0.coveringScreen.frame.contains(mouse) } ?? windows[0] + keyWindow.makeKey() + + // A timer drives the highlight from the real pointer position: mouse-moved + // events are only delivered to the key window, and the overlay must track the + // pointer even over another app's window. + hoverTimer?.invalidate() + hoverTimer = Timer.scheduledTimer(withTimeInterval: 1.0 / 60.0, repeats: true) { + [weak self] _ in + MainActor.assumeIsolated { + self?.updateHover(at: NSEvent.mouseLocation) + } + } + + monitor = NSEvent.addLocalMonitorForEvents( + matching: [.mouseMoved, .leftMouseDown, .keyDown] + ) { [weak self] event in + guard let self else { return event } + let type = event.type + let keyCode: UInt16 = (type == .keyDown) ? event.keyCode : 0 + let locationInWindow = event.locationInWindow + let windowNumber = event.windowNumber + let consume = MainActor.assumeIsolated { + let location = self.globalAppKitLocation( + locationInWindow: locationInWindow, windowNumber: windowNumber) + return self.handle(type: type, keyCode: keyCode, location: location) + } + return consume ? nil : event + } + + updateHover(at: mouse) + } + + private func handle(type: NSEvent.EventType, keyCode: UInt16, location: NSPoint?) -> Bool { + switch type { + case .keyDown: + if keyCode == 53 { // Escape + finish(target: nil) + return true + } + return false + case .mouseMoved: + updateHover(at: location ?? NSEvent.mouseLocation) + return false + case .leftMouseDown: + if let target = targetUnderPointer(at: location ?? NSEvent.mouseLocation) { + finish(target: target) + } + return true + default: + return false + } + } + + // MARK: - Hover + + private func updateHover(at point: NSPoint) { + let screen = NSScreen.screens.first { $0.frame.contains(point) } + let candidate = candidate(at: point) + hovered = candidate + hoveredScreen = screen + + let highlightRect = candidate.map { appKitRect($0.frame) } ?? screen?.frame + let chip: String + if let candidate { + let app = appName(for: candidate) + let title = windowTitle(for: candidate) + chip = title.isEmpty ? app : "\(app) — \(title)" + } else { + chip = "Entire Screen" + } + + for window in windows { + guard let windowScreen = windows.first(where: { $0 === window })?.coveringScreen + else { continue } + guard let highlightRect, windowScreen.frame.intersects(highlightRect) else { + window.updateSelection(localRect: nil, sizeText: nil) + continue + } + let local = CGRect( + x: highlightRect.minX - windowScreen.frame.minX, + y: highlightRect.minY - windowScreen.frame.minY, + width: highlightRect.width, + height: highlightRect.height + ) + window.updateSelection(localRect: local, sizeText: chip) + } + } + + private func targetUnderPointer(at point: NSPoint) -> CaptureTarget? { + if let candidate = candidate(at: point) { + return .window( + windowID: candidate.windowID, + frame: candidate.frame, + displayID: CaptureTargetResolver.displayID(containing: candidate.frame) + ) + } + guard let screen = NSScreen.screens.first(where: { $0.frame.contains(point) }) else { + return nil + } + return .display(displayID: displayID(for: screen)) + } + + private func candidate(at point: NSPoint) -> WindowCandidate? { + candidates.first { candidate in + appKitRect(candidate.frame).contains(point) + } + } + + // MARK: - Geometry and labels + + private func appKitRect(_ cgRect: CGRect) -> CGRect { + CGRect( + x: cgRect.minX, + y: primaryHeight - cgRect.minY - cgRect.height, + width: cgRect.width, + height: cgRect.height + ) + } + + private func displayID(for screen: NSScreen) -> UInt32 { + (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)? + .uint32Value ?? CGMainDisplayID() + } + + private func appName(for candidate: WindowCandidate) -> String { + guard let bundle = candidate.ownerBundleID, + let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundle) + else { return "Window" } + return FileManager.default.displayName(atPath: url.path) + .replacingOccurrences(of: ".app", with: "") + } + + private func windowTitle(for candidate: WindowCandidate) -> String { + guard let raw = CGWindowListCopyWindowInfo([.optionIncludingWindow], candidate.windowID) + as? [[String: Any]], let first = raw.first + else { return "" } + return first[kCGWindowName as String] as? String ?? "" + } + + private func globalAppKitLocation(locationInWindow: NSPoint, windowNumber: Int) -> NSPoint? { + if let window = windows.first(where: { $0.windowNumber == windowNumber }) { + return window.convertPoint(toScreen: locationInWindow) + } + if windowNumber != 0, let window = NSApp.window(withWindowNumber: windowNumber) { + return window.convertPoint(toScreen: locationInWindow) + } + return NSEvent.mouseLocation + } + + // MARK: - Finish + + private func finish(target: CaptureTarget?) { + hoverTimer?.invalidate() + hoverTimer = nil + if let monitor { + NSEvent.removeMonitor(monitor) + } + monitor = nil + for window in windows { + window.orderOut(nil) + } + windows = [] + let completion = self.completion + self.completion = nil + completion?(target) + } +} diff --git a/Sources/Shotdeck/main.swift b/Sources/Shotdeck/main.swift index 3a32799..3d8dcb6 100644 --- a/Sources/Shotdeck/main.swift +++ b/Sources/Shotdeck/main.swift @@ -7,6 +7,12 @@ import ShotdeckCore if ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil { MainActor.assumeIsolated { PanelSnapshot.runIfRequested() } } +if SelfTestLaunch.phase == "e2e" { + MainActor.assumeIsolated { PanelSelfTest.runE2EIfRequested() } +} +if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "panel" { + MainActor.assumeIsolated { PanelSelfTest.runIfRequested() } +} if ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] == "onedrive" { MainActor.assumeIsolated { PickerSelfTest.runOneDriveOnlyIfRequested() } } @@ -75,6 +81,25 @@ final class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { Task { await model.bootstrap() } + // `--window` opens the session window at launch (scripts and demos); a normal + // launch stays quiet in the menu bar. + if CommandLine.arguments.contains("--window") { + presentSessionsWindow() + } + } + + /// Clicking the app in Finder, or `open -a Redline`, while it runs shows the + /// window instead of doing nothing — standard macOS behaviour for a menu-bar app + /// with a main window. + func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows: Bool) -> Bool { + if !hasVisibleWindows { + presentSessionsWindow() + } + return true + } + + private func presentSessionsWindow() { + (model as SessionsWindowPresenting).presentSessionsWindow(focusLane: false) } /// Builds the model exactly the way the real app launches: paths come from @@ -86,10 +111,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate { /// point this at a temp directory instead of the real /// ~/Library/Application Support/Shotdeck — production always calls this with no /// argument (the real root). Internal, not private, for that same reason. - static func makeLaunchModel(appSupportRoot: URL? = nil) -> AppModel { + static func makeLaunchModel( + appSupportRoot: URL? = nil, + retentionDefaults: UserDefaults = .standard + ) -> AppModel { do { let paths = try TransportSettings.resolvedAppSupportPaths(root: appSupportRoot) - return try makeModel(paths: paths) + return try makeModel(paths: paths, retentionDefaults: retentionDefaults) } catch { Log.ui.critical( "AppModel init failed: \(String(describing: error), privacy: .public)" @@ -98,13 +126,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate { 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) + let model = try! makeModel(paths: fallback, retentionDefaults: retentionDefaults) model.setStatus("Redline could not access its storage folder. Captures will not persist.") return model } } - private static func makeModel(paths: AppSupportPaths) throws -> AppModel { + private static func makeModel( + paths: AppSupportPaths, + retentionDefaults: UserDefaults + ) throws -> AppModel { let ledger = try ReturnLedger(paths: paths) return AppModel( paths: paths, @@ -114,7 +145,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { hotkeys: HotkeyCenter(), picker: RegionPickerController(), ledger: ledger, - watcher: ReturnWatcher(paths: paths, ledger: ledger) + watcher: ReturnWatcher(paths: paths, ledger: ledger), + retentionDefaults: retentionDefaults ) } } diff --git a/Sources/ShotdeckCore/Capture/CaptureRegion.swift b/Sources/ShotdeckCore/Capture/CaptureRegion.swift index d5a7ab2..adf544f 100644 --- a/Sources/ShotdeckCore/Capture/CaptureRegion.swift +++ b/Sources/ShotdeckCore/Capture/CaptureRegion.swift @@ -55,4 +55,20 @@ public struct CaptureRegion: Codable, Sendable, Equatable { /// Persisted in UserDefaults under this key BY THE APP (WP-4a), never by this type. public static let defaultsKey = "ai.flowmaster.shotdeck.region" + + /// 1-based position of this region's display in the current screen list; 1 when the + /// display is no longer attached. + public var displayNumber: Int { + let match = NSScreen.screens.firstIndex { screen in + let id = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] + as? NSNumber)?.uint32Value + return id == displayID + } + return (match ?? 0) + 1 + } + + /// "800 × 600 on Display 1" — the line the popover shows under the capture control. + public var summary: String { + String(format: "%.0f × %.0f on Display %d", rect.width, rect.height, displayNumber) + } } diff --git a/Sources/ShotdeckCore/Capture/CaptureScope.swift b/Sources/ShotdeckCore/Capture/CaptureScope.swift new file mode 100644 index 0000000..0efd925 --- /dev/null +++ b/Sources/ShotdeckCore/Capture/CaptureScope.swift @@ -0,0 +1,79 @@ +import Foundation + +/// What a capture takes a picture of. +/// +/// The choice belongs to the session being captured into: it is stored once and copied +/// to the next session, so a review run keeps capturing the same kind of thing until +/// the user says otherwise. Choosing anything other than `.area` never clears the saved +/// area — it comes back when Area is chosen again. +public enum CaptureScope: String, Codable, Sendable, CaseIterable { + case area + case window + case browser + case screen + + /// Label for the segmented control and the window's menu. + public var displayName: String { + switch self { + case .area: return "Area" + case .window: return "Window" + case .browser: return "Browser" + case .screen: return "Screen" + } + } + + /// The longer menu item wording (window picker). + public var menuTitle: String { + switch self { + case .area: return "Saved Area" + case .window: return "Front Window" + case .browser: return "Browser Page" + case .screen: return "Whole Screen" + } + } + + /// Sentence shown under the control: what pressing Capture will take. + public func targetDescription(savedArea: CaptureRegion?) -> String { + switch self { + case .area: + guard let savedArea else { return "No area saved yet — choose one first" } + return savedArea.summary + case .window: + return "The frontmost window when you capture" + case .browser: + return "The frontmost browser window when you capture" + case .screen: + guard let savedArea else { return "The display with the frontmost window" } + return "All of Display \(savedArea.displayNumber)" + } + } +} + +/// Persistence for the capture choice. Stored separately from the chosen area so +/// switching scope never destroys the area. +public enum CaptureSettings { + public static let scopeKey = "ai.flowmaster.shotdeck.captureScope" + public static let askOnNewSessionKey = "ai.flowmaster.shotdeck.askScopeOnNewSession" + + public static func scope(defaults: UserDefaults = .standard) -> CaptureScope { + guard let raw = defaults.string(forKey: scopeKey), + let scope = CaptureScope(rawValue: raw) + else { return .area } + return scope + } + + public static func setScope(_ scope: CaptureScope, defaults: UserDefaults = .standard) { + defaults.set(scope.rawValue, forKey: scopeKey) + } + + /// Whether "New Session…" asks what to capture before starting. Off means it + /// starts immediately with the current choice. + public static func askOnNewSession(defaults: UserDefaults = .standard) -> Bool { + guard defaults.object(forKey: askOnNewSessionKey) != nil else { return true } + return defaults.bool(forKey: askOnNewSessionKey) + } + + public static func setAskOnNewSession(_ value: Bool, defaults: UserDefaults = .standard) { + defaults.set(value, forKey: askOnNewSessionKey) + } +} diff --git a/Sources/ShotdeckCore/Capture/CaptureTargetResolver.swift b/Sources/ShotdeckCore/Capture/CaptureTargetResolver.swift new file mode 100644 index 0000000..faf1c96 --- /dev/null +++ b/Sources/ShotdeckCore/Capture/CaptureTargetResolver.swift @@ -0,0 +1,125 @@ +import CoreGraphics +import Foundation + +/// One on-screen window as the capture resolver sees it. Kept as plain data so the +/// choice logic is testable without a window server. +public struct WindowCandidate: Sendable, Equatable { + public let windowID: UInt32 + public let ownerBundleID: String? + public let ownerPID: Int32 + public let frame: CGRect + public let layer: Int + + public init( + windowID: UInt32, + ownerBundleID: String?, + ownerPID: Int32, + frame: CGRect, + layer: Int + ) { + self.windowID = windowID + self.ownerBundleID = ownerBundleID + self.ownerPID = ownerPID + self.frame = frame + self.layer = layer + } +} + +/// What a capture will take: one region of a display, one whole display, or one window. +public enum CaptureTarget: Sendable, Equatable { + case region(CaptureRegion) + case display(displayID: UInt32) + case window(windowID: UInt32, frame: CGRect, displayID: UInt32) +} + +/// Chooses the capture target for a scope from the windows that are on screen. +/// +/// Candidates arrive front-to-back (the order the window server reports), which is what +/// makes "the front window" well defined. Redline's own windows are never candidates, +/// so choosing Window never captures the app's own panel. +public enum CaptureTargetResolver { + /// Bundles whose front window counts as a browser page. + public static let browserBundleIDs: Set = [ + "com.apple.Safari", + "com.google.Chrome", + "com.google.Chrome.canary", + "com.microsoft.edgemac", + "com.brave.Browser", + "company.thebrowser.Browser", + "org.mozilla.firefox", + "com.vivaldi.Vivaldi", + "com.operasoftware.Opera", + ] + + /// Redline's own bundle identifier — never a capture target. + public static let ownBundleID = "ai.flowmaster.shotdeck" + + public static func resolve( + scope: CaptureScope, + savedArea: CaptureRegion?, + frontmostPID: Int32, + candidates: [WindowCandidate] + ) throws -> CaptureTarget { + let usable = candidates.filter { candidate in + candidate.layer == 0 + && candidate.ownerBundleID != ownBundleID + && candidate.frame.width >= 40 + && candidate.frame.height >= 40 + } + + switch scope { + case .area: + guard let savedArea else { throw ShotdeckError.noRegionRemembered } + return .region(savedArea) + + case .screen: + if let savedArea { + return .display(displayID: savedArea.displayID) + } + guard let window = usable.first else { throw ShotdeckError.noFrontWindow } + return .display(displayID: displayID(containing: window.frame)) + + case .window: + let ownAppFirst = usable.first { $0.ownerPID == frontmostPID } + guard let window = ownAppFirst ?? usable.first else { + throw ShotdeckError.noFrontWindow + } + return .window( + windowID: window.windowID, + frame: window.frame, + displayID: displayID(containing: window.frame) + ) + + case .browser: + guard let window = usable.first(where: { + guard let bundle = $0.ownerBundleID else { return false } + return browserBundleIDs.contains(bundle) + }) else { + throw ShotdeckError.noBrowserWindow + } + return .window( + windowID: window.windowID, + frame: window.frame, + displayID: displayID(containing: window.frame) + ) + } + } + + /// The display whose bounds contain the window's centre; the main display when a + /// window straddles two screens and belongs to neither cleanly. + public static func displayID(containing frame: CGRect) -> UInt32 { + let centre = CGPoint(x: frame.midX, y: frame.midY) + var count: UInt32 = 0 + guard CGGetActiveDisplayList(0, nil, &count) == .success, count > 0 else { + return CGMainDisplayID() + } + var displays = [CGDirectDisplayID](repeating: 0, count: Int(count)) + guard CGGetActiveDisplayList(count, &displays, &count) == .success else { + return CGMainDisplayID() + } + for display in displays.prefix(Int(count)) where CGDisplayBounds(display).contains(centre) { + return display + } + return CGMainDisplayID() + } +} diff --git a/Sources/ShotdeckCore/Capture/ScreenCapturer.swift b/Sources/ShotdeckCore/Capture/ScreenCapturer.swift index b6158fc..c5c06de 100644 --- a/Sources/ShotdeckCore/Capture/ScreenCapturer.swift +++ b/Sources/ShotdeckCore/Capture/ScreenCapturer.swift @@ -18,6 +18,135 @@ public struct ScreenCapturer: Sendable { /// Does NOT prompt. Reports the current Screen Recording grant. public static var isScreenRecordingGranted: Bool { CGPreflightScreenCaptureAccess() } + /// Captures whatever the given scope points at, resolving it right now. + public func capture( + _ scope: CaptureScope, + savedArea: CaptureRegion? + ) async throws -> CapturedImage { + guard Self.isScreenRecordingGranted else { + throw ShotdeckError.screenRecordingNotGranted + } + let frontmostPID = NSWorkspace.shared.frontmostApplication?.processIdentifier ?? 0 + let target = try CaptureTargetResolver.resolve( + scope: scope, + savedArea: savedArea, + frontmostPID: frontmostPID, + candidates: Self.onScreenWindows() + ) + return try await capture(target) + } + + /// Captures one resolved target. A window is captured window-only (so an overlapping + /// window never ends up in a review shot); a region or a display goes through the + /// display path. + public func capture(_ target: CaptureTarget) async throws -> CapturedImage { + guard Self.isScreenRecordingGranted else { + throw ShotdeckError.screenRecordingNotGranted + } + switch target { + case .region(let region): + return try await capture(region) + case .display(let displayID): + let bounds = CGDisplayBounds(displayID) + return try await capture( + CaptureRegion( + displayID: displayID, rect: bounds, + capturedScale: Self.backingScale(for: displayID))) + case .window(let windowID, let frame, let displayID): + return try await captureWindow( + windowID: windowID, frame: frame, displayID: displayID) + } + } + + /// On-screen windows, front-most first, as plain data for the resolver. + public static func onScreenWindows() -> [WindowCandidate] { + guard let raw = CGWindowListCopyWindowInfo( + [.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID + ) as? [[String: Any]] else { return [] } + + return raw.compactMap { entry in + guard let windowID = (entry[kCGWindowNumber as String] as? NSNumber)?.uint32Value, + let ownerPID = (entry[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value, + let boundsDict = entry[kCGWindowBounds as String] as? [String: Any], + let layer = (entry[kCGWindowLayer as String] as? NSNumber)?.intValue + else { return nil } + let frame = CGRect( + x: boundsDict["X"] as? Double ?? 0, + y: boundsDict["Y"] as? Double ?? 0, + width: boundsDict["Width"] as? Double ?? 0, + height: boundsDict["Height"] as? Double ?? 0 + ) + return WindowCandidate( + windowID: windowID, + ownerBundleID: bundleIdentifier(forPID: ownerPID), + ownerPID: ownerPID, + frame: frame, + layer: layer + ) + } + } + + private static func bundleIdentifier(forPID pid: Int32) -> String? { + NSRunningApplication(processIdentifier: pid)?.bundleIdentifier + } + + private static func backingScale(for displayID: UInt32) -> CGFloat { + guard let mode = CGDisplayCopyDisplayMode(displayID), mode.width > 0 else { return 2 } + return CGFloat(mode.pixelWidth) / CGFloat(mode.width) + } + + /// Captures a single window through ScreenCaptureKit's window filter, at the display's + /// backing scale, without the window server compositing anything on top of it. + private func captureWindow( + windowID: UInt32, + frame: CGRect, + displayID: UInt32 + ) async throws -> CapturedImage { + let content: SCShareableContent + do { + content = try await SCShareableContent.excludingDesktopWindows( + false, onScreenWindowsOnly: true) + } catch { + throw ShotdeckError.captureFailed(underlying: error.localizedDescription) + } + guard let window = content.windows.first(where: { $0.windowID == windowID }) else { + throw ShotdeckError.noFrontWindow + } + + let scale = Self.backingScale(for: displayID) + let filter = SCContentFilter(desktopIndependentWindow: window) + let configuration = SCStreamConfiguration() + configuration.width = Int((frame.width * scale).rounded()) + configuration.height = Int((frame.height * scale).rounded()) + configuration.showsCursor = false + configuration.scalesToFit = false + + let cgImage: CGImage + do { + cgImage = try await SCScreenshotManager.captureImage( + contentFilter: filter, configuration: configuration) + } catch { + throw ShotdeckError.captureFailed(underlying: error.localizedDescription) + } + + let data = NSMutableData() + guard let dest = CGImageDestinationCreateWithData( + data, UTType.png.identifier as CFString, 1, nil + ) else { + throw ShotdeckError.captureFailed(underlying: "could not create PNG image destination") + } + CGImageDestinationAddImage(dest, cgImage, nil) + guard CGImageDestinationFinalize(dest) else { + throw ShotdeckError.captureFailed(underlying: "PNG encoding failed to finalize") + } + return CapturedImage( + pngData: data as Data, + pixelWidth: cgImage.width, + pixelHeight: cgImage.height, + scale: scale + ) + } + /// Captures `region` at the display's true backing scale. Throws /// `.screenRecordingNotGranted` when the grant is absent — never requests it. public func capture(_ region: CaptureRegion) async throws -> CapturedImage { diff --git a/Sources/ShotdeckCore/Model/CaptureSession.swift b/Sources/ShotdeckCore/Model/CaptureSession.swift index b61a65d..9093e4f 100644 --- a/Sources/ShotdeckCore/Model/CaptureSession.swift +++ b/Sources/ShotdeckCore/Model/CaptureSession.swift @@ -2,7 +2,7 @@ import Foundation public enum SessionState: String, Codable, Sendable { case open // accepting captures - case archived // closed and kept as a past session (sent or not); pruned by retention + case archived // closed and kept as a past session (sent or not); pruned only by an age policy the user set } /// The manifest persisted as session.json alongside the PNGs. @@ -12,28 +12,39 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable { public private(set) var state: SessionState public private(set) var captures: [Capture] /// Set when the PDF is built, so a re-send reuses the same file. nil on a - /// session that was closed without ever sending — the Past submissions list + /// session that was closed without ever sending — the Past sessions list /// shows that as "Not sent". public private(set) var pdfFileName: String? + /// Lane / deployed build / commit / reviewer / note for this session. Absent from + /// manifests written before v0.5.0 — those decode as `.empty`, never a guess. + public private(set) var context: ReviewContext public init( id: UUID, createdAt: Date, state: SessionState, captures: [Capture], - pdfFileName: String? + pdfFileName: String?, + context: ReviewContext = .empty ) { self.id = id self.createdAt = createdAt self.state = state self.captures = captures self.pdfFileName = pdfFileName + self.context = context } public var isEmpty: Bool { captures.isEmpty } + /// First 8 characters of the UUID, uppercase — the stable short handle used in + /// file names, the session list and the PDF header. + public var shortID: String { + String(id.uuidString.replacingOccurrences(of: "-", with: "").prefix(8)).uppercased() + } + /// max(sequence)+1, or 1 when empty. public var nextSequence: Int { (captures.map(\.sequence).max() ?? 0) + 1 @@ -46,7 +57,8 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable { createdAt: createdAt, state: state, captures: captures + [capture], - pdfFileName: pdfFileName + pdfFileName: pdfFileName, + context: context ) } @@ -58,7 +70,8 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable { createdAt: createdAt, state: state, captures: captures.filter { $0.id != captureID }, - pdfFileName: pdfFileName + pdfFileName: pdfFileName, + context: context ) } @@ -70,7 +83,50 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable { createdAt: createdAt, state: .archived, captures: captures, - pdfFileName: pdfFileName + pdfFileName: pdfFileName, + context: context + ) + } + + /// Value-semantic: returns a new session; does not mutate `self`. + public func withContext(_ newContext: ReviewContext) -> CaptureSession { + CaptureSession( + id: id, + createdAt: createdAt, + state: state, + captures: captures, + pdfFileName: pdfFileName, + context: newContext + ) + } + + /// Value-semantic: returns a new session; does not mutate `self`. + public func withPDFFileName(_ name: String?) -> CaptureSession { + CaptureSession( + id: id, + createdAt: createdAt, + state: state, + captures: captures, + pdfFileName: name, + context: context + ) + } + + private enum CodingKeys: String, CodingKey { + case id, createdAt, state, captures, pdfFileName, context + } + + /// `context` is decoded leniently so every manifest written before v0.5.0 keeps + /// loading; all other keys are required, exactly as before. + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.init( + id: try container.decode(UUID.self, forKey: .id), + createdAt: try container.decode(Date.self, forKey: .createdAt), + state: try container.decode(SessionState.self, forKey: .state), + captures: try container.decode([Capture].self, forKey: .captures), + pdfFileName: try container.decodeIfPresent(String.self, forKey: .pdfFileName), + context: try container.decodeIfPresent(ReviewContext.self, forKey: .context) ?? .empty ) } } diff --git a/Sources/ShotdeckCore/Model/ReviewContext.swift b/Sources/ShotdeckCore/Model/ReviewContext.swift new file mode 100644 index 0000000..a693951 --- /dev/null +++ b/Sources/ShotdeckCore/Model/ReviewContext.swift @@ -0,0 +1,90 @@ +import Foundation + +/// What a review session is ABOUT, recorded once per session and printed on every +/// PDF page plus the PDF's document info, so an annotated page that comes back +/// weeks later still says which lane, build and commit it referred to, who took it +/// and when. +/// +/// Every field is optional in practice (empty string = not recorded); nothing here +/// is invented when the user leaves it blank. `note` is free text. +public struct ReviewContext: Codable, Sendable, Equatable { + /// Hard cap per field: this text ends up on every PDF page, so an unbounded + /// paste must not be able to break the layout. + public static let maxFieldLength = 120 + + public var lane: String + public var deployedVersion: String + public var commit: String + public var reviewer: String + public var note: String + + public init( + lane: String = "", + deployedVersion: String = "", + commit: String = "", + reviewer: String = "", + note: String = "" + ) { + self.lane = Self.cleaned(lane) + self.deployedVersion = Self.cleaned(deployedVersion) + self.commit = Self.cleaned(commit) + self.reviewer = Self.cleaned(reviewer) + self.note = Self.cleaned(note) + } + + public static let empty = ReviewContext() + + /// The macOS account's own name, used to pre-fill `reviewer` on a fresh session. + /// `NSFullUserName()` is empty on a host with no full name set, in which case the + /// short login name identifies the same person. + public static func currentUser() -> String { + let full = NSFullUserName().trimmingCharacters(in: .whitespacesAndNewlines) + if !full.isEmpty { return cleaned(full) } + return cleaned(NSUserName()) + } + + public var isEmpty: Bool { + lane.isEmpty && deployedVersion.isEmpty && commit.isEmpty && reviewer.isEmpty && note.isEmpty + } + + /// "DEV03 · v1.4.2 · a1b2c3d · Ben Hippler" — empty parts are dropped, never + /// replaced with a placeholder. + public var summaryLine: String { + summaryParts.joined(separator: " · ") + } + + /// The individual summary parts in display order, empty ones dropped. + public var summaryParts: [String] { + var parts: [String] = [] + if !lane.isEmpty { parts.append(lane) } + if !deployedVersion.isEmpty { parts.append(deployedVersion) } + if !commit.isEmpty { parts.append(commit) } + if !reviewer.isEmpty { parts.append(reviewer) } + return parts + } + + /// JSON kept tolerant on purpose: an older manifest has no context at all, and a + /// newer one may add fields. Any unknown key is ignored; every known field is + /// optional. + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.init( + lane: try container.decodeIfPresent(String.self, forKey: .lane) ?? "", + deployedVersion: try container.decodeIfPresent(String.self, forKey: .deployedVersion) ?? "", + commit: try container.decodeIfPresent(String.self, forKey: .commit) ?? "", + reviewer: try container.decodeIfPresent(String.self, forKey: .reviewer) ?? "", + note: try container.decodeIfPresent(String.self, forKey: .note) ?? "" + ) + } + + /// Trims, collapses line breaks (the value is drawn on one line) and caps length. + static func cleaned(_ raw: String) -> String { + let collapsed = raw + .replacingOccurrences(of: "\r\n", with: " ") + .replacingOccurrences(of: "\n", with: " ") + .replacingOccurrences(of: "\r", with: " ") + .trimmingCharacters(in: .whitespaces) + guard collapsed.count > maxFieldLength else { return collapsed } + return String(collapsed.prefix(maxFieldLength)) + } +} diff --git a/Sources/ShotdeckCore/Model/ShotdeckError.swift b/Sources/ShotdeckCore/Model/ShotdeckError.swift index ab5b063..92e5687 100644 --- a/Sources/ShotdeckCore/Model/ShotdeckError.swift +++ b/Sources/ShotdeckCore/Model/ShotdeckError.swift @@ -11,6 +11,8 @@ public enum ShotdeckError: Error, LocalizedError, Sendable { case airDropUnavailable case noCommentedReturns case oneDriveFolderUnavailable(path: String) + case noFrontWindow + case noBrowserWindow public var errorDescription: String? { switch self { @@ -34,6 +36,10 @@ public enum ShotdeckError: Error, LocalizedError, Sendable { return "None of the returned PDFs have comments on them." case .oneDriveFolderUnavailable(let path): return "Your OneDrive folder is not available: \(path). Check that OneDrive is signed in, or choose another folder in Settings." + case .noFrontWindow: + return "There is no front window to capture. Click the window you want first, or choose Area." + case .noBrowserWindow: + return "No browser window is open. Open the page you want, or choose Window or Area." } } } diff --git a/Sources/ShotdeckCore/PDF/PDFComposer.swift b/Sources/ShotdeckCore/PDF/PDFComposer.swift index 5fbfbc8..057c819 100644 --- a/Sources/ShotdeckCore/PDF/PDFComposer.swift +++ b/Sources/ShotdeckCore/PDF/PDFComposer.swift @@ -10,12 +10,17 @@ private let pdfLog = Logger(subsystem: "ai.flowmaster.shotdeck", category: "PDF" public struct PDFComposer: Sendable { public init() {} + /// `toolVersion` is the running Redline version (CFBundleShortVersionString) and + /// `composedAt` the build time; both are printed in the page footer and the PDF's + /// document info so a printed or returned page says which tools produced it. @discardableResult public func compose( session: CaptureSession, imageURL: (Capture) -> URL, title: String, - to outputURL: URL + to outputURL: URL, + toolVersion: String = "", + composedAt: Date = Date() ) throws -> Int { if session.isEmpty { throw ShotdeckError.pdfCompositionFailed(reason: "session has no captures") @@ -43,12 +48,18 @@ public struct PDFComposer: Sendable { .deletingLastPathComponent() .appendingPathComponent(".tmp-\(UUID().uuidString)-\(outputURL.lastPathComponent)") + let footerLines = Self.footerLines( + session: session, toolVersion: toolVersion, composedAt: composedAt) + do { try Self.writePDF( loaded: loaded, pageCount: pageCount, title: title, sessionID: session.id, + footerLines: footerLines, + metadata: Self.documentInfo( + session: session, title: title, toolVersion: toolVersion, composedAt: composedAt), to: tmpURL ) @@ -70,8 +81,72 @@ public struct PDFComposer: Sendable { } } - public static func fileName(for _: CaptureSession) -> String { - "Redline-\(DubaiTime.fileStamp(Date())).pdf" + /// `Redline---.pdf` — see `PDFFileName`. + public static func fileName(for session: CaptureSession) -> String { + PDFFileName.make(builtAt: Date(), lane: session.context.lane, sessionID: session.id) + } + + /// Both footer lines for a session, untruncated. Line 1 identifies the document + /// (tool, build time, session); line 2 states what it reviewed (lane, deployed + /// build, commit, reviewer, note). Empty context fields are omitted rather than + /// printed as blanks. + public static func footerLines( + session: CaptureSession, + toolVersion: String, + composedAt: Date + ) -> [String] { + let tool = toolVersion.isEmpty ? "Redline" : "Redline \(toolVersion)" + let first = "\(tool) · \(DubaiTime.stamp(composedAt)) · Session \(session.shortID)" + + let context = session.context + var review: [String] = [] + if !context.lane.isEmpty { review.append("Lane \(context.lane)") } + if !context.deployedVersion.isEmpty { review.append("Deployed \(context.deployedVersion)") } + if !context.commit.isEmpty { review.append("Commit \(context.commit)") } + if !context.reviewer.isEmpty { review.append("Reviewer \(context.reviewer)") } + if !context.note.isEmpty { review.append("Note \(context.note)") } + return review.isEmpty ? [first] : [first, review.joined(separator: " · ")] + } + + /// The PDF document info a reader sees in Preview/Acrobat. The subject stays the + /// session UUID (it is the stable machine handle); everything a person needs to + /// identify the review is in Author/Keywords as well as the page footers. + public static func documentInfo( + session: CaptureSession, + title: String, + toolVersion: String, + composedAt: Date + ) -> [String: Any] { + let context = session.context + // Commas separate keywords in the PDF format itself, so a value containing one + // would silently split into two keywords (and PDF readers return a list + // instead of a string). Strip them from every keyword value. + func keywordValue(_ raw: String) -> String { + raw.replacingOccurrences(of: ",", with: " ") + .split(whereSeparator: \.isWhitespace) + .joined(separator: " ") + } + var keywords: [String] = ["Redline", "session=\(session.shortID)"] + if !context.lane.isEmpty { keywords.append("lane=\(keywordValue(context.lane))") } + if !context.deployedVersion.isEmpty { + keywords.append("deployed=\(keywordValue(context.deployedVersion))") + } + if !context.commit.isEmpty { keywords.append("commit=\(keywordValue(context.commit))") } + if !context.reviewer.isEmpty { keywords.append("reviewer=\(keywordValue(context.reviewer))") } + if !context.note.isEmpty { keywords.append("note=\(keywordValue(context.note))") } + keywords.append("built=\(DubaiTime.keywordStamp(composedAt))") + if !toolVersion.isEmpty { keywords.append("tool=\(toolVersion)") } + + var info: [String: Any] = [ + kCGPDFContextCreator as String: toolVersion.isEmpty ? "Redline" : "Redline \(toolVersion)", + kCGPDFContextTitle as String: title, + kCGPDFContextSubject as String: session.id.uuidString.lowercased(), + kCGPDFContextKeywords as String: keywords.joined(separator: "; "), + ] + if !context.reviewer.isEmpty { + info[kCGPDFContextAuthor as String] = context.reviewer + } + return info } private static func writePDF( @@ -79,17 +154,15 @@ public struct PDFComposer: Sendable { pageCount: Int, title: String, sessionID: UUID, + footerLines: [String], + metadata: [String: Any], to tmpURL: URL ) throws { guard let consumer = CGDataConsumer(url: tmpURL as CFURL) else { throw ShotdeckError.pdfCompositionFailed(reason: "cannot open output location") } - let auxiliaryInfo: [String: Any] = [ - kCGPDFContextCreator as String: "Redline", - kCGPDFContextTitle as String: title, - kCGPDFContextSubject as String: sessionID.uuidString.lowercased(), - ] + let auxiliaryInfo = metadata guard let context = CGContext( consumer: consumer, @@ -105,7 +178,9 @@ public struct PDFComposer: Sendable { for pageIndex in 1...pageCount { let (capture, cgImage) = loaded[pageIndex - 1] - let layout = PageLayout(capture: capture, pageIndex: pageIndex, pageCount: pageCount) + let layout = PageLayout( + capture: capture, pageIndex: pageIndex, pageCount: pageCount, + footerLines: footerLines) context.beginPDFPage(Self.pageInfo(mediaBox: layout.pageRect)) @@ -149,6 +224,17 @@ public struct PDFComposer: Sendable { strokeTickBox(layout.passTickBox, in: context, color: black) strokeTickBox(layout.failTickBox, in: context, color: black) + for (line, origin) in zip(layout.footerLines, layout.footerOrigins) { + drawTruncatedText( + line, + font: layout.footerFont, + color: timestampColor, + at: origin, + maxWidth: layout.footerRect.width, + in: context + ) + } + context.endPDFPage() } @@ -185,6 +271,40 @@ public struct PDFComposer: Sendable { CTLineDraw(line, context) } + /// Draws one footer line, truncated with an ellipsis when it is wider than the + /// page content width — the reference block must never run into the page edge. + private static func drawTruncatedText( + _ string: String, + font: NSFont, + color: CGColor, + at origin: CGPoint, + maxWidth: CGFloat, + in context: CGContext + ) { + let attributes: [CFString: Any] = [ + kCTFontAttributeName: font, + kCTForegroundColorAttributeName: color, + ] + guard let attributed = CFAttributedStringCreate( + nil, string as CFString, attributes as CFDictionary) + else { return } + var line = CTLineCreateWithAttributedString(attributed) + if CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil)) > maxWidth, + let ellipsisAttributed = CFAttributedStringCreate( + nil, "…" as CFString, attributes as CFDictionary) + { + let ellipsis = CTLineCreateWithAttributedString(ellipsisAttributed) + if let truncated = CTLineCreateTruncatedLine( + line, Double(maxWidth), .end, ellipsis) + { + line = truncated + } + } + context.textMatrix = .identity + context.textPosition = origin + CTLineDraw(line, context) + } + private static func strokeTickBox(_ box: CGRect, in context: CGContext, color: CGColor) { let path = CGPath( roundedRect: box, diff --git a/Sources/ShotdeckCore/PDF/PDFFileName.swift b/Sources/ShotdeckCore/PDF/PDFFileName.swift new file mode 100644 index 0000000..85f9a00 --- /dev/null +++ b/Sources/ShotdeckCore/PDF/PDFFileName.swift @@ -0,0 +1,54 @@ +import Foundation + +/// The PDF file-name scheme: +/// +/// Redline---.pdf +/// Redline--.pdf (no lane recorded) +/// +/// * `yyyyMMdd-HHmm` is Dubai wall-clock time (the time the PDF was built) — the +/// file sorts chronologically as plain text on every filesystem. +/// * `LANE` is the upper-cased lane/environment, reduced to A–Z, 0–9 and single +/// dashes ("OMS test lane" → "OMS-TEST-LANE") so the name is safe everywhere. +/// * `SHORTID` is the session's 8-character id, which keeps two lanes in the same +/// minute — and a re-send of the same session — distinguishable and unique. +public enum PDFFileName { + /// Lane token length cap so the whole name stays comfortably short. + public static let laneMaxLength = 24 + + public static func laneSlug(_ lane: String) -> String { + var slug = "" + var pendingDash = false + for character in lane.uppercased() { + if character.isASCII, character.isLetter || character.isNumber { + if pendingDash, !slug.isEmpty { slug.append("-") } + slug.append(character) + pendingDash = false + } else { + pendingDash = true + } + } + let capped = String(slug.prefix(laneMaxLength)) + return capped.hasSuffix("-") ? String(capped.dropLast()) : capped + } + + public static func make(builtAt: Date, lane: String, sessionID: UUID) -> String { + let shortID = String( + sessionID.uuidString.replacingOccurrences(of: "-", with: "").prefix(8) + ).uppercased() + let slug = laneSlug(lane) + var parts = ["Redline", DubaiTime.fileMinuteStamp(builtAt)] + if !slug.isEmpty { parts.append(slug) } + parts.append(shortID) + return parts.joined(separator: "-") + ".pdf" + } + + /// The session folder's own readable label, e.g. "DEV03-4F2A9C1D" — used in the + /// UI only; the on-disk folder name stays the session UUID. + public static func sessionLabel(lane: String, sessionID: UUID) -> String { + let shortID = String( + sessionID.uuidString.replacingOccurrences(of: "-", with: "").prefix(8) + ).uppercased() + let slug = laneSlug(lane) + return slug.isEmpty ? shortID : "\(slug)-\(shortID)" + } +} diff --git a/Sources/ShotdeckCore/PDF/PageLayout.swift b/Sources/ShotdeckCore/PDF/PageLayout.swift index 7cd7dfe..d2d8947 100644 --- a/Sources/ShotdeckCore/PDF/PageLayout.swift +++ b/Sources/ShotdeckCore/PDF/PageLayout.swift @@ -15,6 +15,12 @@ public struct PageLayout: Sendable, Equatable { public let timestampText: String public let timestampOrigin: CGPoint + /// Reference block under the image (up to two lines): who, when, which lane, + /// which deployed build and commit. Empty when the caller passes no lines. + public let footerRect: CGRect + public let footerLines: [String] + public let footerOrigins: [CGPoint] + public let passLabelOrigin: CGPoint public let failLabelOrigin: CGPoint public let passTickBox: CGRect @@ -25,10 +31,13 @@ public struct PageLayout: Sendable, Equatable { public var pageNumberFont: NSFont { NSFont.systemFont(ofSize: 9, weight: .semibold) } public var timestampFont: NSFont { NSFont.systemFont(ofSize: 9, weight: .regular) } public var tickLabelFont: NSFont { NSFont.systemFont(ofSize: 8, weight: .semibold) } + public var footerFont: NSFont { NSFont.systemFont(ofSize: 7.5, weight: .regular) } private static let marginAll: CGFloat = 18 private static let headerHeight: CGFloat = 26 private static let headerImageGap: CGFloat = 10 + private static let footerLineHeight: CGFloat = 9.5 + private static let footerImageGap: CGFloat = 7 private static let tickBoxSize: CGFloat = 13 private static let tickGroupGap: CGFloat = 8 private static let portraitPage = CGSize(width: 595, height: 842) @@ -36,10 +45,13 @@ public struct PageLayout: Sendable, Equatable { /// `pageIndex` and `pageCount` are 1-based / total, over ACTUALLY-WRITTEN pages /// (see SPEC decision D-D), not `capture.sequence` / `session.captures.count`. - public init(capture: Capture, pageIndex: Int, pageCount: Int) { + /// `footerLines` is the pre-truncated reference block; an empty array keeps the + /// image area exactly as it was before the footer existed. + public init(capture: Capture, pageIndex: Int, pageCount: Int, footerLines: [String] = []) { let pageNumberFont = NSFont.systemFont(ofSize: 9, weight: .semibold) let timestampFont = NSFont.systemFont(ofSize: 9, weight: .regular) let tickLabelFont = NSFont.systemFont(ofSize: 8, weight: .semibold) + let footerLabelFont = NSFont.systemFont(ofSize: 7.5, weight: .regular) isLandscape = capture.isLandscape pageRect = CGRect(origin: .zero, size: isLandscape ? Self.landscapePage : Self.portraitPage) @@ -59,11 +71,23 @@ public struct PageLayout: Sendable, Equatable { height: Self.headerHeight ) - imageBoxRect = CGRect( + self.footerLines = footerLines + let footerHeight = footerLines.isEmpty + ? 0 + : CGFloat(footerLines.count) * Self.footerLineHeight + footerRect = CGRect( x: contentMinX, y: contentMinY, width: contentWidth, - height: headerRect.minY - Self.headerImageGap - contentMinY + height: footerHeight + ) + let imageBoxMinY = contentMinY + (footerLines.isEmpty ? 0 : footerHeight + Self.footerImageGap) + + imageBoxRect = CGRect( + x: contentMinX, + y: imageBoxMinY, + width: contentWidth, + height: headerRect.minY - Self.headerImageGap - imageBoxMinY ) let pointSize = CGSize( @@ -91,6 +115,22 @@ public struct PageLayout: Sendable, Equatable { let descent = CTFontGetDescent(metricsFont) let baselineY = headerRect.minY + (headerRect.height - (ascent + descent)) / 2 + descent + // Footer baselines, top line first, using the footer font's own descent. + let footerMetrics = footerLabelFont as CTFont + let footerAscent = CTFontGetAscent(footerMetrics) + let footerDescent = CTFontGetDescent(footerMetrics) + let footerLeading = Self.footerLineHeight + var origins: [CGPoint] = [] + origins.reserveCapacity(footerLines.count) + for index in footerLines.indices { + let lineBottom = footerRect.maxY - CGFloat(index + 1) * footerLeading + origins.append(CGPoint( + x: footerRect.minX, + y: lineBottom + max(0, (footerLeading - (footerAscent + footerDescent)) / 2) + footerDescent + )) + } + footerOrigins = origins + pageNumberText = "\(pageIndex) / \(pageCount)" pageNumberOrigin = CGPoint(x: headerRect.minX, y: baselineY) @@ -135,6 +175,9 @@ public struct PageLayout: Sendable, Equatable { && lhs.pageNumberOrigin == rhs.pageNumberOrigin && lhs.timestampText == rhs.timestampText && lhs.timestampOrigin == rhs.timestampOrigin + && lhs.footerRect == rhs.footerRect + && lhs.footerLines == rhs.footerLines + && lhs.footerOrigins == rhs.footerOrigins && lhs.passLabelOrigin == rhs.passLabelOrigin && lhs.failLabelOrigin == rhs.failLabelOrigin && lhs.passTickBox == rhs.passTickBox diff --git a/Sources/ShotdeckCore/Spool/SpoolStore.swift b/Sources/ShotdeckCore/Spool/SpoolStore.swift index 5ceff82..a6b025d 100644 --- a/Sources/ShotdeckCore/Spool/SpoolStore.swift +++ b/Sources/ShotdeckCore/Spool/SpoolStore.swift @@ -4,24 +4,26 @@ import CoreGraphics import Darwin public actor SpoolStore { - /// How many archived sessions (past submissions) are kept on disk. Ben's - /// retention rule (2026-10-11): "by default, retain the past 10 sessions" — - /// older session folders are removed from `archive/` once this is exceeded. - /// Any PDF a pruned session produced is not touched: it lives in the outbox - /// (or the OneDrive folder) it was sent to. - public static let defaultRetainedSessionCount = 10 - private let paths: AppSupportPaths private var openSession: CaptureSession + /// The user's age limit for kept sessions. `.never` (the default) means every + /// session is kept: nothing is deleted until an age limit is chosen in Settings. + private var retention: SessionRetention - public init(paths: AppSupportPaths) throws { + public init(paths: AppSupportPaths, retention: SessionRetention = .never) throws { self.paths = paths + self.retention = retention let fm = FileManager.default try Self.supersedeSpoolArchiveOverlaps(paths: paths, fileManager: fm) try Self.finishInterruptedArchives(paths: paths, fileManager: fm) let remainingIDs = try Self.listUUIDDirectories(in: paths.spool, fileManager: fm) if remainingIDs.isEmpty { - self.openSession = try Self.createFreshSession(paths: paths) + // A brand-new store: the reviewer is this Mac's user, so a session taken + // now records who took it without the user typing anything. Lane, build + // and commit stay empty until the user states them. + self.openSession = try Self.createFreshSession( + paths: paths, + context: ReviewContext(reviewer: ReviewContext.currentUser())) } else { var candidates: [CaptureSession] = [] for id in remainingIDs { @@ -34,6 +36,31 @@ public actor SpoolStore { } } + /// Applies a new age limit to future archive/launch prunes. Does not delete + /// anything itself — a caller that just changed the setting calls + /// `pruneExpiredSessions()` when the user asked for a cleanup. + public func setRetention(_ value: SessionRetention) { + retention = value + } + + /// The age limit this store is currently enforcing. + public func configuredRetention() -> SessionRetention { + retention + } + + /// Records the review context (lane / deployed build / commit / reviewer / note) + /// on the open session and persists it in the manifest before returning. Fails + /// loudly if the manifest cannot be written — the in-memory session is only + /// updated after the durable write succeeds. + public func setContext(_ context: ReviewContext) throws -> CaptureSession { + let open = try ensureOpenSession() + let updated = open.withContext(context) + try AtomicFile.writeJSON( + updated, to: paths.sessionDirectory(open.id).appendingPathComponent("session.json")) + openSession = updated + return updated + } + /// The session currently accepting captures. Cheap accessor — all reconciliation already /// happened once, inside init. A truth guard: if the stored session is no longer really /// open on disk (its directory was archived away and the replacement session could not @@ -54,7 +81,7 @@ public actor SpoolStore { let staleID = openSession.id.uuidString Log.spool.error( "The stored open session \(staleID, privacy: .public) is not really open on disk; starting a fresh one.") - let fresh = try Self.createFreshSession(paths: paths) + let fresh = try Self.createFreshSession(paths: paths, context: openSession.context) openSession = fresh return fresh } @@ -86,10 +113,9 @@ public actor SpoolStore { /// D-11: moves the capture's PNG into `/removed/` (created lazily) and drops /// its manifest entry. NEVER unlinks/deletes a user PNG on this path. Throws (no /// filesystem change) if `captureID` is not present in the open session. - /// (Session retention is the one place that removes files: when a session falls - /// outside the newest `defaultRetainedSessionCount`, its WHOLE folder — including - /// `removed/` — is pruned. That is the requested retention policy (Ben, 2026-10-11), - /// not this remove path.) + /// (The one place that removes files is the age limit the user chose in Settings: + /// when a session is older than that limit, its WHOLE folder — including + /// `removed/` — is pruned. Nothing is pruned while the limit is "Never".) public func remove(captureID: UUID) throws -> CaptureSession { let open = try ensureOpenSession() guard let capture = open.captures.first(where: { $0.id == captureID }) else { @@ -129,7 +155,7 @@ public actor SpoolStore { underlying: "cannot archive an empty session") } let archived = try moveOpenSessionToArchive(open.markArchived(pdfFileName: pdfFileName)) - openSession = try Self.createFreshSession(paths: paths) + openSession = try Self.createFreshSession(paths: paths, context: open.context) applyRetention() return archived } @@ -141,31 +167,46 @@ public actor SpoolStore { /// the Past submissions list shows as "Not sent"). An empty open session is /// simply replaced — there is nothing to keep. Returns the archived session, or /// nil when the open session was empty. + /// + /// The new session inherits the closed session's review context: one review run + /// spans several sessions in the same lane and build, so retyping it each time + /// would only add errors. public func closeCurrentSession() throws -> CaptureSession? { let open = try ensureOpenSession() guard !open.isEmpty else { - openSession = try Self.createFreshSession(paths: paths) + openSession = try Self.createFreshSession(paths: paths, context: open.context) return nil } let archived = try moveOpenSessionToArchive( open.markArchived(pdfFileName: open.pdfFileName)) - openSession = try Self.createFreshSession(paths: paths) + openSession = try Self.createFreshSession(paths: paths, context: open.context) applyRetention() return archived } - /// Keeps the newest `limit` archived sessions and removes the rest of the session - /// folders from archive/ (the single folder all sessions live in). Returns the - /// removed ids. Only UUID session folders directly under archive/ are ever - /// touched — never spool/, never anything else. This is the requested retention - /// policy (Ben, 2026-10-11: "retain the past 10 sessions"): a session folder - /// dropped here is gone for good, while any PDF it produced stays in the - /// outbox/OneDrive folder it was sent to. - public func pruneArchivedSessions(keeping limit: Int) throws -> [UUID] { - let sessions = try archivedSessions() - guard sessions.count > limit else { return [] } + /// Removes archived sessions created before the current age limit's cutoff and + /// returns their ids. With `.never` this removes nothing and returns `[]`, so + /// "keep everything" needs no separate code path. Only UUID session folders + /// directly under archive/ are ever touched — never spool/, never a PDF. + public func pruneExpiredSessions(now: Date = Date()) throws -> [UUID] { + guard let cutoff = retention.cutoff(now: now) else { return [] } + return try removeArchivedSessions(createdBefore: cutoff) + } + + /// The ids `pruneExpiredSessions()` would remove right now — what Settings shows + /// before the user commits to a cleanup. Empty under `.never`. + public func expiredSessionIDs(now: Date = Date()) throws -> [UUID] { + guard let cutoff = retention.cutoff(now: now) else { return [] } + return try archivedSessions().filter { $0.createdAt < cutoff }.map(\.id) + } + + /// Deletes the archived session folders created before `cutoff` and returns their + /// ids. Only archive/ is scanned, so an open session can never match. + private func removeArchivedSessions(createdBefore cutoff: Date) throws -> [UUID] { + let expired = try archivedSessions().filter { $0.createdAt < cutoff } + guard !expired.isEmpty else { return [] } var removed: [UUID] = [] - for session in sessions.dropFirst(limit) { + for session in expired { let dir = paths.archiveDirectory(session.id) do { try FileManager.default.removeItem(at: dir) @@ -177,26 +218,23 @@ public actor SpoolStore { removed.append(session.id) } try AtomicFile.fsyncDirectory(at: paths.archive) + Log.spool.warning( + "Session retention (\(self.retention.displayName, privacy: .public)): removed \(removed.count, privacy: .public) archived session(s) older than \(DubaiTime.stamp(cutoff), privacy: .public).") return removed } /// The retention policy every archive path funnels through, so it can never be - /// forgotten: sessions over the default count are pruned. A retention failure is - /// logged loudly (with the exact path) and never thrown — the archive it follows - /// already succeeded, and converting a completed send into a reported failure - /// would be a lie (the safe direction of a failed prune is keeping too much, never - /// losing data). The visible symptom of a failed prune is simply more than 10 - /// sessions in the Past submissions list. + /// forgotten. A retention failure is logged loudly (with the exact path) and + /// never thrown — the archive it follows already succeeded, and converting a + /// completed send into a reported failure would be a lie (the safe direction of a + /// failed prune is keeping too much, never losing data). The visible symptom of a + /// failed prune is simply an old session still in the Past sessions list. private func applyRetention() { do { - let removed = try pruneArchivedSessions(keeping: Self.defaultRetainedSessionCount) - if !removed.isEmpty { - Log.spool.warning( - "Session retention: removed \(removed.count, privacy: .public) archived session(s) beyond the newest \(Self.defaultRetainedSessionCount, privacy: .public).") - } + _ = try pruneExpiredSessions() } catch { Log.spool.error( - "Session retention failed — past sessions were kept beyond \(Self.defaultRetainedSessionCount, privacy: .public): \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription, privacy: .public)") + "Session retention failed — expired sessions were kept: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription, privacy: .public)") } } @@ -224,7 +262,7 @@ public actor SpoolStore { path: paths.sessionDirectory(open.id).path, underlying: "cannot start a new session: \(open.captures.count) capture(s) present in the open session") } - let fresh = try Self.createFreshSession(paths: paths) + let fresh = try Self.createFreshSession(paths: paths, context: open.context) openSession = fresh return fresh } @@ -389,7 +427,8 @@ public actor SpoolStore { createdAt: session.createdAt, state: session.state, captures: finalCaptures, - pdfFileName: session.pdfFileName) + pdfFileName: session.pdfFileName, + context: session.context) try AtomicFile.writeJSON(updated, to: manifestURL) Log.spool.warning("Reconciled session \(id.uuidString, privacy: .public): dropped \(missingCount) missing PNG(s), recovered \(recoveredOrphans.count) orphan(s).") return updated @@ -474,7 +513,10 @@ public actor SpoolStore { } } - private static func createFreshSession(paths: AppSupportPaths) throws -> CaptureSession { + private static func createFreshSession( + paths: AppSupportPaths, + context: ReviewContext + ) throws -> CaptureSession { let id = UUID() let createdAt = Date() let dir = paths.sessionDirectory(id) @@ -483,7 +525,9 @@ public actor SpoolStore { } catch { throw ShotdeckError.spoolWriteFailed(path: dir.path, underlying: error.localizedDescription) } - let session = CaptureSession(id: id, createdAt: createdAt, state: .open, captures: [], pdfFileName: nil) + let session = CaptureSession( + id: id, createdAt: createdAt, state: .open, captures: [], pdfFileName: nil, + context: context) try AtomicFile.writeJSON(session, to: dir.appendingPathComponent("session.json")) return session } diff --git a/Sources/ShotdeckCore/Support/DubaiTime.swift b/Sources/ShotdeckCore/Support/DubaiTime.swift index 2923f1f..deeef79 100644 --- a/Sources/ShotdeckCore/Support/DubaiTime.swift +++ b/Sources/ShotdeckCore/Support/DubaiTime.swift @@ -3,7 +3,11 @@ import Foundation public enum DubaiTime { private static let stampFormatter = LockedDateFormatter(dateFormat: "d MMM yyyy, HH:mm 'Dubai'") private static let fileStampFormatter = LockedDateFormatter(dateFormat: "yyyyMMdd-HHmmss") + private static let fileMinuteStampFormatter = LockedDateFormatter(dateFormat: "yyyyMMdd-HHmm") private static let checkTimeFormatter = LockedDateFormatter(dateFormat: "HH:mm 'Dubai'") + private static let shortStampFormatter = LockedDateFormatter(dateFormat: "d MMM yyyy, HH:mm") + private static let dayStampFormatter = LockedDateFormatter(dateFormat: "d MMM yyyy") + private static let keywordStampFormatter = LockedDateFormatter(dateFormat: "yyyy-MM-dd HH:mm 'Dubai'") public static func stamp(_ date: Date) -> String { stampFormatter.string(from: date) @@ -13,6 +17,28 @@ public enum DubaiTime { fileStampFormatter.string(from: date) } + /// `yyyyMMdd-HHmm` — used in PDF file names where minutes are the useful detail. + public static func fileMinuteStamp(_ date: Date) -> String { + fileMinuteStampFormatter.string(from: date) + } + + /// "31 Oct 2026, 10:31" — compact session-list timestamp (the timezone is stated + /// once in the list header, not on every row). + public static func shortStamp(_ date: Date) -> String { + shortStampFormatter.string(from: date) + } + + /// "31 Oct 2026" — for day-granular expiry notices. + public static func dayStamp(_ date: Date) -> String { + dayStampFormatter.string(from: date) + } + + /// "2026-10-31 11:00 Dubai" — for PDF keywords, where a comma would be read as a + /// keyword separator by the PDF format itself. + public static func keywordStamp(_ date: Date) -> String { + keywordStampFormatter.string(from: date) + } + public static func checkTime(_ date: Date) -> String { checkTimeFormatter.string(from: date) } diff --git a/Sources/ShotdeckCore/Support/RetentionSettings.swift b/Sources/ShotdeckCore/Support/RetentionSettings.swift new file mode 100644 index 0000000..df6a680 --- /dev/null +++ b/Sources/ShotdeckCore/Support/RetentionSettings.swift @@ -0,0 +1,69 @@ +import Foundation + +/// How long Redline keeps a past session's captured screenshots. +/// +/// The default is `.never`: every session is saved and nothing is deleted unless the +/// user picks an age limit in Settings. Session folders are the only thing an age +/// policy ever removes — a PDF that was already sent stays in the folder it went to. +public enum SessionRetention: Sendable, Equatable, Hashable { + case never + case days(Int) + + /// The one list Settings offers, in display order. `nil` day counts never expire. + public static let presets: [SessionRetention] = [ + .never, .days(7), .days(14), .days(30), .days(90), .days(180), .days(365), + ] + + public var dayCount: Int? { + switch self { + case .never: return nil + case .days(let count): return count + } + } + + /// "Never (default)", "7 days", "30 days", "1 year". + public var displayName: String { + switch self { + case .never: return "Never (default)" + case .days(365): return "1 year" + case .days(let count): return "\(count) days" + } + } + + /// Caption for the Settings row and the panel footer: what actually happens. + public var policyDescription: String { + switch self { + case .never: return "All sessions kept." + case .days(365): return "Sessions older than 1 year are deleted." + case .days(let count): return "Sessions older than \(count) days are deleted." + } + } + + /// Sessions created before this instant are expired; nil means nothing expires. + public func cutoff(now: Date = Date()) -> Date? { + guard let dayCount else { return nil } + return Calendar(identifier: .gregorian).date(byAdding: .day, value: -dayCount, to: now) + } +} + +/// Persistence for the age limit, backed by UserDefaults. +/// +/// Stored as a day count; 0 (or no stored value at all) means `never`. A stored value +/// is only ever written by `save`, so an absent key is the honest "user never chose" +/// state, not a hidden default. +public enum RetentionSettings { + public static let defaultsKey = "ai.flowmaster.shotdeck.sessionRetentionDays" + + public static func load(defaults: UserDefaults = .standard) -> SessionRetention { + guard let stored = defaults.object(forKey: defaultsKey) as? Int else { return .never } + return stored > 0 ? .days(stored) : .never + } + + public static func save(_ value: SessionRetention, defaults: UserDefaults = .standard) { + guard let dayCount = value.dayCount else { + defaults.removeObject(forKey: defaultsKey) + return + } + defaults.set(dayCount, forKey: defaultsKey) + } +} diff --git a/Sources/ShotdeckCore/Support/UpdateSettings.swift b/Sources/ShotdeckCore/Support/UpdateSettings.swift new file mode 100644 index 0000000..44bac3d --- /dev/null +++ b/Sources/ShotdeckCore/Support/UpdateSettings.swift @@ -0,0 +1,19 @@ +import Foundation + +/// Whether Redline installs a staged update by itself. +/// +/// On by default: updates download in the background and install the next time the app +/// has nothing unsent, so the tool stays current without anyone chasing a menu row. +/// Off means the staged update waits for the "Update to X" action. +public enum UpdateSettings { + public static let autoInstallKey = "ai.flowmaster.shotdeck.autoInstallUpdates" + + public static func autoInstall(defaults: UserDefaults = .standard) -> Bool { + guard defaults.object(forKey: autoInstallKey) != nil else { return true } + return defaults.bool(forKey: autoInstallKey) + } + + public static func setAutoInstall(_ value: Bool, defaults: UserDefaults = .standard) { + defaults.set(value, forKey: autoInstallKey) + } +} diff --git a/Tests/ShotdeckCoreTests/CaptureScopeTests.swift b/Tests/ShotdeckCoreTests/CaptureScopeTests.swift new file mode 100644 index 0000000..035ed4f --- /dev/null +++ b/Tests/ShotdeckCoreTests/CaptureScopeTests.swift @@ -0,0 +1,165 @@ +import CoreGraphics +import Foundation +import ShotdeckCore +import Testing + +// Which window a capture takes, for each scope — pure logic over the window list the +// window server reports, so it is testable without a display session. + +private func window( + id: UInt32, + bundle: String?, + pid: Int32 = 100, + frame: CGRect = CGRect(x: 100, y: 100, width: 800, height: 600), + layer: Int = 0 +) -> WindowCandidate { + WindowCandidate( + windowID: id, ownerBundleID: bundle, ownerPID: pid, frame: frame, layer: layer) +} + +@Test +func windowScopeTakesTheFrontWindowOfTheFrontApp() throws { + let candidates = [ + window(id: 1, bundle: "com.apple.Safari", pid: 10), + window(id: 2, bundle: "com.apple.Terminal", pid: 20), + ] + let target = try CaptureTargetResolver.resolve( + scope: .window, savedArea: nil, frontmostPID: 20, candidates: candidates) + guard case .window(let id, _, _) = target else { + Issue.record("expected a window target, got \(target)") + return + } + #expect(id == 2) +} + +@Test +func windowScopeFallsBackToTheFrontmostWindowOfAnyApp() throws { + let candidates = [ + window(id: 1, bundle: "com.apple.Safari", pid: 10), + window(id: 2, bundle: "com.apple.Terminal", pid: 20), + ] + let target = try CaptureTargetResolver.resolve( + scope: .window, savedArea: nil, frontmostPID: 99, candidates: candidates) + guard case .window(let id, _, _) = target else { + Issue.record("expected a window target, got \(target)") + return + } + #expect(id == 1) +} + +@Test +func redlineNeverCapturesItself() throws { + let candidates = [ + window(id: 1, bundle: CaptureTargetResolver.ownBundleID, pid: 5), + window(id: 2, bundle: "com.apple.Safari", pid: 10), + ] + let target = try CaptureTargetResolver.resolve( + scope: .window, savedArea: nil, frontmostPID: 5, candidates: candidates) + guard case .window(let id, _, _) = target else { + Issue.record("expected a window target, got \(target)") + return + } + #expect(id == 2) +} + +@Test +func chromeAndDesktopWindowsAreNotCandidates() throws { + let candidates = [ + window(id: 1, bundle: "com.apple.dock", layer: 20), + window(id: 2, bundle: "com.apple.WindowManager", layer: 8), + window(id: 3, bundle: "com.apple.Safari"), + ] + let target = try CaptureTargetResolver.resolve( + scope: .window, savedArea: nil, frontmostPID: 0, candidates: candidates) + guard case .window(let id, _, _) = target else { + Issue.record("expected a window target, got \(target)") + return + } + #expect(id == 3) +} + +@Test +func tinyWindowsAreIgnored() throws { + let candidates = [ + window(id: 1, bundle: "com.apple.Safari", frame: CGRect(x: 0, y: 0, width: 20, height: 20)), + window(id: 2, bundle: "com.apple.Terminal"), + ] + let target = try CaptureTargetResolver.resolve( + scope: .window, savedArea: nil, frontmostPID: 0, candidates: candidates) + guard case .window(let id, _, _) = target else { + Issue.record("expected a window target, got \(target)") + return + } + #expect(id == 2) +} + +@Test +func browserScopeTakesTheFrontBrowserWindow() throws { + let candidates = [ + window(id: 1, bundle: "com.apple.Terminal", pid: 10), + window(id: 2, bundle: "com.google.Chrome", pid: 11), + window(id: 3, bundle: "com.apple.Safari", pid: 12), + ] + let target = try CaptureTargetResolver.resolve( + scope: .browser, savedArea: nil, frontmostPID: 10, candidates: candidates) + guard case .window(let id, _, _) = target else { + Issue.record("expected a window target, got \(target)") + return + } + #expect(id == 2) +} + +@Test +func browserScopeSaysSoWhenNoBrowserIsOpen() { + let candidates = [window(id: 1, bundle: "com.apple.Terminal")] + #expect(throws: ShotdeckError.self) { + _ = try CaptureTargetResolver.resolve( + scope: .browser, savedArea: nil, frontmostPID: 10, candidates: candidates) + } +} + +@Test +func windowScopeSaysSoWhenThereIsNoWindow() { + #expect(throws: ShotdeckError.self) { + _ = try CaptureTargetResolver.resolve( + scope: .window, savedArea: nil, frontmostPID: 10, + candidates: [window(id: 1, bundle: "com.apple.dock", layer: 20)]) + } +} + +@Test +func areaScopeUsesTheSavedAreaAndSaysWhenThereIsNone() throws { + let area = CaptureRegion( + displayID: CGMainDisplayID(), rect: CGRect(x: 10, y: 20, width: 300, height: 200), + capturedScale: 2) + let target = try CaptureTargetResolver.resolve( + scope: .area, savedArea: area, frontmostPID: 0, candidates: []) + #expect(target == .region(area)) + + #expect(throws: ShotdeckError.self) { + _ = try CaptureTargetResolver.resolve( + scope: .area, savedArea: nil, frontmostPID: 0, candidates: []) + } +} + +@Test +func screenScopeUsesTheAreaDisplay() throws { + let area = CaptureRegion( + displayID: CGMainDisplayID(), rect: CGRect(x: 10, y: 20, width: 300, height: 200), + capturedScale: 2) + let target = try CaptureTargetResolver.resolve( + scope: .screen, savedArea: area, frontmostPID: 0, candidates: []) + #expect(target == .display(displayID: area.displayID)) +} + +@Test +func captureScopeDescriptionsNameWhatWillBeTaken() { + let area = CaptureRegion( + displayID: CGMainDisplayID(), rect: CGRect(x: 0, y: 0, width: 800, height: 600), + capturedScale: 2) + #expect(CaptureScope.area.targetDescription(savedArea: area).contains("800 × 600")) + #expect(CaptureScope.area.targetDescription(savedArea: nil).contains("No area")) + #expect(CaptureScope.window.targetDescription(savedArea: area).contains("frontmost window")) + #expect(CaptureScope.browser.targetDescription(savedArea: area).contains("browser")) + #expect(CaptureScope.screen.targetDescription(savedArea: area).contains("Display")) +} diff --git a/Tests/ShotdeckCoreTests/PDFComposerTests.swift b/Tests/ShotdeckCoreTests/PDFComposerTests.swift index 0b3987c..e1c8a9b 100644 --- a/Tests/ShotdeckCoreTests/PDFComposerTests.swift +++ b/Tests/ShotdeckCoreTests/PDFComposerTests.swift @@ -203,17 +203,123 @@ private func pixelWindow( return (pixelX0, pixelY0, pixelX1, pixelY1) } -@Test("fileName uses compose time, not session.createdAt, and matches Redline-yyyyMMdd-HHmmss.pdf") +@Test("fileName is Redline-yyyyMMdd-HHmm-SHORTID.pdf and uses compose time") func fileNameUsesComposeTimeNotSessionCreatedAt() { let old = Date(timeIntervalSince1970: 1_600_000_000) // 2020-09-13 let session = makeSession(captures: [], createdAt: old) let name = PDFComposer.fileName(for: session) - #expect(name.wholeMatch(of: /^Redline-\d{8}-\d{6}\.pdf$/) != nil) - #expect(!name.contains(DubaiTime.fileStamp(old))) - let today = String(DubaiTime.fileStamp(Date()).prefix(8)) + #expect(name.wholeMatch(of: /^Redline-\d{8}-\d{4}-[0-9A-F]{8}\.pdf$/) != nil) + #expect(name.contains(session.shortID)) + #expect(!name.contains(DubaiTime.fileMinuteStamp(old))) + let today = String(DubaiTime.fileMinuteStamp(Date()).prefix(8)) #expect(name.contains(today)) } +@Test("fileName carries the lane slug between the timestamp and the session id") +func fileNameCarriesTheLaneSlug() { + let session = CaptureSession( + id: UUID(uuidString: "4f2a9c1d-0000-4000-8000-000000000000")!, + createdAt: fixtureDate, + state: .open, + captures: [], + pdfFileName: nil, + context: ReviewContext(lane: "OMS test lane")) + let name = PDFComposer.fileName(for: session) + #expect(name.wholeMatch(of: /^Redline-\d{8}-\d{4}-OMS-TEST-LANE-4F2A9C1D\.pdf$/) != nil) +} + +@Test("Review footer lines state the tool, date, session and the recorded review details") +func footerLinesStateTheReviewDetails() { + let session = CaptureSession( + id: UUID(uuidString: "4f2a9c1d-0000-4000-8000-000000000000")!, + createdAt: fixtureDate, + state: .open, + captures: [], + pdfFileName: nil, + context: ReviewContext( + lane: "dev03", deployedVersion: "v1.4.2 (41)", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "checkout")) + let lines = PDFComposer.footerLines( + session: session, toolVersion: "0.5.0", composedAt: fixtureDate) + #expect(lines.count == 2) + #expect(lines[0].contains("Redline 0.5.0")) + #expect(lines[0].contains("Session 4F2A9C1D")) + #expect(lines[0].contains(DubaiTime.stamp(fixtureDate))) + #expect(lines[1].contains("Lane dev03")) + #expect(lines[1].contains("Deployed v1.4.2 (41)")) + #expect(lines[1].contains("Commit a1b2c3d4")) + #expect(lines[1].contains("Reviewer Ben Hippler")) + #expect(lines[1].contains("Note checkout")) + + // A session with no recorded details still identifies itself; nothing is faked. + let bare = makeSession(captures: []) + let bareLines = PDFComposer.footerLines( + session: bare, toolVersion: "", composedAt: fixtureDate) + #expect(bareLines.count == 1) + #expect(bareLines[0].hasPrefix("Redline · ")) +} + +@Test("Document info carries the reviewer and the lane/build/commit keywords") +func documentInfoCarriesTheReviewDetails() { + let session = CaptureSession( + id: UUID(uuidString: "deadbeef-dead-4eef-8ead-deadbeef0001")!, + createdAt: fixtureDate, + state: .open, + captures: [], + pdfFileName: nil, + context: ReviewContext( + lane: "DEV03", deployedVersion: "v1.4.2", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "checkout")) + let info = PDFComposer.documentInfo( + session: session, title: "Redline – DEV03", toolVersion: "0.5.0", composedAt: fixtureDate) + + #expect(info[kCGPDFContextAuthor as String] as? String == "Ben Hippler") + #expect(info[kCGPDFContextCreator as String] as? String == "Redline 0.5.0") + let keywords = try? #require(info[kCGPDFContextKeywords as String] as? String) + #expect(keywords?.contains("lane=DEV03") == true) + #expect(keywords?.contains("deployed=v1.4.2") == true) + #expect(keywords?.contains("commit=a1b2c3d4") == true) + #expect(keywords?.contains("reviewer=Ben Hippler") == true) + #expect(keywords?.contains("built=\(DubaiTime.keywordStamp(fixtureDate))") == true) +} + +@Test("A composed PDF carries the footer text and document info a reader can see") +func composedPDFCarriesTheReferenceBlock() throws { + let directory = try makeScratchDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + + let capture = makeCapture(sequence: 1, pixelWidth: 800, pixelHeight: 600) + let png = try writePNG(for: capture, red: 60, green: 60, blue: 60, in: directory) + let session = CaptureSession( + id: UUID(uuidString: "4f2a9c1d-0000-4000-8000-000000000000")!, + createdAt: fixtureDate, + state: .open, + captures: [capture], + pdfFileName: nil, + context: ReviewContext( + lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "checkout")) + let output = directory.appendingPathComponent("footer.pdf") + _ = try PDFComposer().compose( + session: session, + imageURL: { _ in png }, + title: "Redline – dev03", + to: output, + toolVersion: "0.5.0", + composedAt: fixtureDate + ) + + let document = try openDocument(output) + let pageText = try #require(document.page(at: 0)?.string ?? "") + #expect(pageText.contains("Redline 0.5.0")) + #expect(pageText.contains("Lane dev03")) + #expect(pageText.contains("Commit a1b2c3d4")) + #expect(pageText.contains("Ben Hippler")) + + let attributes = try #require(document.documentAttributes) + #expect(attributes[PDFDocumentAttribute.authorAttribute] as? String == "Ben Hippler") +} + @Test("Three-page basic compose") func threePageBasicCompose() throws { let directory = try makeScratchDirectory() diff --git a/Tests/ShotdeckCoreTests/SessionNamingAndRetentionSettingsTests.swift b/Tests/ShotdeckCoreTests/SessionNamingAndRetentionSettingsTests.swift new file mode 100644 index 0000000..8187c50 --- /dev/null +++ b/Tests/ShotdeckCoreTests/SessionNamingAndRetentionSettingsTests.swift @@ -0,0 +1,138 @@ +import Foundation +import ShotdeckCore +import Testing + +// PDF naming scheme + the persisted session age limit. + +// MARK: - PDF file names + +@Test +func laneSlugKeepsLettersDigitsAndSingleDashes() { + #expect(PDFFileName.laneSlug("OMS test lane") == "OMS-TEST-LANE") + #expect(PDFFileName.laneSlug(" dev03 ") == "DEV03") + #expect(PDFFileName.laneSlug("v1.4.2 / stage") == "V1-4-2-STAGE") + #expect(PDFFileName.laneSlug("") == "") + #expect(PDFFileName.laneSlug("--") == "") +} + +@Test +func laneSlugIsCappedSoTheFileNameStaysShort() { + let long = String(repeating: "abcdefghij", count: 5) + let slug = PDFFileName.laneSlug(long) + #expect(slug.count == PDFFileName.laneMaxLength) + #expect(!slug.hasSuffix("-")) +} + +@Test +func fileNameIsSortableAndUniquePerSession() { + let sessionID = UUID(uuidString: "4F2A9C1D-0000-4000-8000-000000000000")! + let builtAt = Date(timeIntervalSince1970: 1_777_482_180) + + let withLane = PDFFileName.make(builtAt: builtAt, lane: "dev03", sessionID: sessionID) + #expect(withLane == "Redline-\(DubaiTime.fileMinuteStamp(builtAt))-DEV03-4F2A9C1D.pdf") + + let withoutLane = PDFFileName.make(builtAt: builtAt, lane: "", sessionID: sessionID) + #expect(withoutLane == "Redline-\(DubaiTime.fileMinuteStamp(builtAt))-4F2A9C1D.pdf") + + // Two sessions in the same minute never collide. + let other = UUID(uuidString: "9B8C7D6E-0000-4000-8000-000000000000")! + #expect(PDFFileName.make(builtAt: builtAt, lane: "dev03", sessionID: other) + != withLane) +} + +@Test +func sessionLabelIsLaneOrShortID() { + let id = UUID(uuidString: "4F2A9C1D-0000-4000-8000-000000000000")! + #expect(PDFFileName.sessionLabel(lane: "dev03", sessionID: id) == "DEV03-4F2A9C1D") + #expect(PDFFileName.sessionLabel(lane: "", sessionID: id) == "4F2A9C1D") +} + +// MARK: - Retention setting + +@Test +func retentionDefaultsToNever() throws { + let suite = try makeDefaults() + defer { suite.defaults.removePersistentDomain(forName: suite.name) } + + #expect(RetentionSettings.load(defaults: suite.defaults) == .never) + #expect(RetentionSettings.load(defaults: suite.defaults).cutoff() == nil) +} + +@Test +func retentionRoundTripsThroughDefaults() throws { + let suite = try makeDefaults() + defer { suite.defaults.removePersistentDomain(forName: suite.name) } + + RetentionSettings.save(.days(30), defaults: suite.defaults) + #expect(RetentionSettings.load(defaults: suite.defaults) == .days(30)) + + RetentionSettings.save(.never, defaults: suite.defaults) + #expect(RetentionSettings.load(defaults: suite.defaults) == .never) + #expect(suite.defaults.object(forKey: RetentionSettings.defaultsKey) == nil) +} + +@Test +func retentionCutoffIsTheDayCountBeforeNow() { + let now = Date(timeIntervalSince1970: 1_777_482_180) + let cutoff = try? #require(SessionRetention.days(30).cutoff(now: now)) + let expected = Calendar(identifier: .gregorian).date(byAdding: .day, value: -30, to: now) + #expect(cutoff == expected) +} + +@Test +func retentionPresetsReadAsPlainEnglish() { + #expect(SessionRetention.never.displayName == "Never (default)") + #expect(SessionRetention.days(7).displayName == "7 days") + #expect(SessionRetention.days(365).displayName == "1 year") + #expect(SessionRetention.never.policyDescription == "All sessions kept.") + #expect(SessionRetention.days(14).policyDescription == "Sessions older than 14 days are deleted.") +} + +// MARK: - Review context + +@Test +func reviewContextTrimsCapsAndCollapsesLineBreaks() { + let long = String(repeating: "x", count: ReviewContext.maxFieldLength + 40) + let context = ReviewContext( + lane: " dev03 ", deployedVersion: "v1.4.2\n(build 41)", commit: " a1b2c3d4 ", + reviewer: "Ben Hippler", note: long) + #expect(context.lane == "dev03") + #expect(context.deployedVersion == "v1.4.2 (build 41)") + #expect(context.commit == "a1b2c3d4") + #expect(context.note.count == ReviewContext.maxFieldLength) +} + +@Test +func reviewContextSummaryDropsEmptyParts() { + #expect(ReviewContext(lane: "dev03", commit: "a1b2c3d4").summaryLine == "dev03 · a1b2c3d4") + #expect(ReviewContext().summaryLine == "") + #expect(ReviewContext().isEmpty) +} + +@Test +func reviewContextDecodesPartialJSON() throws { + let json = Data(#"{"lane":"dev03","commit":"a1b2c3d4"}"#.utf8) + let context = try JSONDecoder().decode(ReviewContext.self, from: json) + #expect(context.lane == "dev03") + #expect(context.commit == "a1b2c3d4") + #expect(context.reviewer == "") + #expect(context.note == "") +} + +// MARK: - Fixtures + +private struct DefaultsSuite { + let name: String + let defaults: UserDefaults +} + +private func makeDefaults() throws -> DefaultsSuite { + let name = "shotdeck-retention-settings-\(UUID().uuidString)" + guard let defaults = UserDefaults(suiteName: name) else { + throw SettingsFixtureError.noSuite + } + defaults.removePersistentDomain(forName: name) + return DefaultsSuite(name: name, defaults: defaults) +} + +private enum SettingsFixtureError: Error { case noSuite } diff --git a/Tests/ShotdeckCoreTests/SessionRetentionTests.swift b/Tests/ShotdeckCoreTests/SessionRetentionTests.swift index 6a6b68b..a3ca528 100644 --- a/Tests/ShotdeckCoreTests/SessionRetentionTests.swift +++ b/Tests/ShotdeckCoreTests/SessionRetentionTests.swift @@ -4,9 +4,9 @@ import ImageIO import Testing import ShotdeckCore -// Session lifecycle + retention (MMDB-2925): "Start new session" keeps the current -// screenshots as a past session, and the newest 10 sessions are retained in the one -// archive folder. +// Session lifecycle + retention: "Start new session" keeps the current screenshots as +// a past session; every session is kept by default, and an age limit chosen in +// Settings is the only thing that ever removes one. // MARK: - 1. closeCurrentSession keeps the captures as a past session @@ -95,14 +95,16 @@ func pastSessionsDistinguishSentFromUnsentByPDFFileName() async throws { #expect(past.map(\.pdfFileName) == [nil, "Redline-20261011-120000.pdf"]) } -// MARK: - 4. retention keeps the newest 10 sessions, in the one archive folder +// MARK: - 4. nothing is deleted by default @Test -func retentionKeepsTheNewestTenSessionsAndRemovesTheRest() async throws { +func defaultPolicyKeepsEverySession() async throws { let (root, paths) = try makeIsolatedPaths() defer { try? FileManager.default.removeItem(at: root) } let store = try SpoolStore(paths: paths) + #expect(await store.configuredRetention() == .never) + var closedIDs: [UUID] = [] for index in 0..<12 { _ = try await store.append( @@ -113,78 +115,141 @@ func retentionKeepsTheNewestTenSessionsAndRemovesTheRest() async throws { closedIDs.append(closed.id) } - // All 12 sessions live in the single archive/ folder as UUID session folders. + // All 12 sessions live on in the single archive/ folder; none was pruned. let fm = FileManager.default let entries = try fm.contentsOfDirectory(at: paths.archive, includingPropertiesForKeys: nil) let sessionDirs = entries.filter { UUID(uuidString: $0.lastPathComponent) != nil } - #expect(sessionDirs.count == SpoolStore.defaultRetainedSessionCount) + #expect(sessionDirs.count == closedIDs.count) let kept = try await store.archivedSessions().map(\.id) - #expect(kept == Array(closedIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed())) + #expect(kept == closedIDs.reversed()) - // The two oldest sessions are gone; the newest ten are fully on disk. - for id in closedIDs.prefix(2) { - #expect(!fm.fileExists(atPath: paths.archiveDirectory(id).path)) - } - for id in closedIDs.suffix(SpoolStore.defaultRetainedSessionCount) { + for id in closedIDs { #expect(fm.fileExists(atPath: paths.archiveDirectory(id).appendingPathComponent("session.json").path)) } - // The open session is never touched by retention. - let open = try await store.currentSession() - #expect(open.state == .open) - #expect(open.isEmpty) - #expect(fm.fileExists(atPath: paths.sessionDirectory(open.id).path)) + // A prune under the default policy removes nothing at all. + #expect(try await store.pruneExpiredSessions().isEmpty) + #expect(try await store.expiredSessionIDs().isEmpty) } -// MARK: - 5. explicit prune keeps exactly the requested count +// MARK: - 5. an age limit removes exactly the expired sessions @Test -func pruneArchivedSessionsKeepingNRemovesExactlyTheOldest() async throws { +func ageLimitRemovesOnlySessionsOlderThanTheCutoff() async throws { let (root, paths) = try makeIsolatedPaths() defer { try? FileManager.default.removeItem(at: root) } - let store = try SpoolStore(paths: paths) - var closedIDs: [UUID] = [] - for _ in 0..<4 { - _ = try await store.append( - pngData: try makePNGData(width: 4, height: 4, red: 0.2, green: 0.2, blue: 0.2), - pixelWidth: 4, pixelHeight: 4, scale: 1.0, capturedAt: Date()) - closedIDs.append(try #require(try await store.closeCurrentSession()).id) + let now = Date(timeIntervalSince1970: 1_700_000_000) // fixed "now" for the test + let day: TimeInterval = 86_400 + let oldIDs = try [ + try writeArchivedSession(createdAt: now.addingTimeInterval(-40 * day), in: paths), + try writeArchivedSession(createdAt: now.addingTimeInterval(-31 * day), in: paths), + ] + let recentIDs = try [ + try writeArchivedSession(createdAt: now.addingTimeInterval(-29 * day), in: paths), + try writeArchivedSession(createdAt: now.addingTimeInterval(-1 * day), in: paths), + ] + + let store = try SpoolStore(paths: paths, retention: .days(30)) + + // Asking what would happen deletes nothing. + #expect(Set(try await store.expiredSessionIDs(now: now)) == Set(oldIDs)) + #expect(try await store.archivedSessions().count == 4) + + let removed = try await store.pruneExpiredSessions(now: now) + #expect(Set(removed) == Set(oldIDs)) + + let fm = FileManager.default + for id in oldIDs { + #expect(!fm.fileExists(atPath: paths.archiveDirectory(id).path)) + } + for id in recentIDs { + #expect(fm.fileExists(atPath: paths.archiveDirectory(id).appendingPathComponent("session.json").path)) } - let removed = try await store.pruneArchivedSessions(keeping: 2) - #expect(removed == Array(closedIDs.prefix(2).reversed())) // newest-first walk order - let kept = try await store.archivedSessions().map(\.id) - #expect(kept == Array(closedIDs.suffix(2).reversed())) - - // Idempotent: nothing left to prune at that limit. - let removedAgain = try await store.pruneArchivedSessions(keeping: 2) - #expect(removedAgain.isEmpty) + // The open session is never a candidate, and a second pass is a no-op. + #expect(try await store.currentSession().state == .open) + #expect(try await store.pruneExpiredSessions(now: now).isEmpty) } -// MARK: - 6. retention runs on the send path too +// MARK: - 6. the archive path applies the configured age limit @Test -func theSendArchivePathAppliesRetention() async throws { +func theArchivePathAppliesTheAgeLimit() async throws { let (root, paths) = try makeIsolatedPaths() defer { try? FileManager.default.removeItem(at: root) } - let store = try SpoolStore(paths: paths) - var sentIDs: [UUID] = [] - for index in 0..<(SpoolStore.defaultRetainedSessionCount + 3) { - _ = try await store.append( - pngData: try makePNGData(width: 4, height: 4, red: 0.3, green: 0.3, blue: 0.3), - pixelWidth: 4, pixelHeight: 4, scale: 1.0, - capturedAt: Date(timeIntervalSince1970: 1_700_100_000 + Double(index))) - let archived = try await store.archiveCurrent(pdfFileName: "Redline-\(index).pdf") - sentIDs.append(archived.id) - } + let day: TimeInterval = 86_400 + let expiredID = try writeArchivedSession( + createdAt: Date().addingTimeInterval(-10 * day), in: paths) + + let store = try SpoolStore(paths: paths, retention: .days(7)) + _ = try await store.append( + pngData: try makePNGData(width: 4, height: 4, red: 0.3, green: 0.3, blue: 0.3), + pixelWidth: 4, pixelHeight: 4, scale: 1.0, capturedAt: Date()) + let archived = try await store.archiveCurrent(pdfFileName: "Redline-20261031-1200-A1B2C3D4.pdf") let kept = try await store.archivedSessions() - #expect(kept.count == SpoolStore.defaultRetainedSessionCount) - #expect(kept.map(\.id) == Array(sentIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed())) - #expect(kept.allSatisfy { $0.pdfFileName != nil }) + #expect(kept.map(\.id) == [archived.id]) + #expect(!FileManager.default.fileExists(atPath: paths.archiveDirectory(expiredID).path)) +} + +// MARK: - 7. review context is persisted, survives a relaunch and is inherited + +@Test +func reviewContextPersistsAndIsInheritedByTheNextSession() async throws { + let (root, paths) = try makeIsolatedPaths() + defer { try? FileManager.default.removeItem(at: root) } + + let store = try SpoolStore(paths: paths) + let context = ReviewContext( + lane: "dev03", deployedVersion: "v1.4.2 (41)", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "checkout flow") + + let updated = try await store.setContext(context) + #expect(updated.context == context) + + // A second store on the same directory is what a relaunch sees. + let reopened = try SpoolStore(paths: paths) + #expect(try await reopened.currentSession().context == context) + + _ = try await store.append( + pngData: try makePNGData(width: 4, height: 4, red: 0.4, green: 0.4, blue: 0.4), + pixelWidth: 4, pixelHeight: 4, scale: 1.0, capturedAt: Date()) + let archived = try #require(try await store.closeCurrentSession()) + #expect(archived.context == context) + + // The fresh session keeps the same review details. + #expect(try await store.currentSession().context == context) +} + +// MARK: - 8. a manifest written before contexts existed still loads + +@Test +func legacyManifestWithoutContextDecodesAsEmptyContext() async throws { + let (root, paths) = try makeIsolatedPaths() + defer { try? FileManager.default.removeItem(at: root) } + + let id = UUID() + let dir = paths.archiveDirectory(id) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let legacyJSON = """ + { + "id": "\(id.uuidString)", + "createdAt": "2026-10-11T12:00:00Z", + "state": "archived", + "captures": [], + "pdfFileName": "Redline-20261011-120000.pdf" + } + """ + try Data(legacyJSON.utf8).write(to: dir.appendingPathComponent("session.json")) + + let store = try SpoolStore(paths: paths) + let sessions = try await store.archivedSessions() + #expect(sessions.map(\.id) == [id]) + #expect(sessions.first?.context == .empty) + #expect(sessions.first?.pdfFileName == "Redline-20261011-120000.pdf") } // MARK: - 7. a stale open session is never returned as current (truth guard) @@ -218,6 +283,28 @@ func aStaleOpenSessionIsNeverReturnedAsCurrent() async throws { // MARK: - Fixtures +/// Writes an archived session folder with the given creation date, exactly the shape +/// production writes (a manifest plus one PNG), so retention can be exercised without +/// waiting days. +private func writeArchivedSession(createdAt: Date, in paths: AppSupportPaths) throws -> UUID { + let id = UUID() + let dir = paths.archiveDirectory(id) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let pngName = "001-A1B2C3D4.png" + try makePNGData(width: 4, height: 4, red: 0.5, green: 0.5, blue: 0.5) + .write(to: dir.appendingPathComponent(pngName)) + let capture = Capture( + id: UUID(), sequence: 1, fileName: pngName, + pixelWidth: 4, pixelHeight: 4, scale: 1.0, capturedAt: createdAt) + let session = CaptureSession( + id: id, createdAt: createdAt, state: .archived, captures: [capture], + pdfFileName: "Redline-\(DubaiTime.fileMinuteStamp(createdAt)).pdf") + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + try encoder.encode(session).write(to: dir.appendingPathComponent("session.json")) + return id +} + private enum FixtureError: Error { case pngGenerationFailed } diff --git a/Tests/ShotdeckTests/SessionWorkflowTests.swift b/Tests/ShotdeckTests/SessionWorkflowTests.swift index 2fe3f88..3a8770a 100644 --- a/Tests/ShotdeckTests/SessionWorkflowTests.swift +++ b/Tests/ShotdeckTests/SessionWorkflowTests.swift @@ -6,15 +6,15 @@ import Testing import ShotdeckCore @testable import Shotdeck -/// MMDB-2925, through the REAL app-target seams the menu rows invoke (`AppModel` -/// actions + `SpoolStore`): "Start new session" keeps the current screenshots as a -/// past session, the Past submissions state reflects what was sent, and session -/// retention keeps the newest 10 sessions in the one archive folder. `bootstrap()` -/// itself is covered by LaunchWiringTests; here `addCapture` refreshes the session -/// from the store exactly the way `AppModel.captureNow()` does after a real capture. +/// Through the REAL app-target seams the menu rows invoke (`AppModel` actions + +/// `SpoolStore`): "Start new session" keeps the current screenshots as a past session, +/// the Past sessions state reflects what was sent, every session is kept by default, +/// and a chosen age limit is what removes one. `bootstrap()` itself is covered by +/// LaunchWiringTests; here `addCapture` refreshes the session from the store exactly +/// the way `AppModel.captureNow()` does after a real capture. @MainActor -@Test("Menu actions: start new session keeps captures, lists past submissions, retains 10") -func startNewSessionKeepsCapturesListsPastSubmissionsAndRetainsTen() async throws { +@Test("Menu actions: start new session keeps captures and lists past submissions") +func startNewSessionKeepsCapturesAndListsPastSessions() async throws { let fm = FileManager.default let root = fm.temporaryDirectory .appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true) @@ -51,8 +51,8 @@ func startNewSessionKeepsCapturesListsPastSubmissionsAndRetainsTen() async throw } @MainActor -@Test("Retention: 12 sessions through the menu action leave the newest 10 on disk") -func twelveSessionsLeaveTheNewestTenInTheOneArchiveFolder() async throws { +@Test("Retention: 12 sessions through the menu action are all kept by default") +func twelveSessionsStayOnDiskByDefault() async throws { let fm = FileManager.default let root = fm.temporaryDirectory .appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true) @@ -66,16 +66,91 @@ func twelveSessionsLeaveTheNewestTenInTheOneArchiveFolder() async throws { await model.startNewSession() } - #expect(model.pastSessions.count == SpoolStore.defaultRetainedSessionCount) - #expect(model.pastSessions.map(\.id) - == Array(closedIDs.suffix(SpoolStore.defaultRetainedSessionCount).reversed())) + #expect(model.retention == .never) + #expect(model.pastSessions.map(\.id) == closedIDs.reversed()) let entries = try fm.contentsOfDirectory(at: model.paths.archive, includingPropertiesForKeys: nil) let sessionDirs = entries.filter { UUID(uuidString: $0.lastPathComponent) != nil } - #expect(sessionDirs.count == SpoolStore.defaultRetainedSessionCount) - for id in closedIDs.prefix(2) { - #expect(!fm.fileExists(atPath: model.paths.archiveDirectory(id).path)) + #expect(sessionDirs.count == closedIDs.count) + for id in closedIDs { + #expect(fm.fileExists(atPath: model.paths.archiveDirectory(id).path)) } + #expect(model.expiredSessionCount == 0) +} + +@MainActor +@Test("A review detail typed in the panel is saved and inherited by the next session") +func reviewDetailsPersistThroughTheModel() async throws { + let fm = FileManager.default + let root = fm.temporaryDirectory + .appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true) + defer { try? fm.removeItem(at: root) } + let model = AppDelegate.makeLaunchModel(appSupportRoot: root) + + let context = ReviewContext( + lane: "dev03", deployedVersion: "v1.4.2", commit: "a1b2c3d4", + reviewer: "Ben Hippler", note: "checkout") + await model.setContextField(context) + #expect(model.session.context == context) + #expect(model.sessionContext.summaryLine == "dev03 · v1.4.2 · a1b2c3d4 · Ben Hippler") + #expect(model.nextPDFFileNameHint.contains("-DEV03-")) + + _ = try await addCapture(to: model, red: 0.1, green: 0.4, blue: 0.9) + await model.startNewSession() + + // The closed session keeps its details; the new one inherits them. + #expect(model.pastSessions.first?.context == context) + #expect(model.session.context == context) +} + +@MainActor +@Test("Settings age limit: cleanup removes only expired sessions, never a sent PDF") +func cleanUpHonorsTheAgeLimit() async throws { + let fm = FileManager.default + let root = fm.temporaryDirectory + .appendingPathComponent("shotdeck-session-workflow-\(UUID().uuidString)", isDirectory: true) + defer { try? fm.removeItem(at: root) } + let suite = try makeIsolatedDefaults() + defer { suite.defaults.removePersistentDomain(forName: suite.name) } + let model = AppDelegate.makeLaunchModel( + appSupportRoot: root, retentionDefaults: suite.defaults) + await model.bootstrap() + + // One real session that was sent (its PDF is in the outbox) … + _ = try await addCapture(to: model, red: 0.6, green: 0.2, blue: 0.2) + let sentName = "Redline-20261001-0900-A1B2C3D4.pdf" + _ = try await model.spool.archiveCurrent(pdfFileName: sentName) + try Data("%PDF-1.4\n% test\n".utf8) + .write(to: model.paths.outbox.appendingPathComponent(sentName)) + + // … and one archived session backdated past the limit, written in the exact shape + // production writes, so the age comparison runs against real manifest dates. + let expiredID = try await writeBackdatedSession(in: model.paths, daysAgo: 40) + await model.reloadFromSpool() + + #expect(model.pastSessions.count == 2) + + // Nothing expires under .never, even with a cleanup. + await model.cleanUpExpiredSessions() + #expect(model.pastSessions.count == 2) + #expect(model.expiredSessionCount == 0) + #expect(model.statusLine?.contains("Nothing to remove") == true) + + // A 30-day limit expires only the backdated session, and says so before deleting. + await model.setRetention(.days(30)) + #expect(model.retention == .days(30)) + #expect(RetentionSettings.load(defaults: suite.defaults) == .days(30)) + #expect(model.expiredSessionCount == 1) + + await model.cleanUpExpiredSessions() + #expect(model.pastSessions.count == 1) + #expect(model.statusLine?.contains("Removed 1 past session") == true) + #expect(!fm.fileExists(atPath: model.paths.archiveDirectory(expiredID).path)) + #expect(fm.fileExists(atPath: model.paths.outbox.appendingPathComponent(sentName).path)) + + // Back to the default in this isolated suite, so the next test starts clean. + await model.setRetention(.never) + #expect(model.expiredSessionCount == 0) } @MainActor @@ -191,6 +266,49 @@ private enum FixtureError: Error { case pngGenerationFailed } +// MARK: - Fixtures + +private struct IsolatedDefaults { + let name: String + let defaults: UserDefaults +} + +/// A throwaway UserDefaults suite — never `.standard` — so the age-limit setting a +/// test writes can never change Ben's real app preference. +private func makeIsolatedDefaults() throws -> IsolatedDefaults { + let name = "shotdeck-session-workflow-\(UUID().uuidString)" + guard let defaults = UserDefaults(suiteName: name) else { + throw FixtureError.pngGenerationFailed + } + defaults.removePersistentDomain(forName: name) + return IsolatedDefaults(name: name, defaults: defaults) +} + +/// Writes an archived session folder dated `daysAgo` days in the past, in the exact +/// on-disk shape the store produces, so an age policy can act on a real manifest date. +@discardableResult +private func writeBackdatedSession(in paths: AppSupportPaths, daysAgo: Int) async throws -> UUID { + let id = UUID() + let createdAt = Date().addingTimeInterval(-Double(daysAgo) * 86_400) + let dir = paths.archiveDirectory(id) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let pngName = "001-\(String(id.uuidString.prefix(8)).uppercased()).png" + try makePNGData(width: 8, height: 8, red: 0.3, green: 0.3, blue: 0.3) + .write(to: dir.appendingPathComponent(pngName)) + let capture = Capture( + id: UUID(), sequence: 1, fileName: pngName, + pixelWidth: 8, pixelHeight: 8, scale: 1.0, capturedAt: createdAt) + let session = CaptureSession( + id: id, createdAt: createdAt, state: .archived, captures: [capture], + pdfFileName: nil, + context: ReviewContext(lane: "DEV03", deployedVersion: "v1.0.0", commit: "abc1234")) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + try encoder.encode(session).write(to: dir.appendingPathComponent("session.json")) + return id +} + + private func makePNGData( width: Int, height: Int, diff --git a/design/ux-rework/redline-ux-v2.html b/design/ux-rework/redline-ux-v2.html new file mode 100644 index 0000000..0c3db8f --- /dev/null +++ b/design/ux-rework/redline-ux-v2.html @@ -0,0 +1,343 @@ + + + + + +Redline UX v2 + + + + +
+

Redline v2 — decide what you capture first

+

The popover now starts with the capture decision (what, and where), then the pages, then the two verbs. Settings has one visible door: the gear in the popover header. Filler lines are gone; a status line appears only when something happened. Updates install themselves.

+
+ + + + + + + + + + + + + + +
+
1Menu-bar popover340 pt · controlSize small · capture decision → pages → verbs
+
+ +
1a · Idle, empty session · light
+
◫Sat 31 Oct 13:05
+
+
  • Header has exactly two icons: details (opens the window on Lane) and Settings. No “…” menu.
  • The capture box is the first decision on screen; Choose Area… is always one click away.
  • No footer. Nothing is printed unless it is news.
+
+ +
1b · Pages present + one return · dark
+
◫ 3Sat 31 Oct 13:05
+
+
  • The Capture button wears the scope icon, so what ⌥⇧2 will grab is never ambiguous.
  • Choosing a non-area scope keeps the saved area (“area kept”) — switching back to Area restores it.
+
+ +
1c · New Session… — the capture decision at the moment of starting · light
+
◫ 3Sat 31 Oct 13:06
+
+
  • New Session… never starts silently: it shows scope, area and inherited details in place of the pages, with Start Session as the default button (Return).
  • Choose Area… here dismisses the popover, runs the picker, and comes back to this step with the new size.
+
+ +
1d · Capture-scope menu from the keyboard (⌥⇧1) · dark
+
◫Sat 31 Oct 13:06
+
+
  • ⌥⇧1 opens this menu where the pointer is; one keystroke captures with that scope and makes it the session’s scope.
  • Browser Page grabs the front browser window’s page area (Safari, Chrome, Arc, Edge); the tab strip and toolbar are cropped.
+
+ +
1e · Update installed in the background · light
+
◫Sat 31 Oct 13:07
+
+
DEV03 · v1.4.2 (41)
a1b2c3d4 · Ben Hippler
+
Redline 0.6.0 is ready — restarts after you sendRestart Now
+
Capture ⌥⇧2Send 2 pages
+
+
  • One line, only while it matters. It never interrupts a session with unsent pages.
  • Cropped to the relevant part for this mock.
+
+ +
+
+ + +
+
2Redline window · headerscope and area are part of the session, shown where the verbs are
+
+
2a · Current session · light
+
+
+
DEV03 Current
3 pages · not sent
+ Area · 800 × 600 + Choose Area… + Capture + New Session… + Send 3 pages +
+
Today
DEV03 13:05
3 pages · not sent
OMS test lane 11:48
2 pages marked
+
1
2
3
+
+
  • No gear here: Settings is ⌘, (and the popover gear) — one surface, one door.
  • Cropped to the header and a slice of the content for this mock.
+
+
2b · Same, dark, Browser scope
+
+
+
DEV03 Current
3 pages · not sent
+ Browser Page + Capture + New Session… + Send 3 pages +
+
+
  • With a non-area scope, Choose Area… disappears from the header; it lives in the scope menu as “Choose New Area…”.
+
+
+
+ + +
+
3Settings460 pt · one window, reached only from the popover gear or ⌘,
+
+
3a · light
+
+
Redline Settings
+
+
Capture
+
+
CaptureSaved Area
+
Saved area800 × 600 on Display 1Choose…
+
Capture shortcut⌥⇧2
+
Capture menu shortcut⌥⇧1
+
Ask what to capture on New Session
+
+
Sending
+
+
Send withAirDropOneDrive
+
Save PDFs to~/DesktopChoose…
+
Watch for returns in~/DownloadsChoose…
+
+
Sessions
+
+
Delete sessions older thanNever
+
20 sessions on this MacClean Up Now…
+
+
Deleting removes Redline’s own screenshots only. PDFs you sent stay where they are.
+
Updates
+
+
Install updates automatically
+
Version 0.5.0 · checked 13:02Check Now
+
+
Updates download in the background and install the next time Redline has no unsent pages. Your area, shortcuts and sessions are kept.
+
Redline 0.5.0Quit Redline
+
+
+
3b · dark · update ready
+
+
Redline Settings
+
+
Updates
+
+
Install updates automatically
+
0.6.0 downloaded · installs after your next sendRestart Now
+
+
Turned off: Redline still checks every 6 hours and shows “Update to 0.6.0” here and in the popover, but waits for you.
+
Capture
+
+
CaptureFront Window
+
Saved area800 × 600 on Display 1Choose…
+
+
+
+
  • Quit lives here (and ⌘Q in the popover): the popover has no menu left to hide it in.
  • 3b is cropped to the changed groups.
+
+
+
+ + +
+
4Labels, keys, states
+
+

Strings

+ + + + + + + + + + + +
PlaceExact label
Popover header iconsEdit review details (tooltip + VoiceOver), Settings (tooltip “Settings (⌘,)”)
Scope segmented control (VoiceOver “Capture”)Area · Window · Browser · Screen
Target lineArea: 800 × 600 on Display 1 + Choose Area… · Window: Front window when you press ⌥⇧2 · Browser: Front browser page when you press ⌥⇧2 · Screen: Display 1 · 2560 × 1440; non-area scopes add area kept: 800 × 600
Empty pagesNo pages yet / ⌥⇧2 captures the area|window|page|screen
VerbsCapture ⌥⇧2, Send (empty, disabled) / Send 3 pages, OneDrive: Save 3 pages; New Session…, Open Redline
New-session stepTitle New session; subtitle The current 3 pages are kept as a past session.; groups Capture, Review details + Edit…; buttons Cancel, Start Session
Scope menu (⌥⇧1)Header Capture; Saved Area (1), Front Window (2), Browser Page (3), Whole Screen (4), Choose New Area… (A)
Status line (only when news)Captured page 4 · Sent · 3 pages · Saved to OneDrive · 3 pages · OMS test lane came back · 2 pages marked + Open · No front window to capture · No browser window in front · Redline 0.6.0 is ready — restarts after you send + Restart Now
SettingsGroups Capture, Sending, Sessions, Updates; rows as in 3a; captions as in 3a/3b; footer Quit Redline
+

Keyboard

+

Global: ⌥⇧2 capture with the session’s scope · ⌥⇧1 open the capture menu (1–4 or A picks and captures). Popover Tab order: Edit review details → Settings → scope segments (←/→ move) → Choose Area… → Capture → Send → New Session… → Open Redline. Return = Send when enabled, otherwise Capture; Escape closes. ⌘, opens Settings; ⌘N = New Session…; ⌘Q quits. New-session step: Tab scope → Choose Area… → Edit… → Cancel → Start Session; Return = Start Session, Escape = Cancel. Window: ⌘N New Session…, ⌘S Send, ⌘, Settings, ⌘F search.

+

Scope states

+

The scope belongs to the session and is copied to the next one. Area uses the saved rectangle; if none is saved, Capture first runs the picker. Window grabs the frontmost window of the app that was front before Redline (never Redline itself); none → status “No front window to capture”, nothing added. Browser grabs the frontmost Safari / Chrome / Arc / Edge / Firefox window, page area only; no browser in front → “No browser window in front”. Screen grabs the display the pointer is on. Choosing Window, Browser or Screen never clears the saved area: it is shown as “area kept” and comes back when Area is chosen. Choose Area… / Choose New Area… always replaces the saved area and switches the scope to Area.

+

Information architecture

+

The capture decision lives in the popover, above the pages, as a four-way segmented control with the target line under it — and again, unmissably, in the New Session… step, which replaces the page strip until Start Session. The window header mirrors the scope as a pop-up next to the verbs. Settings has one door: the gear in the popover header (⌘, from anywhere in Redline); the window has no gear and the popover has no “…” menu. Popover hierarchy, top to bottom: what is being reviewed (lane, build, commit, reviewer) → what will be captured (scope, target) → what has been captured (pages) → news (one status line, only when there is any) → verbs (Capture, Send) → session control (New Session…, Open Redline). Updates move into Settings › Updates and surface in the popover only when an installed update is waiting.

+

Still the biggest thing wrong

+

The popover still carries two jobs at once — deciding what to capture and reviewing what was captured — and the real fix is to make the session, not the popover, the unit of decision: every capture rule (scope, area, lane, build, commit) should be set once, when the session starts, and then stay out of the way. Today the new-session step is the only place that treats it that way; until scope and details are locked per session (with change visibly recorded on the PDF when they change mid-session), a reviewer can still produce a PDF whose pages were captured under different rules without anyone noticing.

+
+
+ + diff --git a/design/ux-rework/redline-ux.html b/design/ux-rework/redline-ux.html new file mode 100644 index 0000000..0004594 --- /dev/null +++ b/design/ux-rework/redline-ux.html @@ -0,0 +1,480 @@ + + + + + +Redline UX Rework + + + + + +
+

Redline, rebuilt from the job outwards

+

The menu-bar popover only answers "what am I capturing, and what do I do next". Everything about past sessions, review details and PDF facts lives in one Redline window. Settings has three sections. Each mock is shown at 1:1 size in light and dark.

+
+ +
+
1Menu-bar popover: glance and act340 pt wide · controlSize small · current session only
+
+
+ +
+
2Redline window: the session workspace1100 × 700 · sidebar · content · inspector · controlSize regular
+
+
+ +
+
3Redline window: first run, nothing captured1100 × 700
+
+
+ +
+
4Settings420 × 484 · three groups, no tabs
+
+
+ + + + diff --git a/scripts/install-local.sh b/scripts/install-local.sh new file mode 100755 index 0000000..795453f --- /dev/null +++ b/scripts/install-local.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Installs the locally built Redline into /Applications and launches it with its +# session window open, so the current build is what is on screen. +# +# ./scripts/install-local.sh +# +# The previously installed copy is kept at .build/Redline-.app so the change +# is reversible. + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +BUILT="${ROOT}/.build/Redline.app" +TARGET="/Applications/Redline.app" +BUNDLE_ID="ai.flowmaster.shotdeck" + +if [[ ! -d "${BUILT}" ]]; then + echo "No ${BUILT}. Run ./scripts/build-app.sh first." >&2 + exit 1 +fi + +if [[ -d "${TARGET}" ]]; then + OLD_VERSION="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "${TARGET}/Contents/Info.plist")" + BACKUP="${ROOT}/.build/Redline-${OLD_VERSION}.app" + if [[ ! -d "${BACKUP}" ]]; then + echo "==> Keeping the installed ${OLD_VERSION} at ${BACKUP}" + ditto "${TARGET}" "${BACKUP}" + fi +fi + +echo "==> Quitting the running Redline" +osascript -e 'quit app "Redline"' >/dev/null 2>&1 || true +for _ in $(seq 1 40); do + if ! pgrep -f "${TARGET}/Contents/MacOS/Shotdeck" >/dev/null 2>&1; then + break + fi + sleep 0.25 +done +pkill -f "${TARGET}/Contents/MacOS/Shotdeck" >/dev/null 2>&1 || true +sleep 0.5 + +echo "==> Installing ${BUILT} to ${TARGET}" +ditto "${BUILT}" "${TARGET}" + +NEW_VERSION="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "${TARGET}/Contents/Info.plist")" +echo "==> Launching Redline ${NEW_VERSION} with its window open" +open -n "${TARGET}" --args --window + +sleep 2 +if pgrep -f "${TARGET}/Contents/MacOS/Shotdeck" >/dev/null 2>&1; then + echo "Redline ${NEW_VERSION} is running from ${TARGET}" +else + echo "Redline did not start" >&2 + exit 1 +fi diff --git a/scripts/render-panels.sh b/scripts/render-panels.sh new file mode 100755 index 0000000..ae85a8b --- /dev/null +++ b/scripts/render-panels.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Renders the headless panel PNGs and a sample review PDF for visual verification. +# +# ./scripts/render-panels.sh [output-directory] +# +# Builds nothing: run `swift build` (or ./scripts/build-app.sh) first. The output +# directory is printed at the end; nothing outside it is touched, and the isolated +# model means the real Application Support spool and the real age-limit preference +# are never read or written. + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +OUT_DIR="${1:-$(mktemp -d /tmp/redline-panels.XXXXXX)}" +BINARY="${ROOT}/.build/Redline.app/Contents/MacOS/Shotdeck" + +if [[ ! -x "${BINARY}" ]]; then + BINARY="${ROOT}/.build/debug/Shotdeck" +fi +if [[ ! -x "${BINARY}" ]]; then + echo "No Shotdeck binary found. Run swift build or ./scripts/build-app.sh first." >&2 + exit 1 +fi + +mkdir -p "${OUT_DIR}" +SHOTDECK_SNAPSHOT_DIR="${OUT_DIR}" "${BINARY}" +echo "Panels written to ${OUT_DIR}" diff --git a/scripts/run-e2e-ui.sh b/scripts/run-e2e-ui.sh new file mode 100755 index 0000000..a6b6eeb --- /dev/null +++ b/scripts/run-e2e-ui.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -euo pipefail + +# End-to-end UI run: the real panel, in the ACTIVE app, typed into with the keyboard +# and clicked with the mouse. Launched through LaunchServices ("open -n") because a +# background shell launch can never get a key window — macOS will not let it activate. +# +# ./scripts/run-e2e-ui.sh +# +# Builds a throwaway copy of the signed app under a separate bundle identifier +# (ai.flowmaster.shotdeck.e2e) so it can run alongside the installed Redline without +# touching /Applications, Ben's real captures, or his real preferences. It writes its +# results to a file and exits. + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +SOURCE_APP="${ROOT}/.build/Redline.app" +E2E_APP="${ROOT}/.build/RedlineE2E.app" +IDENTITY="Apple Development: ben@flow-master.ai (QH2H9G2LK5)" +BUNDLE_ID="ai.flowmaster.shotdeck.e2e" +WORK_DIR="$(mktemp -d /tmp/redline-e2e.XXXXXX)" +RESULT="${WORK_DIR}/result.txt" + +if [[ ! -d "${SOURCE_APP}" ]]; then + echo "No ${SOURCE_APP} found. Run ./scripts/build-app.sh first." >&2 + exit 1 +fi + +# A leftover instance from an interrupted run would hold the bundle identifier and +# make "open -n" a no-op. +pkill -f "RedlineE2E.app/Contents/MacOS/Shotdeck" >/dev/null 2>&1 || true +for _ in $(seq 1 20); do + pgrep -f "RedlineE2E.app/Contents/MacOS/Shotdeck" >/dev/null 2>&1 || break + sleep 0.2 +done +rm -rf "${E2E_APP}" +ditto "${SOURCE_APP}" "${E2E_APP}" +/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier ${BUNDLE_ID}" "${E2E_APP}/Contents/Info.plist" +/usr/libexec/PlistBuddy -c "Set :CFBundleName Redline E2E" "${E2E_APP}/Contents/Info.plist" +# A menu-bar app (LSUIElement) is never activated by LaunchServices, and macOS only +# lets an active app own the key window the keyboard goes to. The test copy is a +# regular app for the duration of the run; the shipped app keeps LSUIElement. +/usr/libexec/PlistBuddy -c "Set :LSUIElement false" "${E2E_APP}/Contents/Info.plist" +codesign --force --options runtime \ + --sign "${IDENTITY}" \ + --identifier "${BUNDLE_ID}" \ + "${E2E_APP}" + +open -n "${E2E_APP}" --args --selftest e2e --root "${WORK_DIR}/storage" --result "${RESULT}" + +for _ in $(seq 1 120); do + if [[ -f "${RESULT}" ]] && grep -qE "^E2E (PASS|FAIL)$" "${RESULT}"; then + break + fi + sleep 0.25 +done + +sleep 0.5 +osascript -e "tell application id \"${BUNDLE_ID}\" to quit" >/dev/null 2>&1 || true + +if [[ ! -f "${RESULT}" ]]; then + echo "E2E FAIL: no result file was written (${RESULT})" >&2 + exit 1 +fi + +cat "${RESULT}" +grep -q "^E2E PASS$" "${RESULT}" diff --git a/scripts/run-selftest.sh b/scripts/run-selftest.sh new file mode 100755 index 0000000..43b0565 --- /dev/null +++ b/scripts/run-selftest.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Runs one in-process self-test phase against the built binary. +# +# ./scripts/run-selftest.sh panel +# ./scripts/run-selftest.sh onedrive +# ./scripts/run-selftest.sh sendtruth +# +# Prints the phase's PASS/FAIL lines and exits with the binary's status. + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +PHASE="${1:-panel}" +BINARY="${ROOT}/.build/Redline.app/Contents/MacOS/Shotdeck" + +if [[ ! -x "${BINARY}" ]]; then + BINARY="${ROOT}/.build/debug/Shotdeck" +fi +if [[ ! -x "${BINARY}" ]]; then + echo "No Shotdeck binary found. Run swift build or ./scripts/build-app.sh first." >&2 + exit 1 +fi + +REDLINE_SELFTEST_PHASE="${PHASE}" "${BINARY}"