// SPDX-License-Identifier: GPL-3.0-or-later import Combine import Foundation /// Browsing/reading choices are personal state, not part of either shipped catalog. struct LibraryBrowseState: Codable, Equatable, Sendable { var scope = "" var query = "" var filters: [String: String] = [:] var selectedID: String? var selectedEditionID: String? var topVisibleID: String? var offset: Double = 0 var pageOffset = 0 } struct LibraryReadingPosition: Codable, Equatable, Sendable { var documentID: String var relativePath: String? = nil var page = 1 var anchor: String? = nil var offset: Double = 0 var horizontalOffset: Double = 0 var zoom: Double? = nil var autoScales: Bool? = nil var readingOrder: Int? = nil } struct ManualBookmark: Codable, Equatable, Identifiable, Sendable { let id: UUID let bookID: String var bookTitle: String var sectionTitle: String var position: LibraryReadingPosition var label: String? let createdAt: Date var updatedAt: Date var locationChanged: Bool? = nil var displayName: String { label.flatMap { $0.isEmpty ? nil : $0 } ?? sectionTitle } var locationKey: String { bookID + "/" + (position.relativePath ?? "") + "#" + (position.anchor ?? "offset-\(Int(position.offset * 10_000))") } } @MainActor final class LibraryContinuityStore: ObservableObject { private(set) static var shared: LibraryContinuityStore = { #if VCC_UI_TESTING return LibraryContinuityStore(directory: FileManager.default.temporaryDirectory.appendingPathComponent("VCCContinuityUITest-" + UUID().uuidString)) #else if CommandLine.arguments.contains("--interface-validation") || CommandLine.arguments.contains("--validate-startup") { return LibraryContinuityStore(directory: FileManager.default.temporaryDirectory.appendingPathComponent("VCCContinuityValidation-" + UUID().uuidString)) } return LibraryContinuityStore(directory: AppIdentity.supportDirectory) #endif }() /// Called by the app delegate after selecting its normal or isolated support root. static func configureShared(directory: URL) { guard shared.fileURL.deletingLastPathComponent() != directory else { return } shared = LibraryContinuityStore(directory: directory) } private struct Document: Codable, Sendable { var version = 1 var browse: [String: LibraryBrowseState] = [:] var reading: [String: LibraryReadingPosition] = [:] var bookmarks: [ManualBookmark] = [] } @Published private(set) var bookmarks: [ManualBookmark] = [] @Published private(set) var saveError: String? private var document = Document() private var maySave = true private var revision = 0 private var pendingSave: Task? private let queue = DispatchQueue(label: "com.brianholman.vccplus.library-continuity", qos: .utility) let fileURL: URL init(directory: URL) { fileURL = directory.appendingPathComponent("LibraryContinuity.json") guard FileManager.default.fileExists(atPath: fileURL.path) else { return } do { let handle = try FileHandle(forReadingFrom: fileURL) defer { try? handle.close() } let bytes = try handle.read(upToCount: 8 * 1024 * 1024 + 1) ?? Data() guard bytes.count <= 8 * 1024 * 1024 else { throw Failure.invalid } let decoded = try JSONDecoder().decode(Document.self, from: bytes) guard decoded.version == 1, decoded.browse.count <= 256, decoded.reading.count <= 20_000, decoded.bookmarks.count <= 5_000, decoded.browse.allSatisfy({ Self.validID($0.key) && Self.valid($0.value) }), decoded.reading.allSatisfy({ Self.validID($0.key) && Self.valid($0.value) }), decoded.bookmarks.allSatisfy({ Self.valid($0.position) && Self.validID($0.bookID) }), Set(decoded.bookmarks.map(\.id)).count == decoded.bookmarks.count else { throw Failure.invalid } document = decoded bookmarks = decoded.bookmarks } catch { maySave = false saveError = "Saved library positions and bookmarks could not be read. The original file has been preserved at \(fileURL.path). \(error.localizedDescription)" } } func browse(for key: String) -> LibraryBrowseState? { document.browse[key] } func reading(for key: String) -> LibraryReadingPosition? { document.reading[key] } func setBrowse(_ value: LibraryBrowseState, for key: String) { guard maySave, Self.validID(key), Self.valid(value), document.browse[key] != value else { return } document.browse[key] = value; scheduleSave() } func setReading(_ value: LibraryReadingPosition, for key: String) { guard maySave, Self.validID(key), Self.valid(value), document.reading[key] != value else { return } document.reading[key] = value; scheduleSave() } @discardableResult func addBookmark(bookID: String, bookTitle: String, sectionTitle: String, position: LibraryReadingPosition) -> ManualBookmark? { guard maySave, Self.validID(bookID), Self.valid(position), bookmarks.count < 5_000 else { return nil } let candidate = ManualBookmark(id: UUID(), bookID: bookID, bookTitle: String(bookTitle.prefix(512)), sectionTitle: String(sectionTitle.prefix(1024)), position: position, createdAt: Date(), updatedAt: Date()) if let existing = bookmarks.first(where: { $0.locationKey == candidate.locationKey }) { return existing } bookmarks.append(candidate); document.bookmarks = bookmarks; scheduleSave(); return candidate } func renameBookmark(_ id: UUID, label: String) { guard maySave, let index = bookmarks.firstIndex(where: { $0.id == id }) else { return } bookmarks[index].label = String(label.trimmingCharacters(in: .whitespacesAndNewlines).prefix(512)) bookmarks[index].updatedAt = Date(); document.bookmarks = bookmarks; scheduleSave() } func removeBookmark(_ id: UUID) { guard maySave else { return } bookmarks.removeAll { $0.id == id }; document.bookmarks = bookmarks; scheduleSave() } func markBookmarkLocationChanged(_ id: UUID, changed: Bool) { guard maySave, let index = bookmarks.firstIndex(where: { $0.id == id }), bookmarks[index].locationChanged != changed else { return } bookmarks[index].locationChanged = changed document.bookmarks = bookmarks; scheduleSave() } func flush() async { pendingSave?.cancel(); pendingSave = nil guard maySave else { return } await withCheckedContinuation { continuation in write { continuation.resume() } } } /// Queue the latest checkpoint without a main-thread or emulator wait. func checkpoint() { pendingSave?.cancel(); pendingSave = nil if maySave { write() } } private func scheduleSave() { revision += 1 pendingSave?.cancel() pendingSave = Task { [weak self] in do { try await Task.sleep(for: .milliseconds(300)) } catch { return } guard let self, !Task.isCancelled else { return } self.write() } } private func write(completion: (@Sendable () -> Void)? = nil) { let value = document, destination = fileURL, generation = revision queue.async { [weak self] in let message: String? do { let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] let bytes = try encoder.encode(value) guard bytes.count <= 8 * 1024 * 1024 else { throw Failure.invalid } try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) try bytes.write(to: destination, options: .atomic) message = nil } catch { message = "Library positions and bookmarks could not be saved: \(error.localizedDescription)" } Task { @MainActor [weak self] in guard let self, self.revision == generation else { return } self.saveError = message } completion?() } } private static func validID(_ value: String) -> Bool { !value.isEmpty && value.utf8.count <= 4096 && !value.contains("\0") } private static func valid(_ state: LibraryBrowseState) -> Bool { state.scope.utf8.count <= 4096 && state.query.count <= 256 && state.filters.count <= 32 && state.filters.allSatisfy { $0.key.count <= 128 && $0.value.count <= 4096 } && state.offset.isFinite && state.offset >= 0 && (0...250_000).contains(state.pageOffset) } private static func valid(_ position: LibraryReadingPosition) -> Bool { validID(position.documentID) && position.page > 0 && position.page <= 1_000_000 && position.offset.isFinite && (0...1).contains(position.offset) && position.horizontalOffset.isFinite && (0...1).contains(position.horizontalOffset) && position.zoom.map { $0.isFinite && $0 > 0 && $0 <= 100 } != false && position.relativePath.map { !$0.hasPrefix("/") && !$0.split(separator: "/").contains("..") && !$0.contains("\0") } != false && position.anchor.map { $0.count <= 2048 && !$0.contains("\0") } != false } private enum Failure: LocalizedError { case invalid var errorDescription: String? { "The continuity file is damaged or uses an unsupported version." } } } struct ArchiveLibraryOpenRequest: Equatable, Sendable { let id = UUID() let documentID: String let location: Int? let expectedSHA256: String? } /// A request is retained until the Archive window appears, so opening its window /// and requesting an exact document do not depend on notification timing. @MainActor final class ArchiveLibraryNavigation: ObservableObject { static let shared = ArchiveLibraryNavigation() @Published private(set) var request: ArchiveLibraryOpenRequest? func open(documentID: String, location: Int? = nil, expectedSHA256: String? = nil) { request = ArchiveLibraryOpenRequest(documentID: documentID, location: location, expectedSHA256: expectedSHA256) } func consumed(_ id: UUID) { if request?.id == id { request = nil } } }