Cotton code
290 lines · 21.1 KB · SwiftRaw
// A tool's fan tile as data (Cotton Cinemas, Round 19, 6 Nov 2026; Round 25,// 8 Nov 2026): the core answers the tile — the stock, the type, each tile's// pictogram — and the shell only draws it: a tile with a stock is painted,// whatever its type — the black felt letterboard with live cream capitals,// or a courier stock with typed words in ink. A tool naming no tile, or a// tile naming no stock, draws today's cards, unchanged.#if os(iOS)import CottonPaperimport SwiftUIimport XCTest@testable import CottonUI@MainActorfinal class PaintedTileTests: XCTestCase {    private let stock = "photo:" + String(repeating: "a", count: 64)    private let mark = "photo:" + String(repeating: "b", count: 64)    private let list = "photo:" + String(repeating: "c", count: 64)    /// RULE: `shell.fan` says a tool's tile and each view's pictogram; a list's is the tile's `list` role, said by the core; a tool naming none reads as none.    func testTheCoreSaysTheTileAndEachPictogram() throws {        let json = #"""        {"key": "cinemas", "name": "Cinemas", "kind": "tool", "tool": "cinemas", "ringed": true, "poster": false, "counted": true,         "tile": {"stock": "\#(stock)", "type": "letterboard", "pictures": {"list": "\#(list)"}},         "views": [           {"id": "films", "label": "Films", "count": 2, "default": true, "pictogram": "\#(mark)", "read": {"table": "film"}},           {"id": "group:synthetic", "label": "Synthetic nights", "count": 1, "group": "synthetic", "pictogram": "\#(list)", "read": {"table": "film"}}         ]}        """#        let tile = try JSONDecoder().decode(FanAnswer.Tile.self, from: Data(json.utf8))        let look = try XCTUnwrap(tile.tile)        XCTAssertTrue(look.letterboard)        XCTAssertEqual(look.stock, stock)        XCTAssertEqual(look.role("list"), list)        let tier = ViewTier.make(tool: "cinemas", views: tile.views, current: nil, tile: look)        XCTAssertEqual(tier.tile, look)        XCTAssertEqual(tier.cards.map(\.pictogram), [mark, list])        let plain = #"{"key": "books", "name": "Books", "kind": "tool", "tool": "books", "ringed": true, "poster": false, "counted": true, "views": [{"id": "reading", "label": "Reading", "read": {"table": "book"}}]}"#        let books = try JSONDecoder().decode(FanAnswer.Tile.self, from: Data(plain.utf8))        XCTAssertNil(books.tile)        let before = ViewTier.make(tool: "books", views: books.views, current: nil)        XCTAssertEqual(ViewTier.make(tool: "books", views: books.views, current: nil, tile: books.tile), before, "a tool naming no tile deals today's tier")        XCTAssertNil(before.cards[0].pictogram)    }    /// RULE (the owner on Cotton Cinemas 1.0 (4), 7 Nov 2026): a series' seasons and a season's episodes stand on the tool's letterboard: the core's tile names the tables its tool owns, and a whole's part finds its tile by its table; a table no tile names stays the shell's cream.    func testAWholesPartsStandOnTheTileOfTheToolOwningTheirTable() throws {        let json = #"{"stock": "\#(stock)", "type": "letterboard", "pictures": {}, "tables": ["film", "film_episode", "film_season", "watch"]}"#        let look = try JSONDecoder().decode(FanTileLook.self, from: Data(json.utf8))        XCTAssertEqual(FanTileLook.owning("film_season", in: [look]), look)        XCTAssertEqual(FanTileLook.owning("film_episode", in: [look]), look)        XCTAssertNil(FanTileLook.owning("book", in: [look]))        let older = try JSONDecoder().decode(FanTileLook.self, from: Data(#"{"stock": null, "type": "letterboard", "pictures": {}}"#.utf8))        XCTAssertNil(FanTileLook.owning("film_season", in: [older]), "a tile naming no tables owns none")    }    /// RULE: a held card's acts and Plus's doors carry the tile and each one's pictogram; an answer with neither decodes as it did.    func testActsAndDoorsCarryTheirPictograms() throws {        let acts = #"{"actions": [{"id": "play", "label": "Play", "kind": "command", "pictogram": "\#(mark)"}], "tile": {"stock": "\#(stock)", "type": "letterboard", "pictures": {}}}"#        let answer = try JSONDecoder().decode(CardActions.self, from: Data(acts.utf8))        XCTAssertEqual(answer.tile?.stock, stock)        XCTAssertEqual(answer.actions.map(\.pictogram), [mark])        let plain = try JSONDecoder().decode(CardActions.self, from: Data(#"{"actions": [{"id": "play", "label": "Play", "kind": "command"}]}"#.utf8))        XCTAssertNil(plain.tile)        XCTAssertEqual(plain.actions.map(\.pictogram), [nil])    }    /// RULE (the 6 Nov rule, both types): the name stands in the type's case — the letterboard's capitals, courier's own — broken only between words, at most two lines, at every text size up to the largest; the count beneath is never under two thirds of the name; both stand inside the stock's words foot.    func testTheWordsAreWholeAtEveryTextSize() {        let geometry = FanGeometry(scale: Theme.paper.scale)        let names = ["Films", "On this phone", "Keep everything on this phone", "Remove download", "Synthetic Extraordinarily Long Weekend Marathon", "A to Z",                     "Cancelled", "With a person", "Subscriptions"]        for type in [PaintedTileType.letterboard, .courier] {            for growth: CGFloat in [1, 1.4, 2, 3.1] {                for name in names {                    let set = PaintedTileWords.set(name, figure: "12", type: type, width: geometry.tileWidth, height: geometry.tileHeight, growth: growth)                    XCTAssertLessThanOrEqual(set.lines.count, PaintedTileWords.lines, "\(name) at \(growth)")                    let words = type.cased(name).split(separator: " ").map(String.init)                    XCTAssertEqual(set.lines.flatMap { $0.split(separator: " ").map(String.init) }, words, "\(name) at \(growth): never broken inside a word, never cut")                    let room = CGFloat(geometry.tileWidth * type.wordsWidth)                    for line in set.lines {                        XCTAssertTrue(InkFit.fits(line, face: type.face, size: set.name, width: room, lines: 1), "\(type.face) \(name) at \(growth): '\(line)' stands inside the stock at \(set.name)")                    }                    XCTAssertGreaterThanOrEqual(set.count, set.name * PaintedTileKnobs.countLeast - 0.001, "\(name)'s count")                    XCTAssertLessThanOrEqual(set.countBaseline, CGFloat(geometry.tileHeight) * type.wordsFoot + 0.5, "\(type.face) \(name) at \(growth): the count stands inside the stock")                }            }        }    }    /// RULE: a name too wide for one line at the largest text size breaks between its words onto two, as the stock sets it.    func testALongNameBreaksAtAWord() {        let geometry = FanGeometry(scale: Theme.paper.scale)        let set = PaintedTileWords.set("Synthetic nights", figure: "4", width: geometry.tileWidth, height: geometry.tileHeight, growth: 3.1)        XCTAssertEqual(set.lines, ["SYNTHETIC", "NIGHTS"])        XCTAssertEqual(set.baselines.count, 2)        XCTAssertGreaterThan(set.countBaseline, set.baselines[1])        let courier = PaintedTileWords.set("With a person", figure: "6", type: .courier, width: geometry.tileWidth, height: geometry.tileHeight, growth: 3.1)        XCTAssertLessThanOrEqual(courier.lines.count, PaintedTileWords.lines)        XCTAssertEqual(courier.lines.joined(separator: " "), "With a person", "courier keeps its case, whole: \(courier.lines)")        let long = PaintedTileWords.set("Keep everything on this phone", figure: "6", type: .courier, width: geometry.tileWidth, height: geometry.tileHeight, growth: 3.1)        XCTAssertEqual(long.lines.count, 2, "a courier name too long for one line breaks at a word: \(long.lines)")    }    /// RULE (Round 25, 8 Nov 2026): what decides a painted tile is its stock, not its type — a courier tile with a stock is painted (Downloads, Money, Podcasts), a tile naming no stock stays the plain card whatever its type; the type sets only the words.    func testATileWithAStockIsPaintedWhateverItsType() throws {        XCTAssertTrue(FanTileLook(stock: stock, type: "courier").painted)        XCTAssertTrue(FanTileLook(stock: stock, type: "letterboard").painted)        XCTAssertFalse(FanTileLook(stock: nil, type: "courier").painted)        XCTAssertFalse(FanTileLook(stock: nil, type: "letterboard").painted)        XCTAssertEqual(FanTileLook(stock: stock, type: "courier").paintedType, .courier)        XCTAssertEqual(FanTileLook(stock: stock, type: "letterboard").paintedType, .letterboard)        let geometry = FanGeometry(scale: Theme.paper.scale)        let card = FanTier.Card(id: "all", label: "All", style: .leaf, count: 32, pictogram: mark)        func png(_ tile: FanTileLook?) throws -> Data {            let image = try drawn(FanTierCard(look: .init(card: card, raised: false, width: geometry.tileWidth, height: geometry.tileHeight, tile: tile))                .environment(\.theme, Theme.paper))            return try XCTUnwrap(UIImage(cgImage: image).pngData())        }        let plain = try png(nil)        XCTAssertEqual(try png(FanTileLook(stock: nil, type: "courier")), plain, "a courier tile naming no stock is today's card")        XCTAssertEqual(try png(FanTileLook(stock: nil, type: "letterboard")), plain, "a tile naming no stock is today's card whatever its type")        XCTAssertNotEqual(try png(FanTileLook(stock: stock, type: "courier")), plain, "a courier tile with a stock is painted")    }    /// RULE: a courier stock is the whole face, its words typed in the theme's ink in its label, its pictogram in the box as painted; a red act's pictogram and words turn the kit's red, the stock stays as painted.    func testACourierStockIsDrawnInkOnItsLabel() throws {        let geometry = FanGeometry(scale: Theme.paper.scale)        let (width, height) = (geometry.tileWidth, geometry.tileHeight)        let kraft = Image(uiImage: UIGraphicsImageRenderer(size: CGSize(width: 474, height: 696)).image { context in            UIColor(red: 0.78, green: 0.56, blue: 0.3, alpha: 1).setFill()            context.fill(CGRect(x: 0, y: 0, width: 474, height: 696))        })        let navy = Image(uiImage: UIGraphicsImageRenderer(size: CGSize(width: 300, height: 300)).image { context in            UIColor(red: 0.09, green: 0.14, blue: 0.24, alpha: 1).setFill()            context.fill(CGRect(x: 0, y: 0, width: 300, height: 300))        })        let red = Theme.paper.print(.red)        func tile(_ label: String, ink: Color? = nil) -> some View {            PaintedTile(stock: kraft, type: .courier, label: label, figure: "3", ink: ink, width: width, height: height) {                PaintedPictogram(navy, red: ink, type: .courier)            }            .environment(\.theme, Theme.paper)        }        let plain = try drawn(tile("Active"))        let stockPixel = try XCTUnwrap(pixel(plain, at: (0.1, 0.95)))        XCTAssertEqual(Int(stockPixel[0]), 199, accuracy: 4, "the stock is the face: \(stockPixel)")        let markPixel = try XCTUnwrap(pixel(plain, at: (0.5, PaintedTileKnobs.markCentre)))        XCTAssertLessThan(Int(markPixel[0]), 40, "the pictogram as painted: \(markPixel)")        let reddened = try drawn(tile("Cancel", ink: red))        let redMark = try XCTUnwrap(pixel(reddened, at: (0.5, PaintedTileKnobs.markCentre)))        XCTAssertGreaterThan(Int(redMark[0]), Int(redMark[1]) + 60, "a red act's pictogram is red: \(redMark)")        XCTAssertEqual(try XCTUnwrap(pixel(reddened, at: (0.1, 0.95))), stockPixel, "the stock stays as painted under a red act")        // The words stand low, in the label: none above the pictogram's box foot.        let set = PaintedTileWords.set("Active", figure: "3", type: .courier, width: width, height: height)        XCTAssertGreaterThan(set.baselines[0] - set.name * PaintedTileType.courier.capRatio,                             CGFloat(height * PaintedTileKnobs.markCentre + width * PaintedTileKnobs.markSide / 2))    }    /// RULE: the letterboard draws the stock as the whole face with live cream words; a red act's words turn red on the black board, never a red tile; the centred tile stands brighter than its neighbours.    func testTheBoardIsDrawnRedInkStaysInkAndTheCentreIsLifted() throws {        let geometry = FanGeometry(scale: Theme.paper.scale)        let (width, height) = (geometry.tileWidth, geometry.tileHeight)        let board = Image(uiImage: UIGraphicsImageRenderer(size: CGSize(width: 474, height: 696)).image { context in            UIColor(red: 0.2, green: 0.19, blue: 0.18, alpha: 1).setFill()            context.fill(CGRect(x: 0, y: 0, width: 474, height: 696))        })        func tile(_ label: String, ink: Color = PaintedTileKnobs.cream, centred: Bool = false) -> some View {            PaintedTile(stock: board, label: label, figure: "3", ink: ink, centred: centred, width: width, height: height) {                Rectangle().fill(ink)            }        }        let side = try drawn(tile("Films"))        let centre = try drawn(tile("Films", centred: true))        let red = try drawn(tile("Remove", ink: Theme.paper.print(.red)))        // The felt at the board's foot corner is the stock as given.        let felt = try XCTUnwrap(pixel(side, at: (0.1, 0.95)))        XCTAssertEqual(Int(felt[0]), 51, accuracy: 4, "the stock is the face: \(felt)")        // The pictogram's box holds the ink.        let markInk = try XCTUnwrap(pixel(side, at: (0.5, PaintedTileKnobs.markCentre)))        XCTAssertGreaterThan(Int(markInk[0]), 200, "cream in the box: \(markInk)")        let redInk = try XCTUnwrap(pixel(red, at: (0.5, PaintedTileKnobs.markCentre)))        XCTAssertGreaterThan(Int(redInk[0]), Int(redInk[1]) + 60, "a red act's mark is red: \(redInk)")        let redFelt = try XCTUnwrap(pixel(red, at: (0.1, 0.95)))        XCTAssertEqual(redFelt, felt, "the board stays black under a red act")        // The centred board is about 12% brighter.        let lifted = try XCTUnwrap(pixel(centre, at: (0.1, 0.95)))        XCTAssertEqual(Double(lifted[0]) / Double(felt[0]), 1 + PaintedTileKnobs.lift, accuracy: 0.06, "\(lifted) against \(felt)")    }    /// RULE: a tier naming no tile, or a tile naming no stock, draws today's cream card; a letterboard whose stock is not in hand yet is black felt, a courier one cream.    func testATierWithoutATileDrawsTodaysCard() throws {        let geometry = FanGeometry(scale: Theme.paper.scale)        let card = FanTier.Card(id: "play", label: "Play", style: .leaf, pictogram: mark)        func drawn(_ tile: FanTileLook?) throws -> CGImage {            try self.drawn(FanTierCard(look: .init(card: card, raised: false, width: geometry.tileWidth, height: geometry.tileHeight, tile: tile))                .environment(\.theme, Theme.paper))        }        let cream = try XCTUnwrap(pixel(try drawn(nil), at: (0.5, 0.25)))        let felt = try XCTUnwrap(pixel(try drawn(FanTileLook(stock: stock, type: "letterboard")), at: (0.5, 0.9)))        let courier = try XCTUnwrap(pixel(try drawn(FanTileLook(stock: nil, type: "courier")), at: (0.5, 0.25)))        let unstocked = try XCTUnwrap(pixel(try drawn(FanTileLook(stock: nil, type: "letterboard")), at: (0.5, 0.25)))        let courierBlank = try XCTUnwrap(pixel(try drawn(FanTileLook(stock: stock, type: "courier")), at: (0.5, 0.9)))        XCTAssertGreaterThan(Int(cream[0]), 180, "today's card is cream: \(cream)")        XCTAssertLessThan(Int(felt[0]), 60, "the letterboard is black felt: \(felt)")        XCTAssertEqual(courier, cream, "a courier tile naming no stock is today's card")        XCTAssertEqual(unstocked, cream, "a letterboard naming no stock is today's card")        XCTAssertGreaterThan(Int(courierBlank[0]), 180, "a courier stock not in hand yet is cream: \(courierBlank)")    }    /// RULE (8 Nov 2026, Music's pale legend field and Keys' brass tag): a tile's words are data — the core's `words` give their ink, name and count alike, and their baselines on the 696-high stock; a letterboard naming none keeps its cream at its own baselines.    func testALetterboardsWordsTakeTheirInkAndBaselinesFromTheTile() throws {        let json = ##"{"stock": "\##(stock)", "type": "letterboard", "pictures": {}, "words": {"ink": "#211a12", "name_baseline": 500, "count_baseline_one": 586, "count_baseline_two": 644}}"##        let look = try JSONDecoder().decode(FanTileLook.self, from: Data(json.utf8))        XCTAssertEqual(look.words, FanTileLook.Words(ink: "#211a12", nameBaseline: 500, countBaselineOne: 586, countBaselineTwo: 644))        let worded = look.paintedType        XCTAssertTrue(worded.letterboard, "the words keep the letterboard's face")        XCTAssertEqual(worded.ink, ThemeColor(hex: "#211a12"))        XCTAssertNil(FanTileLook(stock: stock, type: "letterboard").paintedType.ink, "a tile naming no words keeps the type's own ink")        // At the painted size each baseline stands where the painter set it.        let painted = Double(PaintedTileKnobs.stockHeight * worded.nameCap / worded.capRatio)        let name = Double(worded.nameBaseline * PaintedTileKnobs.stockHeight)        XCTAssertEqual(name, 500, accuracy: 0.01)        XCTAssertEqual(name + painted * Double(worded.countGap), 586, accuracy: 0.01)        XCTAssertEqual(name + painted * Double(worded.countGap + worded.lineStep), 644, accuracy: 0.01)        XCTAssertGreaterThanOrEqual(worded.wordsFoot, 644.0 / 696.0, "a two-line name's count stands where it is set")        let only = PaintedTileType.courier.worded(ink: nil, nameBaseline: 430, countOne: nil, countTwo: nil)        XCTAssertEqual(Double(only.nameBaseline * PaintedTileKnobs.stockHeight), 430, accuracy: 0.01)        XCTAssertEqual(only.countGap, PaintedTileType.courier.countGap, accuracy: 0.0001, "a gap not given is the type's")        XCTAssertNil(only.ink)        // Drawn on a grey stock: the worded tile's name and count are dark at        // 500 and 586, the plain letterboard's cream at its own 403 and 502.        let geometry = FanGeometry(scale: Theme.paper.scale)        let (width, height) = (geometry.tileWidth, geometry.tileHeight)        let grey = Image(uiImage: UIGraphicsImageRenderer(size: CGSize(width: 474, height: 696)).image { context in            UIColor(white: 0.5, alpha: 1).setFill()            context.fill(CGRect(x: 0, y: 0, width: 474, height: 696))        })        func tile(_ type: PaintedTileType) throws -> CGImage {            try drawn(PaintedTile(stock: grey, type: type, label: "All", figure: "32", width: width, height: height) { EmptyView() }                .environment(\.theme, Theme.paper))        }        // A row a little above a baseline (painter's pixels), through the capitals.        func inks(_ image: CGImage, at baseline: Double) throws -> (dark: Bool, cream: Bool) {            let shares = try XCTUnwrap(row(image, at: (baseline - 12) / 696))            return (shares.contains { $0 < 70 }, shares.contains { $0 > 200 })        }        let dark = try tile(worded)        XCTAssertEqual(try inks(dark, at: 500).dark, true, "the name is dark at 500")        XCTAssertEqual(try inks(dark, at: 500).cream, false, "and never cream")        XCTAssertEqual(try inks(dark, at: 586).dark, true, "the count is the name's ink at 586")        XCTAssertEqual(try inks(dark, at: 403).dark, false, "nothing at the letterboard's own baseline")        let cream = try tile(.letterboard)        XCTAssertEqual(try inks(cream, at: 403).cream, true, "the plain letterboard's name is cream at 403")        XCTAssertEqual(try inks(cream, at: 502).cream, true, "its count cream at 502")        XCTAssertEqual(try inks(cream, at: 586).cream, false, "nothing at the worded count's baseline")        XCTAssertEqual(try inks(cream, at: 403).dark, false)    }    /// The red channel of every pixel along a row given as a share of the image's height.    private func row(_ image: CGImage, at y: Double) -> [UInt8]? {        var bytes = [UInt8](repeating: 0, count: 4 * image.width)        guard let context = CGContext(data: &bytes, width: image.width, height: 1, bitsPerComponent: 8, bytesPerRow: 4 * image.width,                                      space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }        let row = Double(image.height) * (1 - y)        context.draw(image, in: CGRect(x: 0, y: -row, width: Double(image.width), height: Double(image.height)))        return stride(from: 0, to: bytes.count, by: 4).map { bytes[$0] }    }    private func drawn(_ view: some View) throws -> CGImage {        let renderer = ImageRenderer(content: view)        renderer.scale = 3        return try XCTUnwrap(renderer.cgImage)    }    /// The RGBA bytes at a point given as shares of the image's size.    private func pixel(_ image: CGImage, at point: (x: Double, y: Double)) -> [UInt8]? {        let space = CGColorSpaceCreateDeviceRGB()        var bytes = [UInt8](repeating: 0, count: 4)        guard let context = CGContext(data: &bytes, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: space,                                      bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }        let x = Double(image.width) * point.x, y = Double(image.height) * (1 - point.y)        context.draw(image, in: CGRect(x: -x, y: -y, width: Double(image.width), height: Double(image.height)))        return bytes    }}#endif