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 /// 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 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.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 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? /// 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` never throws; awaiting an already-completed task's `.value` /// returns immediately. Not `@Observable`-relevant — pure internal bookkeeping. var pendingReconcileTask: Task? 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, _ 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) 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() } } /// 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() } } } public func captureNow() 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 capture = try await spool.append( pngData: image.pngData, pixelWidth: image.pixelWidth, pixelHeight: image.pixelHeight, scale: image.scale, capturedAt: Date() ) replaceSession(try await spool.currentSession()) setStatus("Captured page \(capture.sequence).") } catch { screenRecordingGranted = ScreenCapturer.isScreenRecordingGranted setStatus((error as? ShotdeckError)?.errorDescription ?? "The screenshot could not be taken.") } } public func rePickRegion() async { let picked = await withCheckedContinuation { (cont: CheckedContinuation) in picker.pick { cont.resume(returning: $0) } } guard let picked else { return } persistRegion(picked) setStatus("Region set: \(Int(picked.rect.width)) × \(Int(picked.rect.height)).") } public func removeCapture(id: UUID) async { do { // D-11: SpoolStore.remove MOVES the PNG to /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 } }