Cotton code
219 lines · 10.3 KB · SwiftRaw
// What Home's fan keeps of each tile's page while the page is not mounted// (lane fan, stage 2; architect's ruling 2–3, 14 Oct 2026): a PICTURE of the// first screen of the page, drawn off screen while the window is still and// kept compressed for every tile; only the settled tile's neighbours are kept// decoded. While the fan turns, the page area shows the nearest tile's// picture; the live page mounts only once the fan rests on a// tile. This file is the bookkeeping, pure so it is tested as functions// (`PagePictureTests`); the drawing and the bytes are `PagePictures.swift`.import CottonKitimport CoreGraphicsimport Foundationstruct PagePictureLedger: Equatable, Sendable {    struct Entry: Equatable, Sendable {        /// The compressed picture's size.        var bytes: Int        /// A change since it was drawn names what it shows: it is drawn again        /// at the next still window, and shown until then.        var stale: Bool        /// The screen families its page draws; nil when the page's are not        /// known, so any change of data makes it stale.        var families: Set<ScreenFamily>?        /// The page area's size it was drawn at, in points: a picture is        /// shown at the size it was drawn, never scaled to fit, so one drawn        /// at another size is stale.        var size: CGSize        /// The table definitions it was drawn under (`TableDefinitions.stamp`).        var definitions: Int? = nil    }    private(set) var entries: [String: Entry] = [:]    /// Every picture's bytes together.    var bytes: Int { entries.values.reduce(0) { $0 + $1.bytes } }    mutating func kept(_ key: String, bytes: Int, families: Set<ScreenFamily>?, size: CGSize = .zero,                       definitions: Int? = nil, current: Int? = nil) {        entries[key] = Entry(bytes: bytes, stale: definitions != current, families: families, size: size, definitions: definitions)    }    /// The table definitions read now are `stamp`: every picture drawn under    /// others is stale. A page drawn before a table it shows was defined    /// pictured the refusal (`UnknownTable`), and the fan showed that    /// picture over every turn past the tile though its live page drew —    /// Money and Music flashed "This app cannot show these records" (walk,    /// 26 Oct 2026).    mutating func invalidate(definitions stamp: Int) {        for (key, entry) in entries where entry.definitions != stamp { entries[key]?.stale = true }    }    /// The page area is `size` now: every picture drawn at another size is    /// stale — drawn again at the next still window, shown until then.    mutating func resized(to size: CGSize) {        for (key, entry) in entries where entry.size != size { entries[key]?.stale = true }    }    /// The tiles no longer on Home take their pictures with them.    mutating func keepOnly(_ keys: Set<String>) {        entries = entries.filter { keys.contains($0.key) }    }    /// A `data` event moved `families` (`InvalidationMap`): every picture    /// whose page draws one of them — or whose families are not known — is    /// stale. A stale picture is still shown; it is never blank.    mutating func invalidate(_ moved: some Sequence<ScreenFamily>) {        let moved = Set(moved)        guard !moved.isEmpty else { return }        for (key, entry) in entries where entry.families.map({ !$0.isDisjoint(with: moved) }) ?? true {            entries[key]?.stale = true        }    }    /// Tile `key`'s page turned to another screen (a record opened on it,    /// or back): its picture is of what it showed.    mutating func invalidate(key: String) { entries[key]?.stale = true }    func needsDrawing(_ key: String) -> Bool { entries[key]?.stale ?? true }    /// The next tile to draw: the one nearest the settled tile that has no    /// picture or a stale one; the settled tile itself is live, never drawn,    /// and a tile in `skipping` (one with no page of its own) never is.    func next(of keys: [String], settled: Int, skipping: Set<String> = [], reach: Int = .max) -> String? {        guard !keys.isEmpty else { return nil }        for distance in 1..<max(2, min(keys.count, reach.saturatingAdd(1))) {            for index in [settled + distance, settled - distance] where keys.indices.contains(index) {                if !skipping.contains(keys[index]), needsDrawing(keys[index]) { return keys[index] }            }        }        return nil    }    /// The order to decode in: `settled` first — at a release, the tile the    /// fan will land on — then outward, right before left.    static func decodeOrder(around settled: Int, count: Int, reach: Int) -> [Int] {        guard let range = decoded(around: settled, count: count, reach: reach) else { return [] }        let centre = min(max(settled, 0), count - 1)        return range.sorted { (abs($0 - centre), $1) < (abs($1 - centre), $0) }    }    /// The tiles whose pictures are kept decoded: the settled tile's    /// neighbours within `reach`, itself included.    static func decoded(around settled: Int, count: Int, reach: Int) -> ClosedRange<Int>? {        guard count > 0 else { return nil }        let low = max(0, min(settled, count - 1) - max(0, reach))        let high = min(count - 1, max(settled, 0) + max(0, reach))        return low...high    }}/// When the page area draws the live page, and when the nearest tile's/// picture (ruling 2). Pure, so the one-live-page rule is a test.enum FanPageRule {    /// What the page area draws now.    enum Shows: Equatable {        /// The tile's live page, mounted.        case live(Int)        /// The tile's picture; the live page is not mounted.        case picture(Int)    }    /// The live page mounts once the fan RESTS on a tile; while anything    /// moves it — a finger, the spring, a turn — the nearest tile's picture    /// shows. Not "once it is nearly stopped": mounting a page in the    /// spring's last frames cost one 50–260 ms frame inside the turn    /// (simulator, 43 tiles, 14 Oct 2026), where at rest it costs a frame    /// nobody sees move.    static func shows(theta: Double, moving: Bool, count: Int, geometry: FanGeometry) -> Shows {        let nearest = geometry.nearest(theta, count: count)        return moving ? .picture(nearest) : .live(nearest)    }    /// What the page area may draw over the tiles it holds NOW: the fan's    /// tile, or the nearest card to it when the tiles shrank under a settled    /// fan — a database switch brings the new tiles (Me alone, until its    /// arrangement is read) a frame before the motion is recounted, and a    /// removed member's phone sent back to Personal from a page past them    /// trapped in the page's `tiles[index]` (sharing2 walk, 16 Oct 2026).    /// Nil when there is no tile at all.    static func held(_ shows: Shows, count: Int) -> Shows? {        guard count > 0 else { return nil }        switch shows {        case .live(let index): return .live(min(max(index, 0), count - 1))        case .picture(let index): return .picture(min(max(index, 0), count - 1))        }    }    /// What the page area shows while the fan rests: the tile it rests ON, by    /// key. Its tiles change under it at a launch — the bundle's set dealt    /// into the database's own (291 E) — and for the frames before the fan    /// is turned to its tile's new place the old index names whichever card    /// took the slot: the page area drew that card's ghost over a blank page    /// (Me → Notes → Journal floating above the fan) and mounted each one's    /// live page in turn (292, walker292: first launch after a copy, offline    /// launch). A turn's pictures are by index, as the fan moves.    static func resting(_ shows: Shows, keys: [String], on key: String?) -> Shows {        guard case .live(let index) = shows, let key, let at = keys.firstIndex(of: key),              !keys.indices.contains(index) || keys[index] != key        else { return shows }        return .live(at)    }    /// The tile the fan rests on once its tiles change under it: the one it    /// rested on, at its new place, else Me (`opens`). A slot is not a tile —    /// tiles read after the arrangement (a tool's definitions, the shown    /// database's tables) shift Me along the arc, and a fan kept at its slot    /// lands on another card with no page drawn (walker pass 3, 16 Oct 2026:    /// a cold launch and a switch rested on Documents with a ghost card).    static func rest(on key: String?, keys: [String], opens: Int) -> Int {        key.flatMap { keys.firstIndex(of: $0) } ?? opens    }    /// The pages mounted for what the page area shows: at most one, ever.    static func mounted(_ shows: Shows) -> [Int] {        if case .live(let index) = shows { return [index] }        return []    }}/// When the painter may draw a picture off screen (ruling 2, `StillWindow`):/// the window has been still long enough, the fan rests, and no finger is/// down.enum PagePainterGate {    static func mayDraw(touching: Bool, moving: Bool, stillFor: Double, quiet: Double) -> Bool {        !touching && !moving && stillFor >= quiet    }}/// How far two pictures of one page are apart: the share of pixels where any/// channel differs by more than `tolerance`. Both are RGBA, one byte a/// channel, the same size; a size mismatch is all different.enum PictureDiff {    /// A transparent reference owns its opaque objects. Its clear pixels    /// and translucent edges take the window's ground when displayed.    static func fraction(_ a: [UInt8], _ b: [UInt8], tolerance: Int, opaqueReference: Bool = false) -> Double {        guard a.count == b.count, a.count >= 4 else { return 1 }        var differing = 0        var compared = 0        var index = 0        while index + 3 < a.count {            if !opaqueReference || b[index + 3] == 255 {                compared += 1                for channel in 0..<4 where abs(Int(a[index + channel]) - Int(b[index + channel])) > tolerance {                    differing += 1                    break                }            }            index += 4        }        return compared == 0 ? 0 : Double(differing) / Double(compared)    }}private extension Int {    func saturatingAdd(_ other: Int) -> Int {        let (sum, overflow) = addingReportingOverflow(other)        return overflow ? .max : sum    }}