Cotton code
284 lines · 15.5 KB · SwiftRaw
// The rolodex: a person's card typed on a rotary card file's front card —// the name struck above the first rule, one line or two, the number, the// email, the corner and the subtitle on the rules under it, the last-spoke// line pencilled at the foot; a line the card lacks a bare rule; every line// its part; the frame standing on the people's blue felt, stepped by its wheel.@testable import CottonFacesimport CottonPaperimport CottonValuesimport CoreTextimport SwiftUIimport XCTest#if canImport(AppKit)import AppKit#endif@MainActorfinal class RolodexTests: XCTestCase {    private typealias Catalogue = RolodexFaceCatalogue    /// A phone's front card: the deck's card 350 by 437 points, the frame 98% of its width.    private let size: CGSize = {        let frame = 350 * RolodexKnobs.fillWidth        return CGSize(width: RolodexKnobs.card.width * frame, height: RolodexKnobs.card.height * frame / RolodexKnobs.aspect)    }()    private func words(_ text: String) -> [Substring] {        text.split(whereSeparator: { $0.isWhitespace })    }    func testKnurlFollowsSignedProgressAndCompressesAtTheRim() throws {        let centre = try XCTUnwrap(RolodexKnurl.ridge(0, progress: 0))        let forward = try XCTUnwrap(RolodexKnurl.ridge(0, progress: 0.5))        let backward = try XCTUnwrap(RolodexKnurl.ridge(0, progress: -0.5))        XCTAssertEqual(centre.centre, 0.5)        XCTAssertEqual(forward.centre, (1 + sin(.pi / 8)) / 2, accuracy: 0.000001)        XCTAssertGreaterThan(forward.centre, centre.centre, "front tread follows the downward pull")        XCTAssertEqual(backward.centre, 1 - forward.centre, accuracy: 0.000001)        XCTAssertLessThan(forward.thickness, centre.thickness)        let rim = try XCTUnwrap(RolodexKnurl.ridge(15, progress: 0))        XCTAssertLessThan(rim.thickness, centre.thickness * 0.1)        XCTAssertNil(RolodexKnurl.ridge(32, progress: 0), "back of the cylinder is hidden")        let settled = try XCTUnwrap(RolodexKnurl.ridge(56, progress: 1))        XCTAssertEqual(settled.centre, centre.centre, accuracy: 0.000001)        XCTAssertEqual(settled.thickness, centre.thickness, accuracy: 0.000001)    }    func testKnobBodiesStayFixedThroughForwardReverseAndFallback() throws {        for index in 0...1 {            func pixels(_ progress: Double) throws -> Data {                let renderer = ImageRenderer(content: RolodexKnob(index: index, progress: progress)                    .staticBody.frame(width: 52, height: 120))                let image = try XCTUnwrap(renderer.cgImage)                return try XCTUnwrap(image.dataProvider?.data) as Data            }            let still = try pixels(0)            for progress in [-1.0, -0.5, 0.25, 0.75, 1, 0] {                XCTAssertEqual(try pixels(progress), still, "body and highlight must never move")            }        }    }    func testProjectedKnurlMovesAndMeetsTheNextDetent() throws {        for index in 0...1 {            func pixels(_ progress: Double) throws -> Data {                let renderer = ImageRenderer(content: RolodexKnob(index: index, progress: progress)                    .frame(width: 52, height: 120))                let image = try XCTUnwrap(renderer.cgImage)                return try XCTUnwrap(image.dataProvider?.data) as Data            }            let still = try pixels(0)            XCTAssertNotEqual(try pixels(0.1), still)            XCTAssertNotEqual(try pixels(-0.1), still)            XCTAssertEqual(try pixels(1), still, "eight whole teeth meet the next detent")            XCTAssertEqual(try pixels(-1), still)        }    }    func testRiffleNameChangesOnEveryCardWithinTheSameLetter() throws {        let renderer = ImageRenderer(content: RiffleName(card: Catalogue.friend, size: size).frame(width: size.width, height: size.height))        var previous: Data?        for title in ["Rhea", "Rina", "Rita", "Riya"] {            let card = Catalogue.person(["title": .text(title)])            renderer.content = RiffleName(card: card, size: size).frame(width: size.width, height: size.height)            let image = try XCTUnwrap(renderer.cgImage)            let bytes = try XCTUnwrap(image.dataProvider?.data) as Data            if let previous { XCTAssertNotEqual(bytes, previous, "the name must follow every card") }            previous = bytes        }    }    func testCardsStayNestedOnTheRailInBothDirections() {        XCTAssertEqual(RolodexWheel(phase: 0).arrivingAngle, -14)        XCTAssertEqual(RolodexWheel(phase: 1).arrivingAngle, 0)        XCTAssertEqual(RolodexWheel(phase: -0.000001).arrivingAngle, 90, accuracy: 0.001)        XCTAssertEqual(RolodexWheel(phase: -1).arrivingAngle, 0)        for tick in 0...1000 {            let phase = Double(tick) / 1000            let forward = RolodexWheel(phase: phase)            XCTAssertLessThan(forward.arrivingZ, forward.shownZ)            XCTAssertTrue((-14...0).contains(forward.arrivingAngle))            XCTAssertEqual(forward.shownAngle, phase * 180)            if tick > 0 {                let reverse = RolodexWheel(phase: -phase)                XCTAssertGreaterThan(reverse.arrivingZ, reverse.shownZ)                XCTAssertTrue((-14...0).contains(reverse.shownAngle))                XCTAssertTrue((0...90).contains(reverse.arrivingAngle))            }        }        for angle in stride(from: -180.0, through: 180.0, by: 0.25) {            XCTAssertEqual(RolodexWheel.showsFront(angle), angle > -90 && angle < 90)        }    }    func testSingleWordsShrinkBeforeExplicitHyphenation() {        let room = RolodexSetting.room(size).width        let fitted = RolodexSetting.nameLines("Intelliswift", width: room, height: size.height)        XCTAssertEqual(fitted.lines, ["Intelliswift"])        XCTAssertLessThan(fitted.size, RolodexFaceKnobs.nameSize)        let word = "Supercalifragilisticexpialidocious"        let split = RolodexSetting.nameLines(word, width: room, height: size.height)        XCTAssertEqual(split.size, RolodexFaceKnobs.nameSize * RolodexFaceKnobs.nameLeast, accuracy: 0.00001)        XCTAssertEqual(split.lines.count, 2)        XCTAssertTrue(split.lines[0].hasSuffix("-"))        for line in split.lines {            XCTAssertLessThanOrEqual(width(line, points: split.size * size.height), room)        }        XCTAssertTrue(word.hasPrefix(split.lines.joined().replacingOccurrences(of: "-", with: "")))    }    func testStackRetainsItsOpaquePixelsDuringTravel() throws {        func pixels(_ progress: Double) throws -> [UInt8] {            let view = RolodexFace(card: Catalogue.friend, photo: nil)                .environment(\.faceTurn, FaceTurn(progress: progress, window: [-1: Catalogue.ananya, 1: Catalogue.ananya]))                .frame(width: 350, height: 437)            let image = try XCTUnwrap(ImageRenderer(content: view).cgImage)            #if canImport(AppKit)            if let path = ProcessInfo.processInfo.environment["COTTON_ROLODEX_SHOTS"] {                let out = URL(fileURLWithPath: path, isDirectory: true)                try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)                try XCTUnwrap(NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:]))                    .write(to: out.appendingPathComponent("wheel-\(progress).png"))            }            #endif            var bytes = [UInt8](repeating: 0, count: image.width * image.height * 4)            let context = try XCTUnwrap(CGContext(data: &bytes, width: image.width, height: image.height,                bitsPerComponent: 8, bytesPerRow: image.width * 4,                space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))            context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))            return bytes        }        let still = try pixels(0)        // Full object on transparency: shifting a replacement crop used to        // expose transparent pixels at the stack's top. Every opaque frame        // pixel in that strip must survive every direction and phase.        for progress in [0.25, 0.5, 0.75, -0.25, -0.5, -0.75] {            let moving = try pixels(progress)            // The image rows follow the rendered view: the stack is in            // the top 14% of the centred 332pt frame (view y 52...99).            for y in 52..<99 {                for x in 60..<290 {                    let alpha = (y * 350 + x) * 4 + 3                    if still[alpha] == 255 {                        XCTAssertGreaterThanOrEqual(moving[alpha], 253, "stack gap at \(x),\(y), phase \(progress)")                    }                }            }        }    }    private func width(_ words: String, points: CGFloat) -> CGFloat {        let set = NSAttributedString(            string: words, attributes: [NSAttributedString.Key(kCTFontAttributeName as String): RolodexSetting.typeFont(points)])        return CGFloat(CTLineGetTypographicBounds(CTLineCreateWithAttributedString(set), nil, nil, nil))    }    /// RULE: The picture's man is typed whole, every line the card's own words as they are: the name on one line, the number, the email, the birthday in the ribbon's red, the subtitle, the last-spoke line at the foot.    func testTheFriendIsTypedWhole() {        let typed = RolodexSetting.set(Catalogue.friend, size: size)        XCTAssertEqual(typed.name, ["Rahul Mehta"])        XCTAssertEqual(typed.nameSize, RolodexFaceKnobs.nameSize)        XCTAssertEqual(typed.number, "+91 98765 43210")        XCTAssertEqual(typed.email, "rahul@example.org")        XCTAssertEqual(typed.corner, "Birthday Sunday")        XCTAssertTrue(typed.cornerRed, "a birthday is typed in red")        XCTAssertEqual(typed.subtitle, "College friend \u{00B7} Pune")        XCTAssertEqual(typed.foot, "Last spoke 2 days ago on WhatsApp")        XCTAssertEqual(typed.initials, "RM")    }    /// RULE: A card with a name and a number alone types those two and leaves every other rule bare: no placeholder word.    func testASparseCardLeavesTheRulesBare() {        let typed = RolodexSetting.set(Catalogue.sparse, size: size)        XCTAssertEqual(typed.number, "0484 2000 000")        XCTAssertNil(typed.email)        XCTAssertNil(typed.corner)        XCTAssertNil(typed.subtitle)        XCTAssertNil(typed.foot)        XCTAssertFalse(typed.wide)        XCTAssertEqual(typed.initials, "DC", "a blank print carries the initials")    }    /// RULE: The corner is red when it is a birthday or owed, and typed in the ink otherwise.    func testTheCornerIsRedForABirthdayOrOwed() {        XCTAssertTrue(RolodexSetting.set(Catalogue.ananya, size: size).cornerRed)        XCTAssertFalse(RolodexSetting.set(Catalogue.noPortrait, size: size).cornerRed)        XCTAssertTrue(RolodexSetting.set(Catalogue.longName, size: size).cornerRed, "not reached, and pressing")    }    /// RULE: A name takes one line when it fits the room beside the print, else two at its size; one that wants a third is taken down, never under the least, and still stops at a whole word with no ellipsis.    func testANameTakesOneLineOrTwo() {        let room = RolodexSetting.room(size).width        let clinic = RolodexSetting.set(Catalogue.sparse, size: size)        XCTAssertEqual(clinic.name, ["Dr Nair's", "clinic"])        XCTAssertEqual(clinic.nameSize, RolodexFaceKnobs.nameSize, "two lines at the name's own size")        let long = RolodexSetting.set(Catalogue.longName, size: size)        XCTAssertEqual(long.name.flatMap { words($0) }, words("Venkata Lakshmi Narasimhan"), "the whole name, on two lines")        XCTAssertEqual(long.name.count, 2)        XCTAssertLessThan(long.nameSize, RolodexFaceKnobs.nameSize)        XCTAssertGreaterThanOrEqual(long.nameSize, RolodexFaceKnobs.nameSize * RolodexFaceKnobs.nameLeast - 0.0001)        for line in long.name {            XCTAssertLessThanOrEqual(width(line, points: long.nameSize * size.height), room + 0.5, "\"\(line)\" runs past the room")        }        let longer = "Venkata Lakshmi Narasimhan Subramaniam Iyer of the Old Fort Road"        let stopped = RolodexSetting.nameLines(longer, width: room, height: size.height)        XCTAssertEqual(stopped.lines.count, 2)        let written = stopped.lines.flatMap { words($0) }        XCTAssertLessThan(written.count, words(longer).count)        XCTAssertEqual(Array(words(longer).prefix(written.count)), written, "the name stops at a whole word")        XCTAssertFalse(stopped.lines.contains { $0.contains("\u{2026}") })    }    /// RULE: The facts beside the print keep the column; when a fact under the print is too long for the column, every fact under the print is typed from the print's left edge, together, and the number beside the print stays in the column.    func testLongFactsUnderThePrintStartAtItsLeft() {        XCTAssertFalse(RolodexSetting.underPrint(0, size: size), "the number stands beside the print")        for place in 1...3 {            XCTAssertTrue(RolodexSetting.underPrint(place, size: size), "fact \(place) stands under the print")        }        let column = RolodexSetting.room(size)        let long = RolodexSetting.set(Catalogue.longName, size: size)        XCTAssertTrue(long.wide)        XCTAssertEqual(RolodexSetting.factRoom(0, wide: true, size: size).lead, column.lead)        for place in 1...3 {            let room = RolodexSetting.factRoom(place, wide: true, size: size)            XCTAssertLessThan(room.lead, column.lead)            XCTAssertGreaterThan(room.width, column.width)        }        XCTAssertEqual(RolodexSetting.factRoom(2, wide: false, size: size).lead, column.lead)    }    /// RULE: Every line drawn is its part: the print the picture, the name the title, the number the call, the email the email, the corner the when, the subtitle the subtitle; the informational foot has no action, and a line the card lacks tags nothing.    func testEveryLineIsItsPart() {        func parts(_ card: DeckCard) -> Set<FacePart> {            final class Tagged { var parts: Set<FacePart> = [] }            let tagged = Tagged()            let drawn = RolodexFace(card: card, photo: nil)                .frame(width: 350, height: 437)                .backgroundPreferenceValue(FacePartsKey.self) { regions in                    let _ = tagged.parts.formUnion(regions.map(\.part))                    Color.clear                }            XCTAssertNotNil(ImageRenderer(content: drawn).cgImage)            return tagged.parts        }        XCTAssertEqual(parts(Catalogue.friend), [.picture, .title, .call, .email, .when, .subtitle])        XCTAssertEqual(parts(Catalogue.sparse), [.picture, .title, .call])        XCTAssertFalse(Catalogue.face.tagsNoPart)    }    /// RULE: The rolodex stands bare on the people's amethyst desk, laid with its painted tile, by its own id beside the person's face, and is stepped by its wheel.    func testTheRolodexStandsOnTheAmethystDeskAndTurns() {        XCTAssertEqual(FaceRegistry.ground("person.rolodex"), .amethystDesk)        XCTAssertEqual(FaceRegistry.stock("person.rolodex"), .own)        XCTAssertTrue(FaceGround.amethystDesk.dark)        XCTAssertEqual(FaceGround.amethystDesk.tile, "people-amethyst")        XCTAssertEqual(Catalogue.face.steps, .turns)        XCTAssertEqual(Catalogue.face.specimens.map(\.name), ["opened", "friend", "ananya", "no-portrait", "sparse", "long-name"])        for name in ["rolodex-frame", "rolodex-shadow", "rolodex-card", "rolodex-ring", "rolodex-print", "people-amethyst", "rolodex-knob-left", "rolodex-knob-right", "rolodex-knurl"] {            XCTAssertNotNil(CottonMedia.image(name, scale: 3), "\(name) is not in the catalogue")        }    }}