Cotton code
238 lines · 15.2 KB · SwiftRaw
import CottonKitimport SwiftUIimport XCTest@testable import CottonUI/// Home's fan's page pictures and its live page, as functions (lane fan,/// stage 2; architect's ruling 2–3, 14 Oct 2026).final class PagePictureTests: XCTestCase {    private let fan = FanGeometry(scale: Theme.paper.scale)    /// RULE: exactly one live page is mounted at any time, and none while the fan moves — under a finger, in the spring or in a turn it shows the nearest tile's picture (architect's ruling 2, 14 Oct 2026: a live page per passing tile is what the prototype's "live" option cost; mounting one in the spring's last frames cost a 50–260 ms frame inside the turn).    func testAtMostOneLivePageAndNoneWhileTheFanMoves() {        let count = 30        var theta = -fan.step        while theta <= fan.end(count: count) + fan.step {            for moving in [false, true] {                let mounted = FanPageRule.mounted(FanPageRule.shows(theta: theta, moving: moving, count: count, geometry: fan))                XCTAssertLessThanOrEqual(mounted.count, 1)                if moving { XCTAssertEqual(mounted, [], "no live page while the fan moves") }            }            theta += fan.step / 7        }    }    func testTheLivePageIsTheTileTheFanRestsOn() {        XCTAssertEqual(FanPageRule.shows(theta: fan.step * 3, moving: false, count: 10, geometry: fan), .live(3))        XCTAssertEqual(FanPageRule.shows(theta: fan.step * 3.6, moving: true, count: 10, geometry: fan), .picture(4))    }    /// GUARD: a launch paints the tile the fan rests on, never the card that took its slot as the database's cards are dealt in.    /// RULE: while the fan rests, its page is the tile it rests on by key; when the tiles change under it (the bundle's set dealt into the database's own at a launch) the old index names whichever card took the slot, and its ghost floated over a blank page (walker292: Home → Notes → Journal on the first launch after a copy and the offline launch) — no cover stands at a launch, only a cap tap makes one (architect, 293 row 1).    func testALaunchPaintsTheTileTheFanRestsOnAsTheCardsAreDealt() {        let bundle = ["documents", "home", "journal"]        let dealt = ["documents", "notes", "home", "journal"]        // The fan rested on Home at index 1 of the bundle's set; the deal put Notes there.        XCTAssertEqual(FanPageRule.resting(.live(1), keys: dealt, on: "home"), .live(2), "Home's page, wherever Home now stands")        XCTAssertEqual(FanPageRule.resting(.live(1), keys: bundle, on: "home"), .live(1), "nothing dealt: the index is the tile")        XCTAssertEqual(FanPageRule.resting(.picture(1), keys: dealt, on: "home"), .picture(1), "a turn's pictures follow the fan")        XCTAssertEqual(FanPageRule.resting(.live(1), keys: dealt, on: nil), .live(1))        XCTAssertEqual(FanPageRule.resting(.live(1), keys: dealt, on: "gone"), .live(1), "a key no longer held leaves the index")    }    /// RULE: the painter never draws while a finger is down, while the fan moves, or before the window has been still for the quiet time — a picture is drawn only when nobody is waiting on the main thread (architect, 14 Oct 2026, `StillWindow`).    func testThePainterNeverDrawsWhileTouchingOrTurning() {        let quiet = 0.3        XCTAssertFalse(PagePainterGate.mayDraw(touching: true, moving: false, stillFor: 10, quiet: quiet))        XCTAssertFalse(PagePainterGate.mayDraw(touching: false, moving: true, stillFor: 10, quiet: quiet))        XCTAssertFalse(PagePainterGate.mayDraw(touching: false, moving: false, stillFor: quiet / 2, quiet: quiet))        XCTAssertTrue(PagePainterGate.mayDraw(touching: false, moving: false, stillFor: quiet, quiet: quiet))    }    func testTheNearestMissingOrStaleTileIsDrawnNextAndNeverTheSettledOne() {        let keys = ["home", "a", "b", "c", "d"]        var ledger = PagePictureLedger()        XCTAssertEqual(ledger.next(of: keys, settled: 2), "c", "right of the settled tile first")        ledger.kept("c", bytes: 10, families: nil)        XCTAssertEqual(ledger.next(of: keys, settled: 2), "a")        for key in keys { ledger.kept(key, bytes: 10, families: nil) }        XCTAssertNil(ledger.next(of: keys, settled: 2), "every picture drawn and fresh")        ledger.invalidate([.todos])        XCTAssertEqual(ledger.next(of: keys, settled: 2), "c", "unknown families go stale on any change")        XCTAssertNil(ledger.next(of: ["home"], settled: 0), "the settled tile is live, never drawn")    }    /// A change goes stale only on the pages that draw it, when they are known.    func testInvalidationFollowsTheFamilies() {        var ledger = PagePictureLedger()        ledger.kept("todos", bytes: 10, families: [.todos])        ledger.kept("people", bytes: 10, families: [.people])        ledger.kept("home", bytes: 10, families: nil)        ledger.invalidate([.todos])        XCTAssertTrue(ledger.needsDrawing("todos"))        XCTAssertFalse(ledger.needsDrawing("people"))        XCTAssertTrue(ledger.needsDrawing("home"))        ledger.invalidate([])        XCTAssertFalse(ledger.needsDrawing("people"), "a change of nothing stales nothing")    }    /// RULE (walk, 26 Oct 2026): a page pictured under other table definitions is drawn again — Money and Music were pictured before their tables were defined, and every turn past them flashed "This app cannot show these records" though their live pages drew.    func testAPicturedPageIsDrawnAgainUnderOtherDefinitions() {        var ledger = PagePictureLedger()        ledger.kept("money", bytes: 10, families: [.todos], definitions: 1, current: 1)        ledger.kept("music", bytes: 10, families: [.people], definitions: 1, current: 1)        ledger.invalidate(definitions: 1)        XCTAssertFalse(ledger.needsDrawing("money"), "the same definitions stale nothing")        ledger.invalidate(definitions: 2)        XCTAssertTrue(ledger.needsDrawing("money"))        XCTAssertTrue(ledger.needsDrawing("music"))        ledger.kept("money", bytes: 10, families: [.todos], definitions: 1, current: 2)        XCTAssertTrue(ledger.needsDrawing("money"), "a picture finished under the definitions before is kept stale")        ledger.kept("money", bytes: 10, families: [.todos], definitions: 2, current: 2)        XCTAssertFalse(ledger.needsDrawing("money"))    }    func testToolSelectionKeepsPicturesUnderUnchangedDefinitions() {        let keys = ["home", "todos", "music", "messages", "calendar", "notebook", "photos"]        var ledger = PagePictureLedger()        for key in keys { ledger.kept(key, bytes: 10, families: nil, definitions: 1, current: 1) }        var previous = FanPageStand(key: "home")        for key in keys.dropFirst() + ["home"] {            let selected = FanPageStand(key: key)            if let stale = FanPageStand.changedPage(from: previous, to: selected) { ledger.invalidate(key: stale) }            ledger.invalidate(definitions: 1)            XCTAssertNil(ledger.next(of: keys, settled: keys.firstIndex(of: key)!))            XCTAssertTrue(keys.allSatisfy { !ledger.needsDrawing($0) })            previous = selected        }        XCTAssertEqual(FanPageStand.changedPage(from: previous, to: FanPageStand(key: "home", path: "/synthetic")), "home")    }    /// The definitions' stamp: none before they are read, the same for the same definitions, another for others.    func testTheDefinitionsStampFollowsWhatWasRead() {        let bundled = TableDefinitions([], read: false)        XCTAssertNil(bundled.stamp)        let all = FixtureDefinitions.load().definitions        XCTAssertNotNil(TableDefinitions(all).stamp)        XCTAssertEqual(TableDefinitions(all).stamp, TableDefinitions(all).stamp)        XCTAssertNotEqual(TableDefinitions(all).stamp, TableDefinitions(Array(all.dropFirst())).stamp, "a table defined since")    }    func testOnlyTheSettledTilesNeighboursAreDecoded() {        XCTAssertEqual(PagePictureLedger.decoded(around: 0, count: 30, reach: 4), 0...4)        XCTAssertEqual(PagePictureLedger.decoded(around: 15, count: 30, reach: 4), 11...19)        XCTAssertEqual(PagePictureLedger.decoded(around: 29, count: 30, reach: 4), 25...29)        XCTAssertNil(PagePictureLedger.decoded(around: 0, count: 0, reach: 4))    }    func testTilesLeavingHomeTakeTheirPicturesAndTheBytesFollow() {        var ledger = PagePictureLedger()        ledger.kept("a", bytes: 100, families: nil)        ledger.kept("b", bytes: 50, families: nil)        XCTAssertEqual(ledger.bytes, 150)        ledger.keepOnly(["b"])        XCTAssertEqual(ledger.bytes, 50)    }    func testATileWithNoPageOfItsOwnIsNeverPainted() {        let ledger = PagePictureLedger()        XCTAssertEqual(ledger.next(of: ["home", "home", "a"], settled: 0, skipping: ["home"]), "a")        XCTAssertNil(ledger.next(of: ["home", "home"], settled: 0, skipping: ["home"]))    }    /// The tile the fan heads for is decoded first, then outward, right first.    func testTheHeadingTileIsDecodedFirst() {        XCTAssertEqual(PagePictureLedger.decodeOrder(around: 10, count: 30, reach: 2), [10, 11, 9, 12, 8])        XCTAssertEqual(PagePictureLedger.decodeOrder(around: 0, count: 30, reach: 2), [0, 1, 2])        XCTAssertEqual(PagePictureLedger.decodeOrder(around: 0, count: 0, reach: 2), [])    }    func testThePictureDiffCountsPixelsBeyondTheTolerance() {        let a: [UInt8] = [10, 10, 10, 255, 200, 200, 200, 255]        XCTAssertEqual(PictureDiff.fraction(a, a, tolerance: 0), 0)        XCTAssertEqual(PictureDiff.fraction(a, [12, 10, 10, 255, 0, 200, 200, 255], tolerance: 4), 0.5)        XCTAssertEqual(PictureDiff.fraction(a, [10, 10, 10, 255], tolerance: 4), 1, "a size mismatch is all different")    }    func testAPagePictureComparisonChecksItsObjectsOverTheWindowGround() {        let picture: [UInt8] = [0, 0, 0, 0, 100, 80, 60, 255, 50, 40, 30, 128]        let window: [UInt8] = [30, 60, 40, 255, 100, 80, 60, 255, 65, 70, 50, 255]        XCTAssertEqual(PictureDiff.fraction(window, picture, tolerance: 0, opaqueReference: true), 0)        var moved = window        moved[4] = 20        XCTAssertEqual(PictureDiff.fraction(moved, picture, tolerance: 0, opaqueReference: true), 1,                       "A missing or moved opaque object remains a mismatch")        XCTAssertEqual(PictureDiff.fraction(window, [0, 0, 0, 0], tolerance: 0, opaqueReference: true), 1)    }    /// A picture drawn at another page size is stale: it would not line up.    func testAPictureDrawnAtAnotherSizeIsDrawnAgain() {        var ledger = PagePictureLedger()        ledger.kept("a", bytes: 10, families: nil, size: CGSize(width: 402, height: 526))        ledger.kept("b", bytes: 10, families: nil, size: CGSize(width: 402, height: 600))        ledger.resized(to: CGSize(width: 402, height: 526))        XCTAssertFalse(ledger.needsDrawing("a"))        XCTAssertTrue(ledger.needsDrawing("b"))    }    /// RULE: the touch-down snapshot of the live page never outlives the touch: it stands while the fan moves and until its tile's live page is drawn again, and goes the moment the fan is at rest on that drawn page — a tap on the settled tile, which turns nothing, never leaves the page before it drawn over the live one (zoomframe, 15 Oct).    func testTheTouchDownSnapshotGoesWhenTheTouchTurnsNothing() {        XCTAssertFalse(FanSnapshotRule.holds(grabbed: "notes", moving: false, live: true, drawn: "notes"), "a tap on the settled tile")        XCTAssertTrue(FanSnapshotRule.holds(grabbed: "notes", moving: true, live: true, drawn: "notes"), "under the finger")        XCTAssertTrue(FanSnapshotRule.holds(grabbed: "notes", moving: false, live: false, drawn: nil), "its picture still stands")        XCTAssertTrue(FanSnapshotRule.holds(grabbed: "notes", moving: false, live: true, drawn: nil), "the live page not drawn yet")        XCTAssertFalse(FanSnapshotRule.holds(grabbed: nil, moving: true, live: true, drawn: "notes"))    }    /// RULE: only the pages a turn reaches next are painted ahead — never    /// every tile's page at launch, each of which reads its list and held the    /// shared read pool for seconds on the owner's copy (readpool, 16 Oct 2026).    func testPaintsOnlyWithinReachOfTheSettledTile() {        var ledger = PagePictureLedger()        let keys = (0..<10).map { "t\($0)" }        var painted: [String] = []        while let key = ledger.next(of: keys, settled: 0, reach: 2) {            painted.append(key)            ledger.kept(key, bytes: 1, families: nil)        }        XCTAssertEqual(Set(painted), ["t1", "t2"])    }    #if os(iOS)    /// RULE (build 330): a page is painted under the table definitions its picture is kept under, and the tools the fan holds — never the fan's whole environment as it stood, which still held its first frame's definitions (none): the Tools deck was painted "Nothing here" under them, kept as the picture of the 109 definitions read since, and every turn to Tools showed it.    @MainActor    func testAPageIsPaintedUnderTheDefinitionsItsPictureIsKeptUnder() throws {        // A tool as the object serves it (the owner's copy's shape: views        // with a visibility, a photo picture naming its object, a stock).        let tool = try ToolDefinition.decode(Data(#"""            {"views":[{"id":"all","label":"All","visibility":"owner","is_default":false,"read":{"table":"todo"},"lead":"title"},                      {"id":"today","label":"Today","visibility":"owner","is_default":true,"read":{"table":"todo","section":"today"}}],             "id":"todos","name":"Todos","purpose":"What to do.","picture":{"photo":"photo:todos","object":"tool-todos"},             "card_stock":"sage","tables":["todo","todo_recurrence"],"instructions":"Keep the list.","automations":[],             "author":{"device":"object","name":"Cotton"},"signature":null}            """#.utf8))        let tables = FixtureDefinitions.load().definitions.filter { tool.tables.contains($0.id) }        XCTAssertEqual(Set(tables.map(\.id)), ["todo", "todo_recurrence"])        let definitions = TableDefinitions(tables)        XCTAssertNotNil(definitions.stamp, "the definitions the picture is kept under")        // The fan's environment as it stood: no definitions, no tools — the        // Tools deck it paints lists nothing.        let stood = EnvironmentValues()        XCTAssertEqual(BoardLayout.items(definitions: stood.tableDefinitions, dataTools: stood.toolDefinitions, keys: [tool.id]), [])        let painted = PagePainter.environment(stood, definitions: definitions, tools: ToolDefinitions([tool]))        XCTAssertEqual(painted.tableDefinitions.stamp, definitions.stamp, "painted under the definitions it is kept under")        XCTAssertEqual(            BoardLayout.items(definitions: painted.tableDefinitions, dataTools: painted.toolDefinitions, keys: [tool.id]).map(\.id),            ["data-todos"], "the Tools deck painted lists the tool")        // The painter is handed that environment, not the fan's own.        let fan = SourceSweep.withoutComments(            try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Surfaces/Board/FanSurface.swift", ownedBy: "rough"))            .filter { !$0.isWhitespace }        XCTAssertTrue(fan.contains("letpainted=PagePainter.environment(environment,definitions:definitions,tools:dataTools)"))        XCTAssertTrue(fan.contains("PagePainter.draw(page,environment:painted,"))    }    #endif}