Files
shotdeck/Sources/Shotdeck/AppModel.swift
T
Claude Fable 5 3fb9b504f4 feat(capture): choose what to capture — area, window, browser page or screen
Capture is now a decision, not a hidden setting. The popover shows a four-way scope control with the target named under it (800 x 600 on Display 1, the frontmost window, the front browser window, the whole display), and the window header carries the same choice beside the verbs. Picking Window or Browser hides Redline, dims the screen, names the app under the pointer and highlights its window; a click captures exactly that window, Escape cancels, and the desktop highlights the whole screen. New Session is one click: the current captures stay in their own folder, a fresh session opens, and the area picker comes straight up with the saved area pre-selected — Return keeps it, a drag replaces it. Settings is consolidated into one door (the popover gear, plus Cmd-,): what to capture, saved area, shortcut, ask-on-new-session, sending, session age limit, and a new Updates group with automatic install (on by default; installs only when nothing is unsent). The footer filler and the extra-actions menu are gone.
2026-11-01 11:47:58 +04:00

980 lines
42 KiB
Swift

import AppKit
import Foundation
import Observation
import SwiftUI
import ShotdeckCore
@MainActor
public protocol SendCapable: AnyObject {
func send(anchor: NSView?) async
}
@MainActor
public protocol SettingsWindowPresenting: AnyObject {
func presentSettingsWindow()
}
@MainActor
public protocol SessionsWindowPresenting: AnyObject {
func presentSessionsWindow(focusLane: Bool)
}
@MainActor
public protocol ReturnsSectionProviding: AnyObject {
@ViewBuilder func returnsSection() -> AnyView
}
@MainActor
@Observable
public final class AppModel {
public private(set) var session: CaptureSession
public private(set) var region: CaptureRegion?
public private(set) var screenRecordingGranted: Bool
public private(set) var allReturns: [ReturnedDocument] = []
public private(set) var commentedReturns: [ReturnedDocument] = []
/// 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
/// synchronous flag both this action and send() check BEFORE their first await, so
/// the two can never interleave a session close with an in-flight compose (a
/// SwiftUI `.disabled` render-time guard alone does not stop a queued Task).
public private(set) var isStartingNewSession: Bool = false
public private(set) var outboxDisplayName: String
public private(set) var watchFolderDisplayName: String
/// Live transport choice; WP-onedrive reads this to pick the send path and to drive
/// the Settings "Send via" picker and the menu's "Send…" label.
public private(set) var transport: SendTransport
/// Ground truth for the Settings OneDrive row: nil means "no OneDrive folder found".
/// Views read this instead of calling `OneDriveLocator.resolveOneDriveFolder()`
/// directly, so state (and testing with a fake home) flows through the model like
/// everything else — never a View reaching past the model for real UserDefaults/home.
public private(set) var resolvedOneDriveFolder: URL?
/// Live outbox; WP-4b reads this (not `paths.outbox`) so Settings folder changes take effect.
public private(set) var outboxURL: URL
/// Live watch folder; WP-4c updates this alongside `ReturnWatcher.updateWatchFolder`.
public private(set) var watchFolderURL: URL
/// Absolute URL of the PDF composed this run, if any. Used by "Reveal last PDF".
public private(set) var lastComposedPDFURL: URL?
/// Currently bound capture combo (the last one Carbon accepted, or the preferred load).
private(set) var captureHotkey: HotkeyPreference
var hotkeyDisplayString: String { captureHotkey.displayString }
/// Staged update offered in the menu. Set only after checksum + payload validation.
public private(set) var updateAvailable: (version: String, notes: String)?
/// True for the duration of any appcast check (manual or scheduled).
public private(set) var isCheckingForUpdates: Bool = false
let paths: AppSupportPaths
let spool: SpoolStore
let composer: PDFComposer
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,
spool: SpoolStore,
composer: PDFComposer,
capturer: ScreenCapturer,
hotkeys: HotkeyCenter,
picker: RegionPickerController,
ledger: ReturnLedger,
watcher: ReturnWatcher,
retentionDefaults: UserDefaults = .standard
) {
self.retentionDefaults = retentionDefaults
self.paths = paths
self.spool = spool
self.composer = composer
self.capturer = capturer
self.hotkeys = hotkeys
self.picker = picker
self.ledger = ledger
self.watcher = watcher
self.session = CaptureSession(
id: UUID(),
createdAt: Date(),
state: .open,
captures: [],
pdfFileName: nil
)
self.region = Self.loadPersistedRegion()
self.screenRecordingGranted = ScreenCapturer.isScreenRecordingGranted
// Seeded from TransportSettings.effectiveFolders() — the one place that combines
// the transport choice with FolderSettings/OneDriveLocator. Never call
// FolderSettings.resolve() directly outside that function.
let folders = TransportSettings.effectiveFolders()
self.outboxURL = folders.outbox
self.watchFolderURL = folders.watch
self.outboxDisplayName = folders.outbox.lastPathComponent
self.watchFolderDisplayName = folders.watch.lastPathComponent
self.transport = folders.transport
self.resolvedOneDriveFolder = OneDriveLocator.resolveOneDriveFolder()
self.captureHotkey = HotkeyPreference.load()
self.updateChecker = UpdateChecker()
self.updateChecker.onChecked = { [weak self] in
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
}
}
/// CFBundleShortVersionString of the running app.
public var appVersion: String { UpdateChecker.currentVersion() }
/// Version recorded in the app-managed rollback copy, when one exists.
public var previousVersion: String? { updateChecker.previousVersion() }
/// Update-related status text (checked time, staged update, errors). Displayed only in the footer.
public var updateStatusMessage: String? { updateStatus }
// MARK: Seam mutators — the only way a WP-4b/4c extension changes state.
func setStatus(_ text: String?) { statusLine = text }
func setUpdateStatus(_ text: String?) { updateStatus = text }
func setSending(_ value: Bool) { isSending = value }
/// Fixture seam (same family as setSending): lets tests/PanelSnapshot stage the
/// in-flight-start state that production only ever reaches inside startNewSession().
func setStartingNewSession(_ value: Bool) { isStartingNewSession = value }
func setCapturing(_ value: Bool) { isCapturing = value }
func replaceSession(_ new: CaptureSession) { session = new }
func replaceRegion(_ new: CaptureRegion?) { region = new }
func setReturns(all: [ReturnedDocument], commented: [ReturnedDocument]) {
allReturns = all
commentedReturns = commented
}
func 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
}
func setFolderURLs(outbox: URL, watch: URL) {
outboxURL = outbox
watchFolderURL = watch
setFolderDisplayNames(outbox: outbox.lastPathComponent, watch: watch.lastPathComponent)
}
func setTransport(_ value: SendTransport) { transport = value }
func setResolvedOneDriveFolder(_ value: URL?) { resolvedOneDriveFolder = value }
/// Bumped by chooseTransport/chooseOneDriveFolder (SettingsView.swift) before each
/// spawns its async watcher-reconcile Task; that Task checks its own snapshot
/// against the live value before every mutating step, so rapid toggling always
/// 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<Void, Never>?
/// 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
/// Send can never race ahead of the reconcile it depends on (the watcher's
/// recordUncommented flag briefly lagging the just-chosen transport, for example).
/// `Task<Void, Never>` never throws; awaiting an already-completed task's `.value`
/// returns immediately. Not `@Observable`-relevant — pure internal bookkeeping.
var pendingReconcileTask: Task<Void, Never>?
func rememberLastComposedPDF(_ url: URL) { lastComposedPDFURL = url }
/// True when a last-composed PDF path is known this run, or the newest
/// `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<ReviewContext, String>, _ 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])
}
func revealablePDFURL() -> URL? {
if let last = lastComposedPDFURL, FileManager.default.fileExists(atPath: last.path) {
return last
}
return newestOutboxRedlinePDF()
}
func newestOutboxRedlinePDF() -> URL? {
let fm = FileManager.default
let items = (try? fm.contentsOfDirectory(
at: outboxURL,
includingPropertiesForKeys: [.contentModificationDateKey],
options: [.skipsHiddenFiles]
)) ?? []
let matches = items.filter {
$0.lastPathComponent.hasPrefix("Redline-") && $0.pathExtension.lowercased() == "pdf"
}
return matches.max { a, b in
let da = (try? a.resourceValues(forKeys: [.contentModificationDateKey])
.contentModificationDate) ?? .distantPast
let db = (try? b.resourceValues(forKeys: [.contentModificationDateKey])
.contentModificationDate) ?? .distantPast
return da < db
}
}
public var iconState: MenuIconState {
if !screenRecordingGranted { return .recordingMissing }
if isCapturing { return .capturing }
if region == nil { return .noRegion }
if session.captures.isEmpty { return .regionEmpty }
return .hasCaptures(session.captures.count)
}
public func bootstrap() async {
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 {
replaceRegion(decoded)
}
do {
let recovered = try await spool.currentSession()
replaceSession(recovered)
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not open the spool.")
}
do {
let initial = try await ledger.all()
let commented = try await ledger.commented()
setReturns(all: initial, commented: commented)
} catch {
// Empty ledger on first run is not an error.
}
// 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.
// Also make sure the resolved OneDrive folder actually exists before the
// watcher starts watching it (bootstrap is the other creation trigger besides
// chooseTransport/chooseOneDriveFolder — see TransportSettings.effectiveFolders).
if transport == .oneDrive {
try? FileManager.default.createDirectory(at: outboxURL, withIntermediateDirectories: true)
}
setResolvedOneDriveFolder(OneDriveLocator.resolveOneDriveFolder())
await watcher.setRecordUncommented(transport == .airDrop)
do {
// BLOCKER fix: reconcile the watcher's internal watchFolder with the live
// watchFolderURL UNCONDITIONALLY, before it ever starts. `paths` (and so the
// watcher's initial folder, set in its own init) now comes from the same
// transport-aware TransportSettings.effectiveFolders() as watchFolderURL, so
// in the normal case this is a no-op — but it is the only thing that would
// have caught the old bug (launch paths built AirDrop-only while OneDrive was
// the persisted transport, leaving the watcher's FSEvents stream pointed at a
// stale folder for the whole session) and it stays cheap insurance against
// that class of drift ever recurring. Calling it before start() only updates
// the stored folder — no FSEvents stream exists yet to restart.
try await watcher.updateWatchFolder(watchFolderURL)
try await watcher.start { [weak self] _ in
Task { @MainActor in
guard let self else { return }
let all = (try? await self.ledger.all()) ?? []
let commented = (try? await self.ledger.commented()) ?? []
self.setReturns(all: all, commented: commented)
}
}
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not watch the return folder.")
}
// Env-var-flagged self-test/headless runs (PickerSelfTest's phases, PanelSnapshot,
// and the new ShotdeckTests launch-wiring regression test) skip two real-world
// side effects that are unsafe or meaningless in that context: the update-check
// schedule (a real network call), and binding the REAL, process-wide Carbon
// global hotkey — which is not safe to exercise in an automated/parallel test
// process (it can collide with ShotdeckCoreTests' own HotkeyCenterCarbonTests
// running in the same test binary) and was never meaningfully exercised by any
// self-test anyway. A real user launch never sets these env vars, so production
// behavior is unchanged.
let isSelfTestRun =
ProcessInfo.processInfo.environment["SHOTDECK_PICKER_SELFTEST"] != nil
|| ProcessInfo.processInfo.environment["SHOTDECK_SNAPSHOT_DIR"] != nil
|| ProcessInfo.processInfo.environment["SHOTDECK_UPDATE_SELFTEST"] != nil
|| ProcessInfo.processInfo.environment["SHOTDECK_ONEDRIVE_SELFTEST"] != nil
|| ProcessInfo.processInfo.environment["REDLINE_SELFTEST_PHASE"] != nil
let pref = HotkeyPreference.load()
captureHotkey = pref
if !isSelfTestRun, !bindCaptureHotkey(pref) {
setStatus("\(pref.displayString) is already used by another app — capture only works from the menu.")
}
if !isSelfTestRun {
updateChecker.startSchedule()
}
}
/// 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() {
updateChecker.installStaged()
}
/// User-initiated appcast check ("Check for updates" menu row).
public func checkForUpdates() {
Task { @MainActor in
await updateChecker.checkNow(manual: true)
}
}
/// Reverts `/Applications/Redline.app` to the app-managed rollback copy and relaunches.
/// Does nothing unless a `Redline.app.previous` exists and the user clicked the row.
public func revertToPreviousVersion() {
updateChecker.revertToPrevious()
}
/// Unregisters `capture` and binds `HotkeyPreference.load()`. If Carbon rejects the new
/// combo, restores the previous preference (UserDefaults + Carbon) so the old one keeps working.
func reRegisterHotkey() {
let previous = captureHotkey
let next = HotkeyPreference.load()
hotkeys.unregister(id: "capture")
if bindCaptureHotkey(next) {
captureHotkey = next
return
}
setStatus("That combination is taken — pick another.")
previous.save()
if bindCaptureHotkey(previous) {
captureHotkey = previous
}
}
@discardableResult
private func bindCaptureHotkey(_ pref: HotkeyPreference) -> Bool {
hotkeys.register(
id: "capture",
keyCode: pref.keyCode,
modifiers: pref.modifiers
) { [weak self] in
Task { await self?.captureNow() }
}
}
/// 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) }
do {
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,
pixelHeight: image.pixelHeight,
scale: image.scale,
capturedAt: Date()
)
replaceSession(try await spool.currentSession())
setStatus("Captured page \(capture.sequence).")
} catch {
screenRecordingGranted = ScreenCapturer.isScreenRecordingGranted
setStatus((error as? ShotdeckError)?.errorDescription ?? "The screenshot could not be taken.")
}
}
/// 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())
}
}
/// 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<CaptureRegion?, Never>) 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<CaptureTarget?, Never>) 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("\(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 {
do {
// D-11: SpoolStore.remove MOVES the PNG to <session>/removed/; it is never unlinked.
replaceSession(try await spool.remove(captureID: id))
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Could not remove that capture.")
}
}
/// True when "Start new session" applies: there is something to keep and neither a
/// send nor another session start is in flight.
public var canStartNewSession: Bool {
!session.isEmpty && !isSending && !isStartingNewSession
}
/// Menu "Start new session": keeps the current screenshots as a past session
/// (moved into the single archive folder — never deleted) and opens a fresh empty
/// session. Session retention (newest 10 kept) is applied inside the store, on
/// this path and on the send path alike.
public func startNewSession() async {
// Re-checked here on the main actor, synchronously, before the first await:
// the menu's `.disabled` state cannot stop a Task that was queued just before
// a send started.
guard !isSending, !isStartingNewSession else {
setStatus(isSending ? "Finish the current send first." : "A new session is already being started.")
return
}
isStartingNewSession = true
defer { isStartingNewSession = false }
var message: String
do {
if let archived = try await spool.closeCurrentSession() {
let count = archived.captures.count
message = "New session — \(count) capture\(count == 1 ? "" : "s") kept as a past session."
} else {
message = "New session started."
}
} catch {
message = (error as? ShotdeckError)?.errorDescription ?? "Could not start a new session."
}
if let refreshProblem = await reloadFromSpool() {
message += " \(refreshProblem)"
}
selectSession(session.id)
setStatus(message)
}
/// Re-reads the open session and the past-session list from the store. Returns a
/// problem description when either read failed (the caller decides how to surface
/// it), nil when everything was refreshed — never silently substitutes stale state.
func reloadFromSpool() async -> String? {
var problems: [String] = []
do {
replaceSession(try await spool.currentSession())
} catch {
problems.append(
"Could not reload the current session: \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription)")
}
do {
setPastSessions(try await spool.archivedSessions())
} catch {
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: " ")
}
/// Where a past session's sent PDF lives now (the outbox in AirDrop mode, the
/// OneDrive folder in OneDrive mode), or nil when it was never sent / is gone.
public func sentPDFURL(for session: CaptureSession) -> URL? {
guard let name = session.pdfFileName else { return nil }
let url = outboxURL.appendingPathComponent(name)
return FileManager.default.fileExists(atPath: url.path) ? url : nil
}
/// "PDF" action on a past-submission row: reveals the exact PDF that was sent.
public func revealSentPDF(_ session: CaptureSession) {
guard session.pdfFileName != nil else {
setStatus("That session was never sent.")
return
}
guard let url = sentPDFURL(for: session) else {
setStatus("The PDF is no longer in \(outboxDisplayName).")
return
}
NSWorkspace.shared.activateFileViewerSelecting([url])
}
/// "Captures" action on a past-submission row: reveals that session's folder.
public func revealSessionCaptures(_ session: CaptureSession) {
let dir = paths.archiveDirectory(session.id)
guard FileManager.default.fileExists(atPath: dir.path) else {
setStatus("That past session is no longer on disk.")
return
}
NSWorkspace.shared.activateFileViewerSelecting([dir])
}
/// The single folder every retained session lives in.
public func openSessionsFolder() {
NSWorkspace.shared.open(paths.archive)
}
public func copyCommentedLinks() async {
do {
let text = try await ledger.clipboardText()
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.setString(text, forType: .string)
let count = commentedReturns.count
setStatus("Copied \(count) link\(count == 1 ? "" : "s").")
} catch {
setStatus((error as? ShotdeckError)?.errorDescription ?? "Nothing to copy.")
}
}
public func openSpoolFolder() {
NSWorkspace.shared.open(paths.spool)
}
public func openScreenRecordingSettings() {
guard let url = URL(string:
"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture") else {
setStatus("Could not open System Settings.")
return
}
NSWorkspace.shared.open(url)
}
static func loadPersistedRegion() -> CaptureRegion? {
guard let data = UserDefaults.standard.data(forKey: CaptureRegion.defaultsKey),
let decoded = try? JSONDecoder().decode(CaptureRegion.self, from: data),
decoded.isStillValid
else { return nil }
return decoded
}
private func persistRegion(_ picked: CaptureRegion) {
replaceRegion(picked)
if let encoded = try? JSONEncoder().encode(picked) {
UserDefaults.standard.set(encoded, forKey: CaptureRegion.defaultsKey)
}
}
}
public enum MenuIconState: Equatable {
case noRegion, regionEmpty, hasCaptures(Int), capturing, recordingMissing
public var symbolName: String {
switch self {
case .noRegion: return "viewfinder"
case .regionEmpty: return "viewfinder.rectangular"
case .hasCaptures: return "viewfinder.rectangular"
case .capturing: return "viewfinder.circle.fill"
case .recordingMissing: return "exclamationmark.triangle"
}
}
public var countText: String? {
if case .hasCaptures(let n) = self { return "\(n)" }
return nil
}
}