Repository Public
1// ORIX Sonata2// File: Packages/SonataUI/Tests/SonataUITests/DocumentRoundTripTests.swift3// Description: The main journey without a window: new project, edit, compile, diagnostics, fix,4// mixer and note edits, save to disk, reopen, recompile, render — and the same for a lone file.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import SonataBridge10import SonataProject11import Testing12@testable import SonataUI1314@Test @MainActor func projectJourneyEditCompileSaveReopenRender() async throws {15 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("sonata-journey-" + UUID().uuidString)16 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)17 defer { try? FileManager.default.removeItem(at: dir) }1819 // A new project starts from the template, which must compile as shipped.20 let document = SonataDocument()21 let model = DocumentModel(document: document)22 #expect(await model.compile(load: false), "\(model.diagnostics.map(\.message))")23 #expect(model.runState == .ready && model.diagnostics.filter { $0.severity == .error }.isEmpty)24 let timeline = try #require(model.timeline)25 #expect(timeline.tracks.map(\.name) == ["piano", "lead"])2627 // An error is reported with its place, the previous timeline stays, and its safe fix repairs it.28 let good = model.text(for: model.mainPath)29 model.setText(good.replacingOccurrences(of: "ConcertStrings", with: "ConcertString"), for: model.mainPath)30 #expect(model.isStale)31 #expect(!(await model.compile(load: false)))32 #expect(model.runState == .failed)33 let error = try #require(model.diagnostics.first { $0.severity == .error })34 #expect(error.file == model.mainPath && error.line == 21, "\(error)")35 #expect(model.timeline != nil, "the last valid program is kept")36 if let fix = error.fix {37 model.apply(fix, in: error.file)38 #expect(model.text(for: model.mainPath) == good, "the suggested fix restores the name")39 } else {40 model.setText(good, for: model.mainPath)41 }42 #expect(await model.compile(load: false))4344 // Studio edits are overrides beside the code: the code is untouched, the compiled result changes.45 model.setGain(StripID(.track, 0), db: -14)46 model.setMute(StripID(.track, 1), true)47 let piano = try #require(model.timeline?.tracks.first)48 let first = try #require(piano.notes.first)49 model.editNotes([first], in: piano, actionName: "Transpose") { n, base in50 var o = base51 o.pitch = n.pitch + 1252 return o53 }54 model.addNote(AddedNote(track: "piano", start: RationalValue(2, 1), duration: RationalValue(1, 4), pitch: 60, velocity: 0.7))55 model.setLoop(enabled: true, start: 1, end: 3)56 #expect(await model.compile(load: false))57 #expect(model.text(for: model.mainPath) == good)58 #expect(model.conflicts.isEmpty)59 let edited = try #require(model.timeline)60 #expect(edited.tracks[0].gainDb == -14 && edited.tracks[1].mute)61 #expect(edited.tracks[0].notes.first { $0.index == first.index }?.pitch == first.pitch + 12)62 #expect(edited.tracks[0].notes.contains { $0.added && $0.pitch == 60 })63 #expect(model.noteOverrideCount(track: "piano") == 2)6465 // Save, with an asset that the format must carry over untouched.66 let url = dir.appendingPathComponent("Piece.sonataproject")67 try document.fileWrapper(snapshot: try document.snapshot(contentType: .sonataProject), asSource: false, existing: nil).write(to: url, options: .atomic, originalContentsURL: nil)68 try Data([1, 2, 3]).write(to: url.appendingPathComponent("assets/note.bin"))6970 // Reopen: same code, same studio state, same compiled result.71 let reopened = try SonataDocument(fileWrapper: FileWrapper(url: url), isProject: true)72 #expect(reopened.openWarnings.isEmpty)73 let again = DocumentModel(document: reopened)74 again.fileURL = url75 #expect(again.text(for: again.mainPath) == good)76 #expect(again.studio == model.studio)77 #expect(await again.compile(load: false))78 #expect(again.timeline == edited)7980 // A code change that invalidates a note edit is reported as a conflict, not applied blindly.81 again.setText(good.replacingOccurrences(of: "chord [D3, A3, D4] duration 1/2", with: "chord [E3, B3, E4] duration 1/2"), for: again.mainPath)82 #expect(await again.compile(load: false))83 #expect(again.conflicts.contains { $0.kind == "note" }, "\(again.conflicts)")84 again.removeNoteOverrides()85 again.resetStrip(StripID(.track, 0))86 #expect(await again.compile(load: false))87 #expect(again.conflicts.isEmpty && again.timeline?.tracks[0].gainDb == -3, "back to what the code says")8889 // Save again over the existing package: the asset survives, a second module is stored.90 #expect(again.addSource(named: "motifs") == "src/motifs.sonata")91 try reopened.fileWrapper(snapshot: try reopened.snapshot(contentType: .sonataProject), asSource: false, existing: try FileWrapper(url: url)).write(to: url, options: .atomic, originalContentsURL: url)92 #expect(try Data(contentsOf: url.appendingPathComponent("assets/note.bin")) == Data([1, 2, 3]))93 #expect(try SonataProjectBundle.read(from: url).sources.keys.sorted() == ["src/main.sonata", "src/motifs.sonata"])9495 // Render what is on screen to a file and read it back.96 var options = RenderOptions(path: dir.appendingPathComponent("piece.wav").path)97 options.bitDepth = 1698 let rendered = try await again.render(options, cancellation: RenderCancellation()).get()99 let file = try #require(rendered.files.first)100 #expect(rendered.ok && file.peakDb > -40 && file.peakDb <= -1.0 + 0.01)101 #expect(again.runState == .ready)102 let audio = try DecodedAudio(url: URL(fileURLWithPath: file.path))103 #expect(audio.duration >= 5.0 && audio.channels == 2)104 again.close()105 model.close()106}107108@Test @MainActor func loneFileRoundTripsAsPlainText() async throws {109 let source = "composition \"Solo\" {\n tempo 100bpm\n instrument flute: Flute {\n play G4 duration 1/2\n }\n}\n"110 let document = SonataDocument(source: source, isProject: false)111 let model = DocumentModel(document: document)112 #expect(await model.compile(load: false), "\(model.diagnostics.map(\.message))")113 model.setText(source + "// edited\n", for: model.mainPath)114 let wrapper = try document.fileWrapper(snapshot: try document.snapshot(contentType: .sonataSource), asSource: true, existing: nil)115 #expect(String(decoding: try #require(wrapper.regularFileContents), as: UTF8.self) == source + "// edited\n")116 let reopened = try SonataDocument(fileWrapper: wrapper, isProject: false)117 #expect(DocumentModel(document: reopened).text(for: "src/main.sonata") == source + "// edited\n")118 #expect(throws: (any Error).self) { try SonataDocument(fileWrapper: FileWrapper(regularFileWithContents: Data([0xff, 0xfe, 0xfd])), isProject: false) }119 model.close()120}121