Cotton code
160 lines · 7.2 KB · SwiftRaw
// Clips: a copy on one device is a paste on another, without iCloud// (owner, 14 Oct 2026). This file is the half every platform shares — what// a copy must be to become a clip, and the write. Watching a pasteboard is// the platform's: the Mac's `ClipboardWatch` (CottonHost) polls NSPasteboard's// change count, the phone reads on coming to the front.//// What never becomes a clip, in the order it is judged://   1. an item the copying app marked concealed or transient//      (nspasteboard.org) — judged on its TYPES, before its value is read;//   2. a value shaped like a secret or a card number — the core's//      `engine::clips::refusal`, one rule for every device and for MCP, so the//      create is refused and nothing is written;//   3. a text already among the clips (a clip tapped to copy it again comes//      back to the clipboard; keeping it twice would push a real one out).//// The table rides a schema rise: until the database carries the Clips// definition, the keeper writes nothing.import CottonValuesimport Foundationimport CottonKit/// One copy a device saw, before it is a clip.public struct CopiedText: Equatable, Sendable {    public var text: String    /// The pasteboard type identifiers the copied item carries.    public var types: Set<String>    /// The app it was copied in, when the platform says.    public var sourceApp: String?    /// This device's name.    public var sourceDevice: String?    public var copiedAt: Date    public init(text: String, types: Set<String>, sourceApp: String? = nil, sourceDevice: String? = nil, copiedAt: Date = Date()) {        self.text = text        self.types = types        self.sourceApp = sourceApp        self.sourceDevice = sourceDevice        self.copiedAt = copiedAt    }}public enum ClipCapture {    /// The Clips table's definition id.    public static let table = "clip"    /// Whether the copying app asked every reader not to keep this item.    public static func refuses(types: Set<String>) -> Bool {        !types.isDisjoint(with: PasteboardMark.skipped)    }    /// What the device detects the text to be — one of the crate's kinds    /// (`engine::clips::KINDS`): the whole text a link, an email address, a    /// postal address, a phone number or a date, else text.    public static func kind(of text: String) -> String {        let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)        guard !trimmed.isEmpty, trimmed.count <= ClipCaptureKnobs.detectedUpTo else { return "text" }        let whole = NSRange(trimmed.startIndex..., in: trimmed)        let types: NSTextCheckingResult.CheckingType = [.link, .address, .phoneNumber, .date]        guard let detector = try? NSDataDetector(types: types.rawValue),              let match = detector.firstMatch(in: trimmed, options: [], range: whole),              match.range == whole else { return "text" }        switch match.resultType {        case .link: return match.url?.scheme == "mailto" ? "email" : "link"        case .address: return "address"        case .phoneNumber: return "phone"        case .date: return "date"        default: return "text"        }    }    /// The create a copy is written with.    static func data(_ copied: CopiedText) -> [String: RecordValue] {        var data: [String: RecordValue] = [            "text": .text(copied.text),            "kind": .text(kind(of: copied.text)),            "copied_at": .text(CottonDate.format(copied.copiedAt)),        ]        if let app = copied.sourceApp, !app.isEmpty { data["source_app"] = .text(app) }        if let device = copied.sourceDevice, !device.isEmpty { data["source_device"] = .text(device) }        return data    }}/// Writes copies as clips into one database (the person's own).public actor ClipKeeper {    private let store: any Records    private var hasClips = false    private var lookedAt: Date?    public init(store: any Records) {        self.store = store    }    /// Keep the copy as a clip, unless it is one of the three that never    /// become a clip (the file's header) or the database has no Clips yet.    /// Answers whether a clip was written; a refusal is not an error.    @discardableResult    public func keep(_ copied: CopiedText, now: Date = Date()) async -> Bool {        guard !ClipCapture.refuses(types: copied.types),              !copied.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,              await carriesClips(now: now) else { return false }        if let held = try? await store.list(table: ClipCapture.table, project: nil, query: nil, page: 0, where: [:]),           held.records.contains(where: { $0["text"].text == copied.text }) {            return false        }        do {            _ = try await store.create(table: ClipCapture.table, data: ClipCapture.data(copied))            return true        } catch {            // The core refused it (a secret's shape, too long) or the write            // failed: either way the copy is not kept, and nothing is said —            // a clipboard is read in the background.            return false        }    }    /// Whether this device's own row lets it keep copies: its `column`    /// (`clips_on_open` on a phone, off unless turned on; `clips_watch` on a    /// Mac, on unless turned off), or `otherwise` while the row carries no    /// such column — a file before the rise that adds them.    public func deviceAllows(_ column: String, device: String?, otherwise: Bool) async -> Bool {        guard let device, let row = try? await store.get(table: "device", id: device) else { return otherwise }        switch row[column] {        case .bool(let on): return on        case .number(let value): return value != 0        default: return otherwise        }    }    /// The clips held, newest first — every device's, as synced here; none    /// while the database has no Clips.    public func newest(now: Date = Date()) async -> [(text: String, device: String?)] {        guard await carriesClips(now: now),              let page = try? await store.list(table: ClipCapture.table, project: nil, query: nil, page: 0, where: [:])        else { return [] }        return page.records            .sorted { ($0["copied_at"].text ?? "") > ($1["copied_at"].text ?? "") }            .compactMap { record in record["text"].text.map { ($0, record["source_device"].text) } }    }    /// Whether the database carries the Clips definition, asked again at most    /// once a minute while it does not (the table arrives with a rise).    private func carriesClips(now: Date) async -> Bool {        if hasClips { return true }        if let lookedAt, now.timeIntervalSince(lookedAt) < ClipCaptureKnobs.lookAgainAfter { return false }        lookedAt = now        hasClips = (try? await store.tableDefinitions().contains { $0.id == ClipCapture.table }) ?? false        return hasClips    }}/// The sizes and timings Clips works with: Swift's own, beside their reader.enum ClipCaptureKnobs {    /// Longer texts are text: a detector over a document is slow and never    /// finds one link that IS the whole of it.    static let detectedUpTo = 2_000    /// How long a database without Clips is left before it is asked again.    static let lookAgainAfter: TimeInterval = 60}