Cotton code
127 lines · 7.8 KB · SwiftRaw
// The cassette (the list's `list.cassette`, the song's and the player's// `song.cassette`) and the specimen player it is played under in Loom: its// songs are its card's, the packs wind through the whole tape as the player// stands in it, the label's hand line names as many songs as fit and "+N",// a song's cassette says its artist and album, and the face draws playing as// it draws still. With `COTTON_FACE_SHOTS=<dir>` set, the playing and still// cassettes are written there beside the face shots.import CottonFacesimport CottonPaperimport CottonSpecimensimport CottonValuesimport SwiftUIimport XCTest#if canImport(UIKit)    import UIKit#else    import AppKit#endif@MainActorfinal class CassetteTests: XCTestCase {    private let drives = CassetteTape.songs(ListCassetteFaceCatalogue.nightDrives)    private let t0 = Date(timeIntervalSinceReferenceDate: 800_000_000)    /// RULE: A list's songs are its card's entries in their order, each its title, its length and whether it plays.    func testTheSongsAreTheCardsEntries() {        XCTAssertEqual(drives.map(\.title), ["Harbour Lights", "Slow Train", "Blue Hour"])        XCTAssertEqual(drives.map(\.seconds), [221, 302, 178])        XCTAssertEqual(CassetteTape.songs(ListCassetteFaceCatalogue.long).count, 40)        XCTAssertTrue(CassetteTape.songs(ListCassetteFaceCatalogue.blank).isEmpty)        let unplayable = DeckCard(face: .listCassette, fields: ["songs": .list([.object(["title": .text("Gone"), "duration": .number(10), "unavailable": .bool(true)])])])        XCTAssertEqual(CassetteTape.songs(unplayable).map(\.available), [false])    }    /// RULE: The label's smaller hand line names the songs "A / B / C"; with fewer named than there are, "+N" says the rest.    func testTheHandLineNamesSongsThenHowManyMore() {        let titles = ["Harbour Lights", "Slow Train", "Blue Hour"]        XCTAssertEqual(CassetteTape.named(titles, 3), "Harbour Lights / Slow Train / Blue Hour")        XCTAssertEqual(CassetteTape.named(titles, 5), "Harbour Lights / Slow Train / Blue Hour")        XCTAssertEqual(CassetteTape.named(titles, 2), "Harbour Lights / Slow Train +1")        XCTAssertEqual(CassetteTape.named(titles, 0), "+3")        XCTAssertEqual(CassetteTape.named([], 3), "")    }    /// RULE: The packs keep the tape's area: full on one reel is the full radius, none is the bare core, and halfway the radius whose disc holds half the tape.    func testThePacksKeepTheTapesArea() {        XCTAssertEqual(CassetteTape.radius(1), 280, accuracy: 1e-9)        XCTAssertEqual(CassetteTape.radius(0), 95, accuracy: 1e-9)        XCTAssertEqual(CassetteTape.radius(0.1157167530224525), 130.58656033808626, accuracy: 1e-6, "Round 22's proof")        XCTAssertEqual(CassetteTape.radius(1 - 0.1157167530224525), 265.2774967068774, accuracy: 1e-6, "Round 22's proof")        XCTAssertEqual(CassetteTape.radius(2), 280, accuracy: 1e-9, "a share past the whole is the whole")    }    /// RULE: The right reel's share is how far into the whole tape the player stands, over its length; still it is nought, and a blank tape winds nothing.    func testThePackIsThePositionInTheWholeTape() {        XCTAssertEqual(CassetteTape.wound(drives, .still), 0)        let train = TrackPlay(held: true, playing: true, elapsed: 108, duration: 302, song: 1)        XCTAssertEqual(CassetteTape.position(drives, train), 221 + 108)        XCTAssertEqual(CassetteTape.wound(drives, train), (221 + 108) / 701, accuracy: 1e-9)        XCTAssertEqual(CassetteTape.wound(drives, TrackPlay(held: true, elapsed: 178, duration: 178, song: 2)), 1, accuracy: 1e-9)        XCTAssertEqual(CassetteTape.wound([], train), 0)    }    /// RULE: The specimen player is still until played; played, it runs at the clock's pace through the songs in order and the pack follows it; paused, it stands where it is; it plays from any song and seeks within the song it holds.    func testThePlayerAdvancesPausesStartsAndSeeks() {        let player = SpecimenPlayer(lengths: drives.map(\.seconds))        XCTAssertEqual(player.play(at: t0), .still)        player.toggle(at: t0)        var shares: [Double] = []        for (seconds, song, elapsed) in [(0.0, 0, 0.0), (100, 0, 100), (250, 1, 29), (600, 2, 77)] {            let play = player.play(at: t0.addingTimeInterval(seconds))            XCTAssertEqual(play.song, song, "at \(seconds)s")            XCTAssertEqual(play.elapsed, elapsed, accuracy: 1e-6, "at \(seconds)s")            shares.append(CassetteTape.wound(drives, play))        }        XCTAssertEqual(shares, shares.sorted(), "the pack winds one way while it plays")        player.toggle(at: t0.addingTimeInterval(600))        XCTAssertFalse(player.play(at: t0.addingTimeInterval(700)).playing)        XCTAssertEqual(player.play(at: t0.addingTimeInterval(700)).elapsed, 77, accuracy: 1e-6)        player.start(1, at: t0)        player.seek(to: 200, at: t0.addingTimeInterval(10))        let play = player.play(at: t0.addingTimeInterval(15))        XCTAssertEqual(play.song, 1)        XCTAssertEqual(play.elapsed, 205, accuracy: 1e-6)    }    /// RULE: A song's cassette reads its card as a tape of one song: the player's place on it is the tape's first, its length the card's or, held, the player's.    func testASongIsATapeOfOne() {        let held = TrackPlay(held: true, playing: true, elapsed: 60, duration: 242)        let tape = CassetteTape.songs(DeckCard(face: .songCassette, fields: ["songs": .list([.object(["title": .text("Harbour Lights"), "duration": .number(242)])])]))        XCTAssertEqual(CassetteTape.wound(tape, TrackPlay(held: true, playing: true, elapsed: 60, duration: 242, song: 0)), 60.0 / 242, accuracy: 1e-9)        XCTAssertEqual(CassetteTape.wound(tape, held), 0, "a player that names no song holds none of the tape")    }    /// RULE: The cassettes draw still and playing, from the card and the player's word alone: no clock of their own.    func testTheCassettesDrawStillAndPlaying() 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 faces: [(String, Face, DeckCard, TrackPlay)] = [            ("list.cassette-still", ListCassetteFaceCatalogue.face, ListCassetteFaceCatalogue.nightDrives, .still),            ("list.cassette-playing", ListCassetteFaceCatalogue.face, ListCassetteFaceCatalogue.nightDrives, TrackPlay(held: true, playing: true, elapsed: 134, duration: 302, song: 1)),            ("list.cassette-long", ListCassetteFaceCatalogue.face, ListCassetteFaceCatalogue.long, .still),            ("song.cassette-playing", SongCassetteFaceCatalogue.face, SongCassetteFaceCatalogue.player, TrackPlay(held: true, playing: true, elapsed: 134, duration: 242)),        ]        for (name, face, card, play) in faces {            let size = CGSize(width: 360, height: 300)            let renderer = ImageRenderer(content: face.view(card, picture: nil, taps: FaceTaps())                .environment(\.faceTrackPlayer, SpecimenPlaying.standing(play))                .frame(width: size.width, height: size.height)                .background(FaceGroundSurface(.tolex))                .themed(.paper))            renderer.scale = 2            let image = try XCTUnwrap(renderer.cgImage, "the cassette \(name) drew nothing")            if let out { try write(image, to: out.appendingPathComponent("\(name).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)    }}