Cotton code
138 lines · 5.7 KB · SwiftRaw
// THE INK KEPT ON THE PHONE (owner, 3 Nov 2026): every group of strokes// the ink reads is one line in a file in the app's Application Support —// never synced, never in a record — the last `keep_groups` of them, the// oldest dropped. The line is the core's (`cotton_core::ink::captured`, the// shape every lane shares); the phone only appends it. The sync card's Share// ink hands the file to the share sheet (`InkCapture.share`), so the owner// can put it in Cotton's Documents or AirDrop it, and the coordinator replays// it (`pnpm ink:corpus`). Always on wherever ink is read (`InkGate`).import Foundationactor InkCapture {    static let shared = InkCapture()    /// The file's name, as the share sheet offers it.    static let fileName = "cotton-ink.jsonl"    /// Where the file lives: Application Support/Ink, kept out of backups.    nonisolated static var url: URL {        get throws {            let support = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask,                                                      appropriateFor: nil, create: true)            return support.appendingPathComponent("Ink", isDirectory: true).appendingPathComponent(fileName)        }    }    /// How many lines the file keeps (the core's `keep_groups`).    private var keep: Int    /// The lines the file holds, counted once on the first write.    private var count: Int?    init(keep: Int = .max) {        self.keep = keep    }    /// The core's `line` for a group appended, the file keeping its last    /// `last`; past that and a tenth, the oldest dropped down to it. A write    /// that fails is said in the log, never silently lost.    func keep(_ line: String, last: Int) {        keep = last        do {            try append(Data(line.utf8), to: Self.url)        } catch {            print("ink capture: not kept — \(error)")        }    }    func append(_ line: Data, to url: URL) throws {        let folder = url.deletingLastPathComponent()        if !FileManager.default.fileExists(atPath: folder.path) {            try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)            var values = URLResourceValues()            values.isExcludedFromBackup = true            var excluded = folder            try excluded.setResourceValues(values)        }        if count == nil {            count = FileManager.default.fileExists(atPath: url.path) ? try Self.lines(in: url) : 0        }        if let handle = try? FileHandle(forWritingTo: url) {            defer { try? handle.close() }            try handle.seekToEnd()            try handle.write(contentsOf: line)        } else {            try line.write(to: url, options: .atomic)        }        count = (count ?? 0) + (line.isEmpty ? 0 : 1)        if let held = count, held > keep + max(1, keep / 10) {            try Self.keepLast(keep, of: held, in: url)            count = keep        }    }    /// The file is read and cut in pieces of this many bytes, never whole:    /// at the core's five thousand groups and a tenth it runs to megabytes.    static let piece = 64 * 1024    /// How many lines the file holds: its newlines, counted a piece at a time.    static func lines(in url: URL) throws -> Int {        let handle = try FileHandle(forReadingFrom: url)        defer { try? handle.close() }        var lines = 0        while let data = try handle.read(upToCount: piece), !data.isEmpty {            lines += data.reduce(0) { $1 == 0x0A ? $0 + 1 : $0 }        }        return lines    }    /// The file cut back to its last `keep` of `held` lines: read up to the    /// newline that ends the first line dropped, the rest copied a piece at a    /// time into a file beside it, which then takes its place.    static func keepLast(_ keep: Int, of held: Int, in url: URL) throws {        let reading = try FileHandle(forReadingFrom: url)        defer { try? reading.close() }        var dropping = held - keep        var start: UInt64 = 0        while dropping > 0, let data = try reading.read(upToCount: piece), !data.isEmpty {            for (at, byte) in data.enumerated() where byte == 0x0A {                dropping -= 1                if dropping == 0 { start += UInt64(at + 1); break }            }            if dropping > 0 { start += UInt64(data.count) }        }        try reading.seek(toOffset: start)        let kept = url.deletingLastPathComponent().appendingPathComponent(".\(url.lastPathComponent).kept")        FileManager.default.createFile(atPath: kept.path, contents: nil)        let writing = try FileHandle(forWritingTo: kept)        do {            while let data = try reading.read(upToCount: piece), !data.isEmpty { try writing.write(contentsOf: data) }            try writing.close()        } catch {            try? writing.close()            try? FileManager.default.removeItem(at: kept)            throw error        }        _ = try FileManager.default.replaceItemAt(url, withItemAt: kept)    }    /// The sync card's Share ink: the file on the share sheet. A file that    /// cannot be made is said in the log and the act reports it not done.    @MainActor static func share() async -> Bool {        do {            ShareSheet.present(try await shared.file())            return true        } catch {            print("ink capture: nothing to share — \(error)")            return false        }    }    /// The file to share: as it stands, created empty when nothing was    /// written yet, so the share always hands over what the phone holds.    func file() throws -> URL {        let url = try Self.url        if !FileManager.default.fileExists(atPath: url.path) { try append(Data(), to: url) }        return url    }}