Cotton code
194 lines · 12.9 KB · SwiftRaw
// The tray: the album's 12-inch, the song's 7-inch and the player, one// acrylic tray tilted away. Its arm (at rest off the record, on the outer// groove at nought, at the run-out at the end, the album's place over the// whole album), its words (the label's, the strip's, the times), its tilt,// its paintings and its specimens. With `COTTON_FACE_SHOTS=<dir>` set, the// tray in each state is written there beside the face shots.@testable import CottonFacesimport CottonPaperimport CottonSpecimensimport CottonValuesimport SwiftUIimport XCTest#if canImport(UIKit)    import UIKit#else    import AppKit#endif@MainActorfinal class AlbumTrayTests: XCTestCase {    private typealias Knobs = AlbumTrayFaceKnobs    private func radius(_ degrees: Double) -> Double {        let at = TrayDeck.needle(degrees)        return hypot(Double(at.x - Knobs.centre.x), Double(at.y - Knobs.centre.y))    }    /// RULE: The arm turns round the pivot it is painted on (layout.json's `arm.pivot`, 1080, 180), its needle as painted on the 12-inch's outer groove (465.6): at nought it is where it is painted.    func testTheArmIsWhereItIsPainted() {        XCTAssertEqual(Double(Knobs.pivot.x), 1080, accuracy: 0.5)        XCTAssertEqual(Double(Knobs.pivot.y), 180, accuracy: 0.5)        XCTAssertEqual(TrayDeck.painted, 465.6, accuracy: 0.5)        XCTAssertEqual(TrayDeck.arm(0, on: .album), 0, accuracy: 1e-9)    }    /// RULE: Playing, the needle's distance from the centre runs straight from the record's outer groove at nought to its run-out at the end, the rigid arm turned to meet it: the 12-inch's sweep is the layout's 22.8 degrees and the album at 2:14 of 4:02 sits at its 12.4; the 7-inch's arm meets its outer groove (270) at 17.9 and its run-out (140) at 32.5.    func testTheArmSweepsTheGrooves() {        XCTAssertEqual(radius(TrayDeck.arm(1, on: .album)), Knobs.twelveInner, accuracy: 1e-6)        XCTAssertEqual(TrayDeck.arm(1, on: .album), 22.81, accuracy: 0.05)        XCTAssertEqual(TrayDeck.arm(134.0 / 242, on: .album), 12.38, accuracy: 0.05)        XCTAssertEqual(radius(TrayDeck.arm(0.5, on: .album)), (TrayDeck.painted + Knobs.twelveInner) / 2, accuracy: 1e-6, "straight in its groove")        XCTAssertEqual(radius(TrayDeck.arm(0, on: .song)), Knobs.sevenOuter, accuracy: 1e-6)        XCTAssertEqual(radius(TrayDeck.arm(1, on: .song)), Knobs.sevenInner, accuracy: 1e-6)        XCTAssertEqual(TrayDeck.arm(0, on: .song), 17.93, accuracy: 0.05)        XCTAssertEqual(TrayDeck.arm(1, on: .song), 32.54, accuracy: 0.05)        XCTAssertEqual(TrayDeck.share(atArm: TrayDeck.arm(0.3, on: .song), on: .song), 0.3, accuracy: 1e-6)        XCTAssertEqual(TrayDeck.turned(60, by: 0, of: 240, on: .song), 60, accuracy: 1e-6, "a turn of nothing seeks nowhere")        XCTAssertEqual(TrayDeck.turned(60, by: -90, of: 240, on: .song), 0, accuracy: 1e-6, "held to the song")        XCTAssertEqual(TrayDeck.turned(60, by: 90, of: 240, on: .song), 240, accuracy: 1e-6)    }    /// RULE: Holding none of the card the arm rests back off the record, its needle clear of either record; paused it lifts a few degrees back from where it plays; playing it is at its share.    func testTheArmRestsOffTheRecord() {        let rest = TrayDeck.arm(.still, on: .album)        XCTAssertEqual(rest, Knobs.rest)        XCTAssertGreaterThan(radius(rest), Double(Knobs.twelve.width / 2), "clear of the 12-inch")        XCTAssertEqual(TrayDeck.arm(.still, on: .song), Knobs.rest)        let playing = TrackPlay(held: true, playing: true, elapsed: 60, duration: 240)        var paused = playing        paused.playing = false        XCTAssertEqual(TrayDeck.arm(playing, on: .song), TrayDeck.arm(0.25, on: .song), accuracy: 1e-9)        XCTAssertEqual(TrayDeck.arm(paused, on: .song), TrayDeck.arm(0.25, on: .song) - Knobs.lift, accuracy: 1e-9)    }    /// RULE: On the album the arm stands at the album's place: the songs before the one held and how far into it, over the whole album; with no lengths known, how far into the song.    func testTheAlbumsPlace() {        let songs = TrayDeck.songs(AlbumTrayFaceCatalogue.ferry)        XCTAssertEqual(songs.count, 9)        let whole = songs.reduce(0, +)        XCTAssertEqual(TrayDeck.share(TrackPlay(held: true, playing: true, elapsed: 134, duration: 242, song: 0), songs: songs), 134 / whole, accuracy: 1e-9)        XCTAssertEqual(TrayDeck.share(TrackPlay(held: true, playing: true, elapsed: 10, duration: 218, song: 1), songs: songs), (242 + 10) / whole, accuracy: 1e-9)        XCTAssertEqual(TrayDeck.share(TrackPlay(held: true, playing: true, elapsed: 60, duration: 240)), 0.25, accuracy: 1e-9)        XCTAssertEqual(TrayDeck.share(.still, songs: songs), 0)    }    /// RULE: The label types the title and the artist (a player's `artist`, else the card's `subtitle`); while it holds the card, the time played and the time left either side of the spindle, none at rest; the strip types the title and the artist, on the player the held song's album and its artist.    func testTheWordsAreTheCards() {        XCTAssertEqual(TrayDeck.label(AlbumTrayFaceCatalogue.ferry), ["Night Ferry", "The Low Tide"])        XCTAssertEqual(TrayDeck.label(SongTrayFaceCatalogue.harbour), ["Harbour Lights", "The Low Tide"])        XCTAssertEqual(TrayDeck.label(SongTrayFaceCatalogue.playing), ["Harbour Lights", "The Low Tide"])        XCTAssertEqual(TrayDeck.times(TrackPlay(held: true, playing: true, elapsed: 134, duration: 242)), ["2:14", "\u{2212}1:48"])        XCTAssertEqual(TrayDeck.times(.still), [])        XCTAssertEqual(TrayDeck.strip(AlbumTrayFaceCatalogue.ferry, player: false), ["Night Ferry", "The Low Tide"])        XCTAssertEqual(TrayDeck.strip(SongTrayFaceCatalogue.harbour, player: false), ["Harbour Lights", "The Low Tide"])        XCTAssertEqual(TrayDeck.strip(SongTrayFaceCatalogue.playing, player: true), ["Night Ferry", "The Low Tide"])        let bare = DeckCard(face: "album.tray", corner: nil, pressing: false, pace: nil, plate: nil, fields: [:])        XCTAssertEqual(TrayDeck.label(bare), [])        XCTAssertEqual(TrayDeck.strip(bare, player: true), [])    }    /// RULE: Each label lies centred on the spindle, its painted round inside its record's run-out groove; its words inside the label's text circle; the strip, the rail and the jewel where Round 21's layout lays them.    func testThePlacesAreTheLayouts() {        for kind in [TrayKind.album, .song] {            XCTAssertEqual(kind.record.midX, Knobs.centre.x, accuracy: 1e-9)            XCTAssertEqual(kind.record.midY, Knobs.centre.y, accuracy: 1e-9)            XCTAssertLessThan(Double(kind.labelSide * kind.labelRound), kind.grooves.inner, "\(kind)'s label inside its run-out")        }        XCTAssertEqual(Knobs.spindle.midX, Knobs.centre.x)        XCTAssertEqual(Knobs.spindle.midY, Knobs.centre.y)        for line in [(Knobs.title.y, Knobs.title.width), (Knobs.artist.y, Knobs.artist.width)] {            XCTAssertLessThanOrEqual(hypot(line.1 / 2, abs(line.0)), 146 + 1, "inside the text circle")        }        XCTAssertTrue(Knobs.strip.contains(Knobs.art))        XCTAssertTrue(Knobs.art.contains(Knobs.panel))        XCTAssertTrue(Knobs.strip.intersects(Knobs.ledge), "the rail over the strip's lower edge")        XCTAssertLessThan(Knobs.previous.maxY, Knobs.strip.maxY)    }    /// RULE: The tray is composed square-on and tilted away as one piece about its lower edge, by a named angle under a named perspective; seen, it stands a share of its height that the tilt and the perspective say.    func testTheTrayIsTilted() {        XCTAssertEqual(Knobs.tilt, 30)        XCTAssertEqual(Knobs.perspective, 0.4)        let r = Knobs.tilt * .pi / 180        XCTAssertEqual(Double(Knobs.tilted), cos(r) / (1 + 0.4 * sin(r)), accuracy: 1e-9)        XCTAssertLessThan(Knobs.tilted, 1)    }    /// RULE: The tray has no cap: it is drawn `fill` of its card's width, or of its height as the tilted tray stands, whichever binds, so a larger card draws a larger tray.    func testTheTrayFillsItsCard() {        XCTAssertEqual(Knobs.fill, 0.92)        let wide = Knobs.fill * min(393, 600 * Knobs.whole.width / (Knobs.whole.height * Knobs.tilted))        XCTAssertGreaterThan(wide, 300, "wider than the old 300 point cap on a phone's card")        let tall = Knobs.fill * min(393, 300 * Knobs.whole.width / (Knobs.whole.height * Knobs.tilted))        XCTAssertLessThan(tall, wide, "a short card binds by its height")    }    /// RULE: The album's tray and the song's are registered, printed on no stock, laid on the music's tolex, and every painting they draw is in the catalogue.    func testItLiesOnTheTolex() {        for id in ["album.tray", "song.tray"] {            XCTAssertNotNil(FaceRegistry.all.first { $0.id == id }, id)            XCTAssertEqual(FaceRegistry.ground(id), .tolex)            XCTAssertEqual(FaceRegistry.stock(id), .own)        }        for name in ["tray", "tray-shadow", "tray-ledge", "strip-blank", "tray-arm", "tray-arm-shadow", "record", "label-blank",                     "single-record", "single-label-blank", "spindle", "hifi-jewel-on", "hifi-jewel-off"] {            XCTAssertNotNil(CottonMedia.image(name), name)        }    }    /// RULE: The album is reviewed at rest and playing 2:14 of 4:02 with its cover, with no cover and with the longest words; the song on the Songs deck with and without a cover, and as the player playing, paused and with the longest words.    func testTheSpecimens() {        let album = Dictionary(uniqueKeysWithValues: AlbumTrayFaceCatalogue.face.specimens.map { ($0.name, $0) })        XCTAssertEqual(Set(album.keys), ["at rest", "playing", "no cover", "largest"])        XCTAssertNil(album["at rest"]?.play)        XCTAssertEqual(album["playing"]?.play, TrackPlay(held: true, playing: true, elapsed: 134, duration: 242, song: 0))        XCTAssertNotNil(album["playing"]?.picture)        XCTAssertNil(album["no cover"]?.picture)        XCTAssertTrue(album.values.allSatisfy { $0.card.face == "album.tray" })        let song = Dictionary(uniqueKeysWithValues: SongTrayFaceCatalogue.face.specimens.map { ($0.name, $0) })        XCTAssertEqual(Set(song.keys), ["song", "no cover", "player playing", "player paused", "largest"])        XCTAssertNil(song["song"]?.play)        XCTAssertEqual(song["player playing"]?.play.map(HifiDeck.state), .playing)        XCTAssertEqual(song["player paused"]?.play.map(HifiDeck.state), .paused)    }    /// RULE: The tray draws at rest, playing, paused, with no cover and with the longest words, the album's and the song's, from its card and the player's word alone, at every text size, on the tolex.    func testItDrawsInEveryState() throws {        let out = ProcessInfo.processInfo.environment["COTTON_FACE_SHOTS"].flatMap { $0.isEmpty ? nil : URL(fileURLWithPath: $0, isDirectory: true) }        if let out { try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true) }        let states: [(String, DeckCard, Bool, TrackPlay, TrayKind)] = [            ("album-rest", AlbumTrayFaceCatalogue.ferry, true, .still, .album),            ("album-playing", AlbumTrayFaceCatalogue.ferry, true, TrackPlay(held: true, playing: true, elapsed: 134, duration: 242, song: 0), .album),            ("album-largest", AlbumTrayFaceCatalogue.largest, false, .still, .album),            ("song", SongTrayFaceCatalogue.harbour, true, .still, .song),            ("player-playing", SongTrayFaceCatalogue.playing, true, TrackPlay(held: true, playing: true, elapsed: 134, duration: 242), .song),            ("player-paused", SongTrayFaceCatalogue.playing, false, TrackPlay(held: true, playing: false, elapsed: 134, duration: 242), .song),            ("player-largest", SongTrayFaceCatalogue.largest, false, TrackPlay(held: true, playing: false, elapsed: 312, duration: 669), .song),        ]        for size in [DynamicTypeSize.xSmall, .large, .accessibility5] {            for (name, card, covered, play, kind) in states {                let cover = covered ? FacePicture(key: "poster-ferry", edge: 120) : nil                let renderer = ImageRenderer(content: TrayFace(card: card, cover: cover, play: play, toggle: {}, start: { _ in }, kind: kind)                    .frame(width: 340, height: 451)                    .background(FaceGroundSurface(.tolex))                    .environment(\.facePictureDrawer, FixturePictures.drawer)                    .dynamicTypeSize(size)                    .themed(.paper))                renderer.scale = 2                let image = try XCTUnwrap(renderer.cgImage, "the tray \(name) drew nothing")                if let out { try write(image, to: out.appendingPathComponent("tray-\(name)-\(size).png")) }            }        }    }    private func write(_ image: CGImage, to url: URL) throws {        #if canImport(UIKit)            let data = UIImage(cgImage: image).pngData()        #else            let data = NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])        #endif        try XCTUnwrap(data, "\(url.lastPathComponent) was not encoded").write(to: url)    }}