639 lines
36 KiB
Swift
639 lines
36 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
||
import Foundation
|
||
import SwiftUI
|
||
import AppKit
|
||
import UniformTypeIdentifiers
|
||
import Darwin
|
||
import Combine
|
||
|
||
enum CoCoCaptureFiles {
|
||
static func folder(_ folder: URL) throws {
|
||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
||
guard FileManager.default.isWritableFile(atPath: folder.path) else { throw CoCoRecordingError.message("The capture folder is not writable. Choose another folder in Capture Settings.") }
|
||
}
|
||
/// Atomic same-volume rename with no replacement, including simultaneous captures.
|
||
static func promote(_ temporary: URL, folder: URL, name: String, extension ext: String) throws -> URL {
|
||
for n in 0..<10_000 {
|
||
let target = folder.appendingPathComponent(name + (n == 0 ? "" : "-\(n)")).appendingPathExtension(ext)
|
||
if renamex_np(temporary.path, target.path, UInt32(RENAME_EXCL)) == 0 { return target }
|
||
if errno != EEXIST { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) }
|
||
}
|
||
throw CoCoRecordingError.message("A unique capture filename could not be reserved.")
|
||
}
|
||
static func stamp(_ date: Date = Date()) -> String {
|
||
let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX"); f.dateFormat = "yyyy-MM-dd HH-mm-ss"
|
||
return f.string(from: date)
|
||
}
|
||
static func save(_ capture: ScreenCapture, folder: URL) throws -> URL {
|
||
try self.folder(folder)
|
||
let temp = folder.appendingPathComponent(".vcc-screen-\(UUID().uuidString).png")
|
||
defer { try? FileManager.default.removeItem(at: temp) }
|
||
try capture.save(to: temp)
|
||
return try promote(temp, folder: folder, name: "VCC Plus Screen " + stamp(), extension: "png")
|
||
}
|
||
}
|
||
|
||
@MainActor final class CoCoCapturePreferences: ObservableObject {
|
||
enum Destination: String { case desktop, documents, other }
|
||
@Published private(set) var folder: URL
|
||
@Published private(set) var preparingDestination = false
|
||
@Published private(set) var timerSeconds: Int
|
||
@Published var includeVideoAudio: Bool { didSet { defaults.set(includeVideoAudio, forKey: "capture.video.includeAudio") } }
|
||
var screenshots: URL { folder }
|
||
var recordings: URL { folder }
|
||
private let defaults: UserDefaults
|
||
private let fallbackRoot: URL?
|
||
private let makeBookmark: @Sendable (URL) throws -> Data
|
||
private var selectionRevision: UInt64 = 0
|
||
private var scopes: [URL] = []
|
||
var desktop: URL { fallbackRoot ?? FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask)[0] }
|
||
var documents: URL { fallbackRoot?.appendingPathComponent("Documents", isDirectory: true) ?? FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] }
|
||
var destination: Destination {
|
||
if folder.standardizedFileURL == desktop.standardizedFileURL { return .desktop }
|
||
if folder.standardizedFileURL == documents.standardizedFileURL { return .documents }
|
||
return .other
|
||
}
|
||
init(defaults: UserDefaults, fallbackRoot: URL? = nil,
|
||
makeBookmark: @escaping @Sendable (URL) throws -> Data = { url in
|
||
try url.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
|
||
}) {
|
||
self.defaults = defaults; self.fallbackRoot = fallbackRoot; self.makeBookmark = makeBookmark
|
||
let desktop = fallbackRoot ?? FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask)[0]
|
||
let documents = fallbackRoot?.appendingPathComponent("Documents", isDirectory: true)
|
||
?? FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
|
||
let stored = defaults.string(forKey: "capture.destination").flatMap(Destination.init(rawValue:))
|
||
let timer = defaults.integer(forKey: "capture.timer.seconds")
|
||
timerSeconds = [0, 5, 10].contains(timer) ? timer : 0
|
||
includeVideoAudio = defaults.object(forKey: "capture.video.includeAudio") as? Bool ?? true
|
||
if stored == .desktop || stored == .documents {
|
||
// Built-in choices are logical locations, not security bookmarks.
|
||
// Neither selection nor restore touches a cloud-backed directory.
|
||
folder = stored == .documents ? documents : desktop
|
||
} else {
|
||
func resolve(_ key: String) -> URL? {
|
||
guard let data = defaults.data(forKey: key) else { return nil }
|
||
var stale = false
|
||
guard let url = try? URL(resolvingBookmarkData: data, options: [.withSecurityScope, .withoutUI],
|
||
relativeTo: nil, bookmarkDataIsStale: &stale), url.isFileURL else { return nil }
|
||
return url
|
||
}
|
||
let shared = resolve("capture.folder.shared")
|
||
var legacy: (url: URL, bookmark: Data)?
|
||
if shared == nil {
|
||
for key in ["capture.folder.screenshots", "capture.folder.recordings"] {
|
||
if let url = resolve(key), let bookmark = defaults.data(forKey: key) {
|
||
legacy = (url, bookmark); break
|
||
}
|
||
}
|
||
}
|
||
folder = shared ?? legacy?.url ?? desktop
|
||
if let legacy { defaults.set(legacy.bookmark, forKey: "capture.folder.shared") }
|
||
if folder.standardizedFileURL == desktop.standardizedFileURL {
|
||
if shared != nil || legacy != nil { defaults.set(Destination.desktop.rawValue, forKey: "capture.destination") }
|
||
} else if folder.standardizedFileURL == documents.standardizedFileURL {
|
||
defaults.set(Destination.documents.rawValue, forKey: "capture.destination")
|
||
} else if shared != nil || legacy != nil {
|
||
defaults.set(Destination.other.rawValue, forKey: "capture.destination")
|
||
if folder.startAccessingSecurityScopedResource() { scopes.append(folder) }
|
||
}
|
||
}
|
||
}
|
||
func setTimerSeconds(_ seconds: Int) {
|
||
guard [0, 5, 10].contains(seconds) else { return }
|
||
timerSeconds = seconds; defaults.set(seconds, forKey: "capture.timer.seconds")
|
||
}
|
||
private func beginChoice() -> UInt64 {
|
||
selectionRevision &+= 1; preparingDestination = false
|
||
return selectionRevision
|
||
}
|
||
func setFolder(_ url: URL) async throws {
|
||
try await prepareFolder(url, revision: beginChoice())
|
||
}
|
||
private func prepareFolder(_ url: URL, revision: UInt64) async throws {
|
||
guard url.isFileURL else { throw CoCoRecordingError.message("Choose a local capture folder.") }
|
||
guard revision == selectionRevision else { throw CancellationError() }
|
||
// Selecting a built-in through Other Location has the same logical
|
||
// semantics and never creates an unnecessary security bookmark.
|
||
if url.standardizedFileURL == desktop.standardizedFileURL { setDestination(.desktop); return }
|
||
if url.standardizedFileURL == documents.standardizedFileURL { setDestination(.documents); return }
|
||
preparingDestination = true
|
||
let makeBookmark = makeBookmark
|
||
do {
|
||
let grant = try await Task.detached(priority: .userInitiated) {
|
||
let data = try makeBookmark(url)
|
||
return (data, url.startAccessingSecurityScopedResource())
|
||
}.value
|
||
guard revision == selectionRevision else {
|
||
if grant.1 { Task.detached(priority: .utility) { url.stopAccessingSecurityScopedResource() } }
|
||
throw CancellationError()
|
||
}
|
||
// Keep old grants while an in-flight movie still owns its folder.
|
||
if grant.1 { scopes.append(url) }
|
||
defaults.set(grant.0, forKey: "capture.folder.shared")
|
||
defaults.set(Destination.other.rawValue, forKey: "capture.destination")
|
||
folder = url; preparingDestination = false
|
||
} catch {
|
||
guard revision == selectionRevision else { throw CancellationError() }
|
||
preparingDestination = false; throw error
|
||
}
|
||
}
|
||
func setDestination(_ value: Destination) {
|
||
if value == .other { choose(); return }
|
||
_ = beginChoice()
|
||
folder = value == .desktop ? desktop : documents
|
||
defaults.set(value.rawValue, forKey: "capture.destination")
|
||
}
|
||
func choose() {
|
||
let revision = beginChoice()
|
||
let panel = NSOpenPanel(); panel.title = "Save Screenshots and Videos To"
|
||
panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true
|
||
panel.directoryURL = folder
|
||
panel.begin { [weak self] response in
|
||
guard let self, revision == self.selectionRevision, response == .OK, let url = panel.url else { return }
|
||
Task {
|
||
do { try await self.prepareFolder(url, revision: revision) }
|
||
catch is CancellationError { }
|
||
catch { NSAlert(error: error).runModal() }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
struct CoCoRecordingRecovery: Codable, Identifiable {
|
||
let id: UUID
|
||
let created: Date
|
||
let directory: URL
|
||
var working: URL { directory.appendingPathComponent("Working.mov") }
|
||
}
|
||
private struct CoCoRecoveryDocument: Codable {
|
||
var version = 1
|
||
var recordings: [CoCoRecordingRecovery]
|
||
}
|
||
|
||
/// Owns recording transport independently of AppKit's modal/main run loop.
|
||
/// UI progress is observational: it never clocks or drains the movie pipeline.
|
||
private actor CoCoRecordingSession {
|
||
struct Completion: Sendable { let movie: URL?; let error: String? }
|
||
private let controller: VCCMachineController
|
||
private let encoder: CoCoVideoEncoder
|
||
private let includeAudio: Bool
|
||
private let folder: URL
|
||
private let failed: @Sendable (String) -> Void
|
||
private let replies = DispatchQueue(label: "com.brianholman.vccplus.capture-replies", qos: .userInitiated)
|
||
private var pump: Task<Void, Never>?
|
||
private var finalization: Task<Completion, Never>?
|
||
private var capacityCheck: Task<Void, Never>?
|
||
private var failureMessage: String?
|
||
private var started = false
|
||
|
||
init(controller: VCCMachineController, encoder: CoCoVideoEncoder, includeAudio: Bool, folder: URL,
|
||
failed: @escaping @Sendable (String) -> Void) {
|
||
self.controller = controller; self.encoder = encoder; self.includeAudio = includeAudio
|
||
self.folder = folder; self.failed = failed
|
||
}
|
||
func start() async throws -> TimeInterval {
|
||
let snapshot = await withCheckedContinuation { continuation in
|
||
controller.beginVideoCapture(replyQueue: replies) { continuation.resume(returning: $0) }
|
||
}
|
||
if let message = snapshot.errorMessage { throw CoCoRecordingError.message(message) }
|
||
started = true
|
||
let origin = ProcessInfo.processInfo.systemUptime
|
||
encoder.failure = { [weak self] message in Task { await self?.fail(message) } }
|
||
pump = Task { [weak self] in guard let self else { return }; await self.run() }
|
||
return origin
|
||
}
|
||
private func packets(finish: Bool) async -> ([CoCoVideoFrame], String?) {
|
||
let includeAudio = includeAudio
|
||
return await withCheckedContinuation { continuation in
|
||
controller.takeVideoCapture(finish: finish, replyQueue: replies) { packets, error in
|
||
continuation.resume(returning: (packets.map {
|
||
CoCoCaptureCoordinator.videoFrame(pixels: $0.pixels, area: $0.activeArea,
|
||
audio: $0.samples, sampleOffset: Int64($0.sampleOffset), includeAudio: includeAudio)
|
||
}, error))
|
||
}
|
||
}
|
||
}
|
||
private func run() async {
|
||
var nextCapacityCheck: TimeInterval = 0
|
||
while !Task.isCancelled {
|
||
let result = await packets(finish: false)
|
||
// Cancellation cannot discard bytes already drained by this pull.
|
||
encoder.append(result.0)
|
||
if let message = result.1 { fail(message); return }
|
||
guard !Task.isCancelled else { return }
|
||
let now = ProcessInfo.processInfo.systemUptime
|
||
if now >= nextCapacityCheck {
|
||
nextCapacityCheck = now + 5; checkCapacity()
|
||
}
|
||
do { try await Task.sleep(for: .milliseconds(16)) } catch { return }
|
||
}
|
||
}
|
||
private func checkCapacity() {
|
||
guard capacityCheck == nil, finalization == nil else { return }
|
||
let folder = folder
|
||
capacityCheck = Task { [weak self] in
|
||
let free = await Task.detached(priority: .utility) {
|
||
try? folder.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage
|
||
}.value
|
||
await self?.acceptCapacity(free)
|
||
}
|
||
}
|
||
private func acceptCapacity(_ free: Int64?) {
|
||
capacityCheck = nil
|
||
guard finalization == nil, let free, free < 256 * 1024 * 1024 else { return }
|
||
fail("Recording stopped because the destination is low on space. The working movie is retained.")
|
||
}
|
||
private func fail(_ message: String) {
|
||
guard failureMessage == nil else { return }
|
||
failureMessage = message
|
||
_ = beginFinalization()
|
||
failed(message)
|
||
}
|
||
private func beginFinalization() -> Task<Completion, Never> {
|
||
if let finalization { return finalization }
|
||
let draining = pump; pump = nil; draining?.cancel()
|
||
let final = Task { [self] in
|
||
// One owner waits for the in-flight pull, takes the final tail and
|
||
// finishes the writer. User Stop and failures share this result.
|
||
await draining?.value
|
||
if started {
|
||
let tail = await packets(finish: true)
|
||
encoder.append(tail.0)
|
||
if failureMessage == nil { failureMessage = tail.1 }
|
||
}
|
||
let result: Result<URL, Error> = await withCheckedContinuation { continuation in
|
||
encoder.finish { continuation.resume(returning: $0) }
|
||
}
|
||
switch result {
|
||
case .success(let url): return Completion(movie: url, error: failureMessage)
|
||
case .failure(let error): return Completion(movie: nil, error: failureMessage ?? error.localizedDescription)
|
||
}
|
||
}
|
||
finalization = final
|
||
return final
|
||
}
|
||
func finish(failure: String? = nil) async -> Completion {
|
||
if let failure { fail(failure) }
|
||
return await beginFinalization().value
|
||
}
|
||
func currentFailure() -> String? { failureMessage }
|
||
}
|
||
|
||
@MainActor final class CoCoCaptureCoordinator: ObservableObject {
|
||
enum State: Equatable { case idle, starting, recording, finishing }
|
||
@Published private(set) var state: State = .idle
|
||
@Published private(set) var countdown: Int?
|
||
@Published private(set) var elapsed: TimeInterval = 0
|
||
@Published private(set) var saving = false
|
||
@Published var error: String?
|
||
@Published private(set) var saved: URL?
|
||
@Published private(set) var recoveries: [CoCoRecordingRecovery] = []
|
||
@Published var settingsShown = false
|
||
let preferences: CoCoCapturePreferences
|
||
private weak var machine: MachineModel?
|
||
private let controller: VCCMachineController
|
||
private var countdownTask: Task<Void, Never>?
|
||
private var recordingTask: Task<Void, Never>?
|
||
private var pendingImage: ScreenCapture?
|
||
private var session: CoCoRecordingSession?
|
||
private var recovery: CoCoRecordingRecovery?
|
||
private var start = ProcessInfo.processInfo.systemUptime
|
||
private var recoveryURL: URL
|
||
private var canWriteRecovery = true
|
||
private let feedback: (CoCoCaptureFeedback.Cue) -> Void
|
||
var active: Bool { state != .idle }
|
||
var recording: Bool { state == .recording }
|
||
lazy var menuState = CoCoCaptureMenuState(self)
|
||
|
||
init(machine: MachineModel, controller: VCCMachineController, defaults: UserDefaults, directory: URL,
|
||
feedback: ((CoCoCaptureFeedback.Cue) -> Void)? = nil) {
|
||
self.machine = machine; self.controller = controller
|
||
self.feedback = feedback ?? CoCoCaptureFeedback.play
|
||
#if VCC_UI_TESTING
|
||
let root = ProcessInfo.processInfo.environment["VCC_CAPTURE_TEST_DIRECTORY"].map { URL(fileURLWithPath: $0, isDirectory: true) } ?? directory.appendingPathComponent("Captures")
|
||
preferences = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root)
|
||
#else
|
||
preferences = CoCoCapturePreferences(defaults: defaults)
|
||
#endif
|
||
recoveryURL = directory.appendingPathComponent("CaptureRecovery.json")
|
||
if let data = try? Data(contentsOf: recoveryURL) {
|
||
do {
|
||
guard data.count <= 1_048_576 else { throw CoCoRecordingError.message("The recording recovery record is too large.") }
|
||
let document = try JSONDecoder().decode(CoCoRecoveryDocument.self, from: data)
|
||
guard document.version == 1 else { throw CoCoRecordingError.message("A newer recording recovery version has been preserved.") }
|
||
let records = document.recordings
|
||
guard records.allSatisfy({ $0.directory.isFileURL && $0.directory.lastPathComponent == ".vcc-recording-" + $0.id.uuidString }) else {
|
||
throw CoCoRecordingError.message("The recording recovery record is invalid.")
|
||
}
|
||
recoveries = records
|
||
} catch { self.error = "Recording recovery data was preserved but could not be read: \(error.localizedDescription)"; canWriteRecovery = false }
|
||
}
|
||
}
|
||
|
||
/// The camera is the action; selecting menu options only changes preferences.
|
||
func capture() {
|
||
if preferences.timerSeconds == 0 { captureNow() } else { delay(preferences.timerSeconds) }
|
||
}
|
||
func captureNow() {
|
||
guard !saving, pendingImage == nil, countdown == nil, let machine else { return }
|
||
do {
|
||
pendingImage = try ScreenCapture(pixels: machine.pixels, area: machine.activeVideoRect)
|
||
feedback(.screenshot)
|
||
savePending()
|
||
}
|
||
catch { self.error = error.localizedDescription }
|
||
}
|
||
private func savePending() {
|
||
guard let image = pendingImage else { return }
|
||
saving = true; error = nil
|
||
let folder = preferences.screenshots
|
||
Task {
|
||
defer { saving = false }
|
||
do {
|
||
saved = try await Task.detached(priority: .userInitiated) { try CoCoCaptureFiles.save(image, folder: folder) }.value
|
||
pendingImage = nil
|
||
} catch { self.error = error.localizedDescription }
|
||
}
|
||
}
|
||
func saveImageAs() {
|
||
guard let image = pendingImage, !saving else { return }
|
||
let panel = NSSavePanel(); panel.title = "Save Captured CoCo Screen"; panel.allowedContentTypes = [.png]
|
||
panel.nameFieldStringValue = "VCC Plus Screen " + CoCoCaptureFiles.stamp() + ".png"
|
||
panel.begin { [weak self] result in
|
||
guard let self, result == .OK, let url = panel.url else { return }
|
||
self.saving = true
|
||
Task { [self] in
|
||
defer { self.saving = false }
|
||
do {
|
||
try await Task.detached { try image.save(to: url) }.value
|
||
self.pendingImage = nil; self.saved = url; self.error = nil
|
||
} catch { self.error = error.localizedDescription }
|
||
}
|
||
}
|
||
}
|
||
func discardImage() { guard !saving else { return }; pendingImage = nil; error = nil }
|
||
var hasPendingImage: Bool { pendingImage != nil }
|
||
func delay(_ seconds: Int) {
|
||
guard [5, 10].contains(seconds), !saving, pendingImage == nil else { return }
|
||
cancelCountdown(); countdown = seconds
|
||
countdownTask = Task { [weak self] in
|
||
for remaining in stride(from: seconds, through: 1, by: -1) {
|
||
guard let self, !Task.isCancelled else { return }; countdown = remaining
|
||
do { try await Task.sleep(for: .seconds(1)) } catch { return }
|
||
}
|
||
guard let self, !Task.isCancelled else { return }; countdown = nil; captureNow()
|
||
}
|
||
}
|
||
func cancelCountdown() { countdownTask?.cancel(); countdownTask = nil; countdown = nil }
|
||
|
||
func startRecording() {
|
||
guard state == .idle, let machine, machine.pixels != nil else { return }
|
||
if machine.settings.fastForward {
|
||
error = "Turn off fast-forward before recording video. No machine setting has been changed."; return
|
||
}
|
||
guard canWriteRecovery else { error = "Resolve the preserved recording recovery record before starting another movie."; return }
|
||
state = .starting; error = nil
|
||
let includeAudio = preferences.includeVideoAudio
|
||
let folder = preferences.recordings
|
||
Task { [self] in
|
||
do {
|
||
let entry = CoCoRecordingRecovery(id: UUID(), created: Date(), directory: folder.appendingPathComponent(".vcc-recording-" + UUID().uuidString))
|
||
// Directory identity is tied to its recovery ID; never clean a user folder.
|
||
let record = CoCoRecordingRecovery(id: entry.id, created: entry.created,
|
||
directory: folder.appendingPathComponent(".vcc-recording-" + entry.id.uuidString, isDirectory: true))
|
||
let newEncoder = try await Task.detached { try CoCoCaptureFiles.folder(record.directory); return try CoCoVideoEncoder(workingURL: record.working) }.value
|
||
let backend = CoCoRecordingSession(controller: controller, encoder: newEncoder,
|
||
includeAudio: includeAudio, folder: folder) { [weak self] message in
|
||
Task { @MainActor in
|
||
guard let self, self.recovery?.id == record.id else { return }
|
||
self.error = message
|
||
await self.stopRecording(failed: true)
|
||
}
|
||
}
|
||
session = backend
|
||
recovery = record; recoveries.append(record); try await persistRecovery()
|
||
let origin = try await backend.start()
|
||
state = .recording; start = origin; elapsed = ProcessInfo.processInfo.systemUptime - origin
|
||
let startupFailure = await backend.currentFailure()
|
||
// A failure notification can finish this session while the
|
||
// status query suspends us. Never publish a stale success cue
|
||
// or resurrect its progress task after that finalization.
|
||
guard recovery?.id == record.id, state == .recording else { return }
|
||
if let startupFailure {
|
||
error = startupFailure; await stopRecording(failed: true); return
|
||
}
|
||
feedback(.recordingStarted)
|
||
recordingTask = Task { [weak self] in
|
||
while !Task.isCancelled {
|
||
guard let self, state == .recording else { return }
|
||
elapsed = ProcessInfo.processInfo.systemUptime - start
|
||
do { try await Task.sleep(for: .milliseconds(250)) } catch { return }
|
||
}
|
||
}
|
||
} catch {
|
||
self.error = error.localizedDescription
|
||
// Even a failed bridge start may own a writer. Recovery and
|
||
// quit must wait until that writer has finished its last work.
|
||
state = .finishing
|
||
if let session { _ = await session.finish(failure: self.error) }
|
||
session = nil; recovery = nil; state = .idle
|
||
}
|
||
}
|
||
}
|
||
/// Keep the recording clock and packet duration unchanged for silent video.
|
||
/// Only emulated PCM is selected here; host shutter/start cues never enter it.
|
||
nonisolated static func videoFrame(pixels: Data, area: CGRect, audio: Data, sampleOffset: Int64, includeAudio: Bool) -> CoCoVideoFrame {
|
||
CoCoVideoFrame(pixels: pixels, area: area, audio: includeAudio ? audio : Data(count: audio.count), sampleOffset: sampleOffset)
|
||
}
|
||
func stopRecording(failed: Bool = false) async {
|
||
guard state == .recording, let session, let record = recovery else { return }
|
||
state = .finishing
|
||
recordingTask?.cancel(); recordingTask = nil
|
||
let result = await session.finish(failure: failed ? (error ?? "Recording stopped with an error. The working movie is retained.") : nil)
|
||
if let message = result.error { error = message }
|
||
do {
|
||
if !failed, result.error == nil, let movie = result.movie {
|
||
try await complete(record, movie: movie, folder: record.directory.deletingLastPathComponent())
|
||
}
|
||
} catch { self.error = error.localizedDescription }
|
||
self.session = nil; recovery = nil; state = .idle
|
||
}
|
||
func recover(_ record: CoCoRecordingRecovery) {
|
||
guard state == .idle else { return }; state = .finishing; error = nil
|
||
Task {
|
||
defer { state = .idle }
|
||
do { try await complete(record, movie: record.working, folder: preferences.recordings) }
|
||
catch { self.error = "Recovery did not complete. Retained files are unchanged. \(error.localizedDescription)" }
|
||
}
|
||
}
|
||
private func complete(_ record: CoCoRecordingRecovery, movie: URL, folder: URL) async throws {
|
||
let final = try await Task.detached(priority: .userInitiated) {
|
||
try CoCoCaptureFiles.folder(folder)
|
||
let temp = folder.appendingPathComponent(".vcc-finish-" + UUID().uuidString + ".mp4")
|
||
do {
|
||
try await CoCoVideoEncoder.exportMP4(from: movie, to: temp)
|
||
return try CoCoCaptureFiles.promote(temp, folder: folder, name: "VCC Plus Video " + CoCoCaptureFiles.stamp(record.created), extension: "mp4")
|
||
} catch { try? FileManager.default.removeItem(at: temp); throw error }
|
||
}.value
|
||
saved = final
|
||
recoveries.removeAll { $0.id == record.id }; try await persistRecovery()
|
||
// Only this verified owned working file/directory is removed.
|
||
try? FileManager.default.removeItem(at: record.working)
|
||
_ = rmdir(record.directory.path) // Never remove unexpected files added to it.
|
||
}
|
||
private func persistRecovery() async throws {
|
||
guard canWriteRecovery else { throw CoCoRecordingError.message("Recovery data is read-only until repaired.") }
|
||
let records = recoveries, url = recoveryURL
|
||
try await Task.detached(priority: .utility) {
|
||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||
try JSONEncoder().encode(CoCoRecoveryDocument(recordings: records)).write(to: url, options: .atomic)
|
||
}.value
|
||
}
|
||
func stopBeforeReplacingMachine() async -> Bool {
|
||
cancelCountdown()
|
||
guard active else { return true }
|
||
guard state == .recording else { error = "Wait for the recording to finish."; return false }
|
||
let alert = NSAlert(); alert.messageText = "Stop and save the CoCo movie first?"
|
||
alert.informativeText = "Changing the machine ends this recording. Existing media safeguards still apply."
|
||
alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Stop and Continue")
|
||
guard alert.runModal() == .alertSecondButtonReturn else { return false }
|
||
let id = recovery?.id
|
||
await stopRecording(); return state == .idle && !recoveries.contains { $0.id == id }
|
||
}
|
||
}
|
||
|
||
/// Native menus observe transitions, not per-frame/elapsed-time notifications.
|
||
@MainActor final class CoCoCaptureMenuState: ObservableObject {
|
||
@Published private(set) var state: CoCoCaptureCoordinator.State
|
||
@Published private(set) var countdown = false
|
||
private var tokens: Set<AnyCancellable> = []
|
||
init(_ capture: CoCoCaptureCoordinator) {
|
||
state = capture.state
|
||
capture.$state.removeDuplicates().sink { [weak self] in self?.state = $0 }.store(in: &tokens)
|
||
capture.$countdown.map { $0 != nil }.removeDuplicates().sink { [weak self] in self?.countdown = $0 }.store(in: &tokens)
|
||
}
|
||
}
|
||
|
||
struct CoCoCaptureControls: View {
|
||
@ObservedObject var capture: CoCoCaptureCoordinator
|
||
@ObservedObject var machine: MachineModel
|
||
@ObservedObject private var preferences: CoCoCapturePreferences
|
||
init(capture: CoCoCaptureCoordinator, machine: MachineModel) {
|
||
self.capture = capture; self.machine = machine; preferences = capture.preferences
|
||
}
|
||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||
var body: some View {
|
||
HStack(spacing: 4) {
|
||
Button { capture.capture() } label: { Image(systemName: "camera").frame(width: 28, height: 28) }
|
||
.help(preferences.timerSeconds == 0 ? "Capture CoCo Screen" : "Capture CoCo Screen after \(preferences.timerSeconds) seconds").accessibilityLabel("Capture CoCo Screen")
|
||
.accessibilityIdentifier("capture-now")
|
||
.disabled(machine.pixels == nil || capture.countdown != nil || capture.saving || capture.hasPendingImage)
|
||
Menu {
|
||
CoCoCaptureOptions(preferences: preferences)
|
||
if capture.countdown != nil { Button("Cancel Capture", action: capture.cancelCountdown) }
|
||
Divider(); Button("Capture Settings…") { capture.settingsShown = true }
|
||
} label: { Image(systemName: "chevron.down").frame(width: 14, height: 28) }
|
||
.menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().help("Screenshot and video options")
|
||
.accessibilityLabel("Screenshot and video options").accessibilityIdentifier("capture-options")
|
||
Button {
|
||
if capture.recording { Task { await capture.stopRecording() } } else { capture.startRecording() }
|
||
} label: {
|
||
Image(systemName: capture.recording ? "stop.circle.fill" : "video")
|
||
.foregroundStyle(capture.recording ? Color.red : Color.primary)
|
||
.symbolEffect(.pulse, options: .repeating, isActive: capture.recording && !reduceMotion)
|
||
.frame(width: 28, height: 28)
|
||
}.help(capture.recording ? "Stop Recording" : (preferences.includeVideoAudio ? "Record CoCo Video with CoCo audio, even when local playback is muted" : "Record CoCo Video without audio"))
|
||
.accessibilityLabel(capture.recording ? "Stop Recording" : "Record CoCo Video")
|
||
.accessibilityIdentifier("capture-record")
|
||
.disabled((!capture.recording && machine.pixels == nil) || capture.state == .starting || capture.state == .finishing)
|
||
if let seconds = capture.countdown {
|
||
Button("\(seconds)s · Cancel", action: capture.cancelCountdown).font(.caption).help("Cancel Capture")
|
||
.accessibilityIdentifier("capture-countdown-cancel")
|
||
} else if capture.active {
|
||
Text(capture.state == .finishing ? "Finishing…" : String(format: "%02d:%02d", Int(capture.elapsed)/60, Int(capture.elapsed)%60))
|
||
.font(.caption.monospacedDigit()).frame(minWidth: 42)
|
||
}
|
||
if capture.error != nil || !capture.recoveries.isEmpty && !capture.active {
|
||
Button { capture.settingsShown = true } label: { Image(systemName: "exclamationmark.circle").foregroundStyle(.orange) }
|
||
.help(capture.error ?? "Retained recording available — open Capture Settings")
|
||
.accessibilityLabel("Capture status and recovery")
|
||
} else if let saved = capture.saved {
|
||
Button { NSWorkspace.shared.activateFileViewerSelecting([saved]) } label: { Image(systemName: "checkmark.circle") }
|
||
.help("Saved \(saved.lastPathComponent) — Show in Finder").accessibilityLabel("Show saved capture in Finder")
|
||
}
|
||
}.buttonStyle(.borderless)
|
||
.sheet(isPresented: $capture.settingsShown) { CoCoCaptureSettings(capture: capture, preferences: capture.preferences) }
|
||
}
|
||
}
|
||
|
||
/// One shared options view keeps the header menu and settings sheet consistent.
|
||
struct CoCoCaptureOptions: View {
|
||
@ObservedObject var preferences: CoCoCapturePreferences
|
||
var body: some View {
|
||
Section("Save Screenshots and Videos To") {
|
||
Toggle("Desktop", isOn: Binding(get: { preferences.destination == .desktop }, set: { _ in preferences.setDestination(.desktop) }))
|
||
.accessibilityIdentifier("capture-destination-desktop")
|
||
Toggle("Documents", isOn: Binding(get: { preferences.destination == .documents }, set: { _ in preferences.setDestination(.documents) }))
|
||
.accessibilityIdentifier("capture-destination-documents")
|
||
Button(action: preferences.choose) {
|
||
if preferences.destination == .other { Label("Other Location…", systemImage: "checkmark") }
|
||
else { Text("Other Location…") }
|
||
}.accessibilityIdentifier("capture-destination-other")
|
||
if preferences.destination == .other { Text(preferences.folder.lastPathComponent).font(.caption) }
|
||
}
|
||
Picker("Screenshot Timer", selection: Binding(get: { preferences.timerSeconds }, set: preferences.setTimerSeconds)) {
|
||
Text("None").tag(0)
|
||
Text("5 Seconds").tag(5)
|
||
Text("10 Seconds").tag(10)
|
||
}.pickerStyle(.inline).accessibilityIdentifier("capture-timer")
|
||
Toggle("Include CoCo Audio in Video", isOn: $preferences.includeVideoAudio)
|
||
.accessibilityIdentifier("capture-video-audio")
|
||
}
|
||
}
|
||
|
||
struct CoCoCaptureSettings: View {
|
||
@ObservedObject var capture: CoCoCaptureCoordinator
|
||
@ObservedObject var preferences: CoCoCapturePreferences
|
||
@Environment(\.dismiss) private var dismiss
|
||
var body: some View {
|
||
VStack(alignment: .leading, spacing: 16) {
|
||
Text("CoCo Capture").font(.title2.bold())
|
||
Text("Captures include only the CoCo picture. System artwork, Mac windows and the desktop are excluded. Include CoCo Audio in Video controls the movie’s sound, even when local playback is muted. Shutter and recording-start cues are never recorded.")
|
||
VStack(alignment: .leading, spacing: 8) {
|
||
Text("Save Screenshots and Videos To").font(.headline)
|
||
Picker("Save to", selection: Binding(get: { preferences.destination }, set: preferences.setDestination)) {
|
||
Text("Desktop").tag(CoCoCapturePreferences.Destination.desktop)
|
||
Text("Documents").tag(CoCoCapturePreferences.Destination.documents)
|
||
Text("Other Location…").tag(CoCoCapturePreferences.Destination.other)
|
||
}.accessibilityIdentifier("capture-settings-destination")
|
||
Text(preferences.folder.path).font(.caption).textSelection(.enabled).lineLimit(2)
|
||
if preferences.preparingDestination {
|
||
Label("Preparing capture folder…", systemImage: "hourglass").font(.caption)
|
||
.accessibilityIdentifier("capture-settings-preparing-folder")
|
||
}
|
||
HStack { Button("Other Location…", action: preferences.choose); Button("Show in Finder") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: preferences.folder.path) } }
|
||
Picker("Screenshot Timer", selection: Binding(get: { preferences.timerSeconds }, set: preferences.setTimerSeconds)) {
|
||
Text("None").tag(0); Text("5 Seconds").tag(5); Text("10 Seconds").tag(10)
|
||
}.accessibilityIdentifier("capture-settings-timer")
|
||
Toggle("Include CoCo Audio in Video", isOn: $preferences.includeVideoAudio)
|
||
.accessibilityIdentifier("capture-settings-video-audio")
|
||
Text("The camera button uses the selected timer. Video recording starts immediately. Audio choices apply to the next recording.")
|
||
.font(.caption).fixedSize(horizontal: false, vertical: true)
|
||
}
|
||
if !capture.recoveries.isEmpty {
|
||
Divider(); Text("Retained Recordings").font(.headline)
|
||
ForEach(capture.recoveries) { record in
|
||
HStack { Text(record.created.formatted()); Button("Recover MP4") { capture.recover(record) }.disabled(capture.active)
|
||
Button("Show Files") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: record.directory.path) } }
|
||
}
|
||
Text("Interrupted movies may contain only completed fragments. Working files remain until a verified MP4 is saved.").font(.caption)
|
||
}
|
||
if let error = capture.error { Text(error).foregroundStyle(.red).textSelection(.enabled) }
|
||
if capture.hasPendingImage {
|
||
HStack { Button("Save Captured Image As…", action: capture.saveImageAs); Button("Discard Captured Image", action: capture.discardImage) }.disabled(capture.saving)
|
||
}
|
||
HStack { Spacer(); Button("Done") { dismiss() }.keyboardShortcut(.defaultAction) }
|
||
}.padding(24).frame(width: 520)
|
||
}
|
||
}
|