SPB Git

Repository Public

ScoreTests.swift 7.4 KB 128 lines swift

1// ORIX Sonata2// File: Packages/SonataUI/Tests/SonataUITests/ScoreTests.swift3// Description: Score space: decoding of the compiler's notation model, engraving decisions,4// page layout invariants, hit testing and the PDF export.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import PDFKit10import SonataBridge11import Testing12@testable import SonataUI1314func compiledScore(_ body: String, settings: String = "tempo 120bpm\n    signature 4/4") async throws -> ScoreDocument {15    let source = "import std.instruments\n\ncomposition \"Test\" {\n    \(settings)\n    instrument piano: GrandPiano {\n\(body)\n    }\n}\n"16    let session = SonataCompilerSession()17    let result = try await session.compile(name: "main", source: source)18    #expect(result.errors.isEmpty, "\(result.errors.map(\.message))")19    return try ScoreDocument.decode(json: await session.exportJSON("score"))20}2122@Test func scoreDecodesWithEngravingDecisions() async throws {23    // D minor: B flat is in the key, B natural needs an accidental once in the measure.24    let score = try await compiledScore("""25            play Bb4 duration 1/826            play B4 duration 1/827            play B4 duration 1/828            play Bb4 duration 1/829            play C#4 duration 1/430            play C6 duration 1/431    """, settings: "tempo 96bpm\n    key D minor\n    signature 4/4")32    #expect(score.fifths == -1 && score.minor)33    #expect(score.measures.count == 1 && score.measures[0].tempos.first?.bpm == 96)34    let notes = score.parts[0].measures[0].voices[0].filter { !$0.isRest }35    #expect(notes.map { $0.pitches[0].showAccidental } == [false, true, false, true, true, false])36    #expect(notes.map(\.beam) == [.begin, .end, .begin, .end, .none, .none])37    // C#4 is below the middle line (stem up); C6 above (stem down).38    #expect(notes[4].stemUp && !notes[5].stemUp)39    #expect(notes[0].noteType == .eighth && notes[4].noteType == .quarter)40    #expect(notes[0].pitches[0].track == 0 && notes[1].pitches[0].index == 1)41}4243@Test func layoutFillsSystemsAndBreaksPages() async throws {44    let score = try await compiledScore("        repeat 120 {\n            play C4 duration 1/4\n            play E4 duration 1/8\n            play G4 duration 1/8\n            play C5 duration 1/2\n        }")45    #expect(score.measures.count == 120)46    for paper in ScorePaper.all {47        let layout = ScoreLayout.make(score: score, paper: paper)48        #expect(layout.pages.count > 1)49        var seen: [Int] = []50        let systems = layout.pages.flatMap(\.systems)51        for (pi, page) in layout.pages.enumerated() {52            #expect(page.number == pi + 1)53            for system in page.systems {54                let isLast = system.measures.last?.index == score.measures.count - 155                seen += system.measures.map(\.index)56                // Staves stay on the page.57                #expect((system.staffTops.last ?? 0) + 4 * layout.style.staffSpace <= paper.height - layout.style.margin + 0.5)58                #expect(system.x >= layout.style.margin - 0.5 && system.x + system.width <= paper.width - layout.style.margin + 0.5)59                // Measures are contiguous and fill the system; full systems reach the right margin.60                var x = system.x + system.prefixWidth61                for m in system.measures {62                    #expect(abs(m.x - x) < 0.01)63                    #expect(m.width > 0)64                    // Onsets move strictly to the right inside their measure.65                    #expect(zip(m.onsets, m.onsets.dropFirst()).allSatisfy { $0.x < $1.x && $0.offset < $1.offset })66                    #expect((m.onsets.last?.x ?? 0) < m.width)67                    x += m.width68                }69                #expect(abs(x - (system.x + system.width)) < 0.01)70                if !isLast { #expect(abs(system.x + system.width - (paper.width - layout.style.margin)) < 0.5) }71            }72        }73        #expect(seen == Array(0..<120), "every measure exactly once, in order")74        #expect(systems.first?.isFirst == true && systems.dropFirst().allSatisfy { !$0.isFirst })75        #expect(layout.locate(measure: 119)?.page == layout.pages.count - 1)76    }77}7879@Test func staffGeometry() {80    let treble = StaffGeometry(top: 100, staffSpace: 10, clef: "treble")81    // Top line F5, bottom line E4, middle line B4.82    #expect(treble.y(5 * 7 + 3) == 100 && treble.y(4 * 7 + 2) == 140 && treble.y(4 * 7 + 6) == treble.middle)83    #expect(treble.ledgerLines(for: 4 * 7).map { treble.y($0) } == [150]) // middle C: one line below84    #expect(treble.ledgerLines(for: 5 * 7 + 5).count == 1) // A5: one line above85    #expect(treble.ledgerLines(for: 4 * 7 + 4).isEmpty)86    #expect(treble.ledgerLines(for: 3 * 7 + 5).count == 2) // A387    let bass = StaffGeometry(top: 0, staffSpace: 10, clef: "bass")88    #expect(bass.y(3 * 7 + 1) == bass.middle) // D389    // G major: F sharp on the top line of the treble staff, on the fourth line of the bass staff.90    #expect(StaffGeometry.keySignatureOffsets(fifths: 1, clef: "treble") == [0])91    #expect(StaffGeometry.keySignatureOffsets(fifths: 1, clef: "bass") == [2])92    #expect(StaffGeometry.keySignatureOffsets(fifths: -3, clef: "treble") == [4, 1, 5])93    #expect(StaffGeometry.keySignatureOffsets(fifths: 0, clef: "treble").isEmpty)94    #expect(StaffGeometry.keySignatureOffsets(fifths: 9, clef: "treble").count == 7)95}9697@Test func hitsAndPDF() async throws {98    let score = try await compiledScore("        repeat 60 {\n            chord [C4, E4, G4] duration 1/2\n            tuplet 3 in 2 {\n                play A4 duration 1/8\n                play B4 duration 1/8\n                play C5 duration 1/8\n            }\n            rest 1/4\n        }")99    let layout = ScoreLayout.make(score: score)100    let renderer = ScoreRenderer(score: score, layout: layout)101    let total = (0..<layout.pages.count).reduce(0) { $0 + renderer.hits(page: $1).count }102    #expect(total == 60 * 6, "one hit rectangle per notehead")103    let first = try #require(renderer.hits(page: 0).first)104    #expect(first.rect.width > 0 && first.rect.minX > layout.style.margin)105    #expect(renderer.hits(page: 99).isEmpty)106    #expect(score.parts[0].measures[0].voices[0].contains { $0.tuplet?.actual == 3 })107108    let data = renderer.pdfData()109    let pdf = try #require(PDFDocument(data: data))110    #expect(pdf.pageCount == layout.pages.count && pdf.pageCount > 1)111    let box = try #require(pdf.page(at: 0)).bounds(for: .mediaBox)112    #expect(abs(box.width - layout.paper.width) < 0.5 && abs(box.height - layout.paper.height) < 0.5)113    // The title is real text in the PDF (vector, searchable), not a picture of it.114    #expect(pdf.page(at: 0)?.string?.contains("Test") == true)115}116117@Test func percussionIsWrittenOnTheMiddleLine() async throws {118    let source = "import std.instruments\n\ncomposition \"Drums\" {\n    tempo 120bpm\n    instrument kick: Kick {\n        play C2 duration 1/4\n        play C2 duration 1/4\n    }\n}\n"119    let session = SonataCompilerSession()120    let result = try await session.compile(name: "main", source: source)121    #expect(result.errors.isEmpty, "\(result.errors.map(\.message))")122    let score = try ScoreDocument.decode(json: await session.exportJSON("score"))123    #expect(score.parts[0].clef == "percussion")124    let e = try #require(score.parts[0].measures[0].voices[0].first)125    let g = StaffGeometry(top: 0, staffSpace: 10, clef: "percussion")126    #expect(g.y(e.pitches[0].position) == g.middle)127}128
Files main
Menu

Theme