Cotton code
291 lines · 19.8 KB · SwiftRaw
import CottonKitimport CottonValuesimport Foundationimport SwiftUIimport XCTest@testable import CottonUI/// Every face and every surface CottonUI draws, measured on the phone's/// main-thread stack. Builds 227, 230 and 231 each crashed on the phone by/// overflowing its 1 MB main stack in a body nobody had measured — the/// old record page's type, the list's body, then the old page's head — while the/// simulator's and the Mac's 8 MB stacks let every walk pass. The surface/// guards (`SurfaceStackTests`, `RouteSurfaceStackTests`) measured the/// screens that had already crashed; this measures all of them, and a sweep/// over the sources fails when a new face or surface ships unmeasured.final class FaceStackTests: XCTestCase {    /// One thing to measure: a type, the input it was built from, and one    /// evaluation of its body.    struct Case {        let type: String        let table: String        let evaluate: @MainActor () -> Void        /// For a hosted case: the same render with nothing in it, subtracted,        /// so what is left is the surface's own share.        var baseline: (@MainActor () -> Void)? = nil    }    /// RULE: every face and surface in CottonUI — every `View` named `…Face` or `…Surface`, and `BoardTile` — touches at most 256 KB of main-thread stack per body evaluation in a debug build (`StackHighWater.surfaceBudget`, a quarter of the phone's 1 MB main stack), for every bundled table's fixture records where it draws a table and for synthetic input where it draws a board. The phone's main thread has 1 MB of stack and the simulator's and the Mac's 8 MB; builds 227, 230 and 231 each crashed on the phone overflowing it in a body nobody measured (231: the old record page's `editableCell` ← `pageTitle` ← `pageHead`, 1.8 MB per evaluation in debug before 5172602b1), so every face and surface is measured against a quarter of it.    @MainActor    func testEveryFaceAndSurfaceStaysWithinAQuarterOfThePhonesStack() throws {        let started = Date()        var worst: [String: (bytes: Int, table: String)] = [:]        let cases = try Self.cases()        XCTAssertGreaterThan(cases.count, 0, "the guard built \(cases.count) cases — it would pass on nothing")        for item in cases {            var used = StackHighWater.measure { item.evaluate() }            if let baseline = item.baseline {                used = max(0, used - StackHighWater.measure { baseline() })            }            if used >= (worst[item.type]?.bytes ?? -1) { worst[item.type] = (used, item.table) }        }        for (type, cost) in worst.sorted(by: { $0.key < $1.key }) {            print("FaceStackTests \(type): \(cost.bytes / 1024) KB (\(cost.table))")            XCTAssertLessThanOrEqual(                cost.bytes, StackHighWater.surfaceBudget,                "evaluating \(type)'s body (\(cost.table)) touched \(cost.bytes / 1024) KB of main-thread stack; the phone has 1 MB for all of SwiftUI (builds 227, 230, 231) — cut the body into stages built in their own frames and hand them on as AnyView")        }        print("FaceStackTests: \(cases.count) evaluations of \(worst.count) types in \(String(format: "%.1f", Date().timeIntervalSince(started))) s")    }    /// RULE: no face or surface ships unmeasured — every `struct <Name>Face` or `struct <Name>Surface` in CottonUI that conforms to a SwiftUI view (or wraps a platform view) is either measured by `testEveryFaceAndSurfaceStaysWithinAQuarterOfThePhonesStack` or named in `notMeasured` with the reason it cannot be; the phone's main thread has 1 MB of stack and the simulator's and the Mac's 8 MB, and builds 227, 230 and 231 each crashed on the phone overflowing it in a body nobody measured (231: the old record page's `editableCell` ← `pageTitle` ← `pageHead`, 1.8 MB per evaluation in debug before 5172602b1), so every face and surface is measured against a quarter of it.    @MainActor    func testEveryFaceAndSurfaceIsMeasuredOrSaysWhyNot() throws {        let pattern = #"struct\s+(\w+(?:Face|Surface))\s*(?:<[^>]*>)?\s*:[^{]*\b(?:View|UIViewRepresentable|UIViewControllerRepresentable|NSViewRepresentable|NSViewControllerRepresentable)\b"#        let regex = try NSRegularExpression(pattern: pattern)        var declared: [String: String] = [:]        let sources = try SourceSweep.swiftSources().filter { $0.name.hasPrefix("CottonUI/") }        /// RULE: The face-stack guard must read source before it can enforce the stack budget.        XCTAssertFalse(sources.isEmpty, "the sweep read no CottonUI sources")        for source in sources {            let code = SourceSweep.withoutComments(source.text)            for match in regex.matches(in: code, range: NSRange(code.startIndex..., in: code)) {                if let range = Range(match.range(at: 1), in: code) { declared[String(code[range])] = source.name }            }        }        XCTAssertGreaterThan(declared.count, 0, "the sweep found \(declared.count) faces and surfaces — the pattern has stopped matching")        let measured = Set(try Self.cases().map(\.type))        let missing = declared.keys.filter { !measured.contains($0) && Self.notMeasured[$0] == nil }.sorted()        XCTAssertTrue(            missing.isEmpty,            "unmeasured on the phone's 1 MB main stack: \(missing.map { "\($0) (\(declared[$0] ?? ""))" }.joined(separator: ", ")) — add each to FaceStackTests.cases(), or to notMeasured with the reason it cannot be built in a test")        for name in Self.notMeasured.keys.sorted() {            XCTAssertNotNil(declared[name], "notMeasured names \(name), which CottonUI no longer declares — take it out")            XCTAssertFalse(measured.contains(name), "\(name) is measured now — take it out of notMeasured")        }    }    /// The faces and surfaces that cannot be measured here, each with why.    static let notMeasured: [String: String] = [        "CameraSurface":            "a private UIViewControllerRepresentable over UIImagePickerController, compiled only where UIKit is (not in the macOS test run) and unreachable from a test; it has no SwiftUI body to evaluate — UIKit draws the camera"    ]    // MARK: - The cases    static let now = Date(timeIntervalSince1970: 1_791_590_400)    /// Every face and surface, built and ready to evaluate — cheap to build,    /// so the sweep reads the measured type names from the same list.    @MainActor    static func cases() throws -> [Case] {        var cases: [Case] = []        func add<V: View>(_ view: V, _ table: String) {            cases.append(Case(type: name(of: V.self), table: table) { _ = view.body })        }        // Faces that draw a table: every bundled definition, its fixtures.        let bundle = try TestResources.bundle()        let definitions = FixtureDefinitions.load(from: bundle).definitions        /// RULE: The face-stack guard must read definitions before it can enforce the stack budget.        XCTAssertFalse(definitions.isEmpty, "the bundled definitions are missing")        for definition in definitions {            let id = definition.id            let records = try FixtureDefinitions.fixtureRecords(for: id, bundle: bundle)            let shown = Array(records.prefix(3))            for size in TileSize.allCases {                add(BoardTile(definition: definition, records: records, size: size, now: now), "\(id) tile \(size.rawValue)")            }            add(BoardTile(definition: definition, records: records, size: .large, now: now, framed: false), "\(id) section")            add(SectionFace(definition: definition, records: records), id)            add(SlipListFace(definition: definition, records: records, now: now), id)            add(MonthFace(definition: definition, records: records, now: now), id)            add(CardFace(definition: definition, now: now), "\(id) no record")            add(SparklineFace(definition: definition), id)            add(ChartFace(definition: definition, now: now), id)            for stack in TableGroups.Stack.allCases {                add(                    GroupStackFace(definition: definition, face: stack, seed: "g-\(id)", name: "Group", count: records.count, top: shown),                    "\(id) \(stack.rawValue)")            }            add(GroupStackFace(definition: definition, face: .slips, seed: "new-\(id)", name: "New", count: nil, top: [], isNew: true), "\(id) new")            // A table whose groups are albums marks a suggested one under its pile.            if let groups = definition.groups, groups.keptIn != nil {                add(                    GroupStackFace(definition: definition, face: groups.stack, seed: "k-\(id)", name: "Album", count: records.count, top: shown, byline: "suggested"),                    "\(id) kept")            }            for record in shown {                add(SlipFace(definition: definition, record: record), id)                add(RecordCardFace(definition: definition, record: record), id)                let plain = DeckCard(record) ?? DeckCard.named(record, in: definition)                add(PlainFace(card: plain, picture: plain.text("photo").map { AnyView(PagePicture(key: $0, edge: DeckFaceKnobs.photoEdge)) }), id)                add(CoverFace(definition: definition, record: record), id)                add(CardFace(definition: definition, record: record, now: now), id)                add(CapFace(definition: definition, record: record), id)                add(PolaroidFace(definition: definition, record: record), id)            }            add(RecordListSurface(definition: definition) { _ in }, id)            add(DeckSurface(definition: definition, filter: [:], view: nil), id)        }        // The boards.        let home = HomeModel(core: ScriptedCore([:]), toasts: ToastCenter(scheduler: ManualToastScheduler()))        for board in [BoardDefinition.home, BoardDefinition.tools] {            add(                BoardSurface<EmptyView>(                    project: .constant(nil), board: board,                    home: BoardHome(model: home, databaseName: nil, project: nil, now: now),                    results: nil, onOpenTable: { _ in }),                board.id)        }        let tool = ToolDefinition(            id: "everything", name: "Everything", picture: nil, tables: definitions.map(\.id), instructions: "",            automations: [], author: ToolDefinition.Author(device: "test", name: "Test"), signature: nil)        add(ToolBoardSurface(tool: tool, onOpenTable: { _ in }), "every bundled table")        add(EmailArchiveSurface(id: nil), "folders")        add(EmailArchiveSurface(id: "thread-1"), "one thread")        // The kit's faces.        add(ChatFace(seed: "chat", name: "Priya Example", pictureKey: nil), "typed card")        add(ChatFace(seed: "chat", name: "Priya Example", pictureKey: "media/photo-1"), "picture")        add(ReceiptFace(label: "IMPORT", seed: "receipt") { Text("Forty-two records came in.") }, "label and text")        for dye in PaperDye.allCases {            for edge in PaperEdge.allCases {                add(PaperSurface(dye: dye, edge: edge, seed: "paper"), "\(dye.rawValue) \(edge.rawValue)")            }        }        add(TerminalSurface(feed: TerminalFeed(sessionId: "s-1"), onInput: { _ in }, onSize: { _, _ in }), "a session")        #if os(iOS)        // Story's Ink faces (Story/Ink, iPhone only): a person's initial, a picture by its key, a place.        add(InkFace(initial: "A"), "an initial")        add(InkFace(initial: "A", size: 30), "small")        add(InkPictureFace(initial: "A", picture: nil), "no picture")        add(InkPictureFace(initial: "A", picture: "media/photo-1"), "a picture")        let place = try JSONDecoder().decode(StoryPlace.self, from: Data(#"{"id":"place-1","name":"Harbour","scenes":2,"scene_ids":["s-1","s-2"]}"#.utf8))        add(InkPlaceFace(place: place), "a place")        #endif        // The deck's faces, on the gallery's invented cards.        let none = Optional<EmptyView>.none        let faces = GalleryFaces.self        add(DocumentFace(card: DocumentFaceCatalogue.document, page: none), "document")        add(VideoFace(card: VideoFaceCatalogue.falls, still: none), "video")        add(AudioFace(card: AudioFaceCatalogue.shelf, peaks: AudioFaceCatalogue.shelfPeaks), "audio")        add(EventFace(card: EventFaceCatalogue.dinner), "event")        add(SecretFace(card: SecretFaceCatalogue.login, picture: none), "secret")        add(EmailFace(card: EmailFaceCatalogue.contractNote, picture: none), "email")        add(MachineFace(card: MachineFaceCatalogue.studio), "machine")        add(QuotaFace(card: QuotaFaceCatalogue.usage), "quota")        add(SubscriptionFace(card: SubscriptionFaceCatalogue.streaming), "subscription")        add(ArtifactFace(card: ArtifactFaceCatalogue.planner, picture: none), "artifact")        add(BirthdayFace(card: BirthdayFaceCatalogue.birthday, photo: none), "birthday")        add(EpisodeFace(card: EpisodeFaceCatalogue.episode, still: none), "episode")        add(TrackFace(card: TrackFaceCatalogue.lantern, art: none, toggle: {}), "track")        add(MusicAlbumFace(card: MusicAlbumFaceCatalogue.monsoon, art: none), "music album")        add(PlaylistFace(card: PlaylistFaceCatalogue.sunday, covers: [.art("a"), .art("b"), .sleeve(title: "c", artist: nil), .art("d")]) { _, _ in EmptyView() }, "playlist")        add(PlaylistFace(card: PlaylistFaceCatalogue.sunday, covers: []) { _, _ in EmptyView() }, "playlist with no covers")        add(SessionFace(card: SessionFaceCatalogue.runningSession, mark: .green), "session")        add(GroupFace(card: GroupFaceCatalogue.friend, photo: none), "group")        add(SessionFace(card: SessionFaceCatalogue.failedSession, mark: .red), "failed session")        add(SessionFace(card: SessionFaceCatalogue.runningSession, mark: .red, asking: true), "waiting session")        add(SessionFace(card: SessionFaceCatalogue.runningSession, pages: faces.runningTasks), "session and its tasks")        add(MemoryFace(card: MemoryFaceCatalogue.namedMemory), "memory")        add(MemoryFace(card: MemoryFaceCatalogue.keptMemory), "kept memory")        add(MoodFace(card: MoodFaceCatalogue.eveningMood), "mood")        add(MoodFace(card: MoodFaceCatalogue.quietMood), "mood with no emotions")        add(AudioFace(card: faces.standup, peaks: [], preview: faces.standupPages.first?.text), "meeting")        add(AudioFace(card: faces.transcribing, peaks: []), "meeting being transcribed")        let dish = DeckCard(face: .plain, fields: [            "title": .text("Invented dal"), "photo": .text("k"), "amount": .text("₹180"),            "subtitle": .text("Veg · Mild"), "count": .text("23 reviews"), "body": .text("An invented dish."),        ])        add(DishFace(card: dish, picture: none, pages: [CardPage(label: "What buyers say", text: "Invented praise.")],                     rating: 4.5, mark: .green), "dish")        let studioClass = DeckCard(face: .event, fields: [            "photo": .text("k"), "title": .text("Invented flow"), "subtitle": .text("7:00 am · 60 min"),            "used": .number(7), "limit": .number(12), "people": .list([.object(["name": .text("Invented Trainer")])]),        ])        add(ClassFace(card: studioClass, photo: none), "class")        add(MembershipFace(card: MembershipFaceCatalogue.tenClasses, photo: none), "membership")        let studioPlace = DeckCard(face: .sharmilaStudio, fields: [            "photo": .text("k"), "title": .text("Invented Studio"), "subtitle": .text("An invented tagline."),            "people": .list([.object(["name": .text("Invented Founder")])]), "place": .text("Invented Road"),            "period": .text("Mon–Fri"), "body": .text("Invented words about the studio."),        ])        add(StudioPlaceFace(card: studioPlace, photo: none), "studio")        add(TrainerFace(card: TrainerFaceCatalogue.trainer, photo: none), "trainer")        add(ClientFace(card: ClientFaceCatalogue.member), "client")        // Nancy's kitchen in her look (`KitchenFaces`), on invented rows.        let kitchen = CardLabels(bySlot: ["amount": "Price", "count": "Reviews", "body": "Address", "date": "Due"],                                    byColumn: ["delivered": "Delivered", "paid": "Paid", "subscription": "Plan"])        add(DishFace(card: dish, picture: none, pages: [CardPage(label: "What buyers say", text: "Invented praise.")],                     rating: 4.5, mark: .green, kitchen: kitchen), "kitchen dish")        add(KitchenDishFront(card: dish, picture: none, rating: 4.5, mark: .green, labels: kitchen), "kitchen dish front")        add(KitchenChefFace(card: KitchenChefFaceCatalogue.chef, portrait: none, rating: 4.9, labels: kitchen), "kitchen chef")        add(KitchenPlanFace(card: KitchenPlanFaceCatalogue.plan, labels: kitchen), "kitchen plan")        add(KitchenPlaceFace(card: KitchenPlaceFaceCatalogue.kitchen, photo: none, labels: kitchen), "kitchen place")        add(KitchenCateringFace(card: KitchenCateringFaceCatalogue.party, labels: kitchen), "kitchen catering")        add(KitchenDeliveryFace(card: KitchenDeliveryFaceCatalogue.lunch, state: KitchenDeliveryState(delivered: true, paid: true, onPlan: true),                                labels: kitchen, planTag: "Plan"), "kitchen delivery")        for shape in PlainFaceCatalogue.shapes {            let picture = shape.picture.map { AnyView(GalleryFaces.picture($0)) }            add(PlainFace(card: shape.card, picture: picture, pages: shape.pages), "plain \(shape.name)")            add(PlainFace(card: shape.card, picture: picture, pages: shape.pages, page: 1), "plain \(shape.name) turned")        }        add(ToolFace(name: "Calendar", purpose: "Events and time you have planned.", figure: "3 today") { side in            ToolObject(name: "Calendar", picture: nil, printing: .contentOnly, side: side)        }, "tool")        let dinner = TodayItem(title: "Dinner", done: false, line: "8:00 pm")        add(TodayFace(today: dinner, kind: "Event", card: EventFaceCatalogue.dinner) { side in            ToolObject(name: "Event", picture: ToolObjects.picture(for: "calendar"), printing: .contentOnly, side: side)        }, "today")        // The capture surface reads the navigator in its body itself        // (`.onChange(of: navigator.waitingPicture)`), and a non-optional        // `@Environment(Navigator.self)` cannot be read off a view that is        // not installed — so it is measured hosted, with the navigator and        // the toast centre it needs, and an empty render with the same        // environment subtracted. That counts the whole subtree, not one        // body: an upper bound on the surface's own share.        let navigator = Navigator()        let toasts = ToastCenter(scheduler: ManualToastScheduler())        for start in [CaptureStart.listening, .typing] {            let model = CaptureSurfaceModel(                read: ScreenRead(core: ScriptedCore([:]), read: CaptureSurfaceModel.readName, families: [.core]),                dictionary: { DictationHints() }, now: now)            let surface = CaptureSurface(model: model, start: start, onKept: { _ in }, onDiscarded: {})            cases.append(                Case(                    type: name(of: CaptureSurface.self), table: "hosted, \(start)",                    evaluate: { render(surface.environment(navigator).environment(toasts)) },                    baseline: { render(Color.clear.environment(navigator).environment(toasts)) }))        }        return cases    }    /// The type's name without its generic arguments: `BoardSurface<EmptyView>` is `BoardSurface`.    static func name<V>(of type: V.Type) -> String {        let full = String(describing: type)        return full.firstIndex(of: "<").map { String(full[..<$0]) } ?? full    }    /// One whole render of `view` on a phone-sized canvas.    @MainActor    static func render<V: View>(_ view: V) {        let renderer = ImageRenderer(content: view.frame(width: 393, height: 852))        _ = renderer.cgImage    }}