From 8a1d231c783f7e8df9d810af9682c3fa1925c69f Mon Sep 17 00:00:00 2001 From: "prompt.ac/@jeffrey" Date: Sat, 9 May 2026 15:24:14 -0400 Subject: [PATCH] slab/menuband: PDF score round-trip with sample-accurate playback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drag a Menu Band PDF onto the menubar piano (or back onto the score area) and the synth replays the original performance — sample- accurate timing, full sustain, with the auto-played keys lit RED to distinguish "score is playing me back" from "I'm pressing keys." Embeds two payloads in the PDF Info dictionary: • Subject = MusicXML for the staff visual. • Keywords = ["MenuBandFormat:1", "events:"], where the json is [{midi, on, off}] in seconds-from-first-onset. Held notes export as off:null and Swift clamps them to the latest released note's release at extract time, so sustain matches what the user actually held until they grabbed the drag. Timing: • Sheet.noteOn(pitch, t) accepts a Swift-supplied CACurrentMediaTime, bypassing WebKit bridge's variable 5–50ms delivery latency. Onsets are anchored to the input event, not when JS happens to receive the message. • Replay schedules note-on/off via DispatchQueue.main .asyncAfter at .nanoseconds() precision (was rounding to ms). • MenuBandPopover.refreshHeldNotes records `display + octaveShift × 12` so the played pitch (what the user heard) round-trips, not the menubar-clamped C4–B5 display window. • buildMusicXML emits a directive in measure 1 — derived from beatInterval when the metronome's running, or the median (real_gap / notated_seconds_at_120bpm) ratio when free-playing — so Verovio's renderToMIDI replays at the inferred tempo (legacy fallback path for pre-events PDFs). UX polish: • Drag-out clears the staff once the drop completes (NSDraggingSource endedAt) so the next take starts fresh. • Drag-in clears the local notes buffer first so the imported score replaces (not overlays) what was on screen. • Menubar drop target also accepts .pdf, dispatched to a new handlePDFFileDrop that opens the popover and hands off to SheetMusicView.loadAndPlay. Format-spec backstory: the original /MenuBandMusicXML + /MenuBandFormat custom Info-dict keys round-tripped on disk but PDFKit serialised them as PDF strings (parens) instead of PDF names (slash-prefixed). CoreGraphics's stricter parser rejected the whole dict on read with "found non-name key while building dictionary" → documentAttributes returned empty. Switched to Subject + Keywords (predefined PDFDocumentAttribute keys that PDFKit serialises correctly) and kept a raw-bytes legacy fallback for PDFs from the broken format. --- .../Sources/MenuBand/AppDelegate.swift | 43 +- .../MenuBand/KeyboardIconRenderer.swift | 22 +- .../Sources/MenuBand/MenuBandController.swift | 68 +++ .../Sources/MenuBand/MenuBandPopover.swift | 14 +- .../Sources/MenuBand/MidiDropTargetView.swift | 21 +- .../Sources/MenuBand/MidiFilePlayer.swift | 9 + .../MenuBand/Resources/verovio/sheet.html | 107 ++++- .../Sources/MenuBand/SheetMusicView.swift | 393 ++++++++++++++++-- 8 files changed, 618 insertions(+), 59 deletions(-) diff --git a/slab/menuband/Sources/MenuBand/AppDelegate.swift b/slab/menuband/Sources/MenuBand/AppDelegate.swift index d97c7c6ee1..52aa39458a 100644 --- a/slab/menuband/Sources/MenuBand/AppDelegate.swift +++ b/slab/menuband/Sources/MenuBand/AppDelegate.swift @@ -340,13 +340,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate { trackingArea = area // Drag-drop a .mid / .midi file onto the menubar icon // to play it back through the synth as if a player - // piano was striking the keys. Drop target is a + // piano was striking the keys. A Menu Band-authored + // .pdf works the same way — its embedded MusicXML is + // round-tripped through Verovio to produce playable + // MIDI, the popover opens to show the staff, and the + // synth plays the score back. Drop target is a // transparent subview that fills the button so the // button still receives clicks normally. let dropTarget = MidiDropTargetView(frame: button.bounds) dropTarget.autoresizingMask = [.width, .height] dropTarget.onDrop = { [weak self] url in - self?.handleMidiFileDrop(url: url) + let ext = url.pathExtension.lowercased() + if ext == "pdf" { + self?.handlePDFFileDrop(url: url) + } else { + self?.handleMidiFileDrop(url: url) + } } button.addSubview(dropTarget) } @@ -942,6 +951,35 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } } + /// Drag-and-drop entry point for Menu Band PDFs onto the + /// menubar piano icon. Opens the popover so the user sees the + /// score render as it auto-plays, then hands the URL to the + /// sheet view — same `loadAndPlay` code path as dropping the + /// PDF onto the score area inside an already-open popover. + private func handlePDFFileDrop(url: URL) { + // Open the popover first so the SheetMusicView is laid out + // and its WKWebView is in a window — `loadAndPlay` evaluates + // JS through that webView, which silently no-ops if it has + // no host. `showPopover` is idempotent when the popover is + // already up. + showPopover() + // Defer to the next runloop pass so the popover's view + // hierarchy + initial layout finish before we shove a new + // score through the JS bridge. Without this hop the first + // drag-onto-menubar after launch lands while the sheet + // hasn't loaded yet, and the eval fires into a not-ready + // toolkit. + DispatchQueue.main.async { [weak self] in + guard let sheet = self?.popoverVC?.sheetView else { + NSLog("MenuBand: PDF drop \(url.lastPathComponent) — no sheet view available") + return + } + if !sheet.loadAndPlay(pdfURL: url) { + NSLog("MenuBand: PDF drop \(url.lastPathComponent) wasn't a Menu Band score — ignoring") + } + } + } + // MARK: - Adaptive menubar layout /// `true` when the status item button is laid out on a real screen. @@ -1378,6 +1416,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { let voiceLabel: String? = (menuBand.instrumentBackend == .sample) ? "`" : nil button.image = KeyboardIconRenderer.image( litNotes: menuBand.litNotes, + playbackLitNotes: menuBand.playbackLitNotes, enabled: menuBand.midiMode, typeMode: menuBand.typeMode, melodicProgram: menuBand.effectiveMelodicProgram, diff --git a/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift b/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift index 66f0644f96..e3f863f97b 100644 --- a/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift +++ b/slab/menuband/Sources/MenuBand/KeyboardIconRenderer.swift @@ -409,6 +409,7 @@ enum KeyboardIconRenderer { private static var settingsRect: NSRect { settingsHitRect } static func image(litNotes: Set, + playbackLitNotes: Set = [], enabled: Bool, typeMode: Bool = false, melodicProgram: UInt8 = 0, @@ -462,6 +463,12 @@ enum KeyboardIconRenderer { ?? NSColor.controlAccentColor) : (NSColor.controlAccentColor.highlight(withLevel: 0.30) ?? NSColor.controlAccentColor) + // Playback fill — red, distinct from the system-accent + // press color so the user can tell "the score is playing + // me back" from "I'm pressing keys right now." + let playbackLit: NSColor = isDark + ? NSColor(srgbRed: 230/255, green: 60/255, blue: 60/255, alpha: 1) + : NSColor(srgbRed: 220/255, green: 35/255, blue: 35/255, alpha: 1) let groove: NSColor let whiteHi: NSColor let whiteLo: NSColor @@ -519,6 +526,7 @@ enum KeyboardIconRenderer { if !isActive(m) { continue } // negative space — skip draw let rect = whiteRect(at: idx + slotOffset) let isLit = tileOffset == 0 && litNotes.contains(UInt8(m)) + let isPlaybackLit = tileOffset == 0 && playbackLitNotes.contains(UInt8(m)) let isHover = tileOffset == 0 && hovered == .note(UInt8(m)) let isLeftmost = !sliding && (m == leftmostMidi) let isRightmost = !sliding && (m == rightmostMidi) @@ -529,7 +537,13 @@ enum KeyboardIconRenderer { br: isRightmost ? 2.5 : 0, bl: isLeftmost ? 2.5 : 0 ) - if isLit { + if isPlaybackLit { + // Auto-playback from a dragged-in PDF — red + // wins over the user's accent press color so + // the source of the sound stays unambiguous. + playbackLit.setFill() + path.fill() + } else if isLit { // Pressed: whole keycap turns the system accent // — the rainbow stripe stays hidden while the // key's down so the press reads as a single @@ -646,9 +660,13 @@ enum KeyboardIconRenderer { guard let leftIdx = whiteIndex[leftWhite] else { continue } let rect = blackRect(rightOfWhiteIndex: leftIdx + slotOffset) let isLit = tileOffset == 0 && litNotes.contains(UInt8(m)) + let isPlaybackLit = tileOffset == 0 && playbackLitNotes.contains(UInt8(m)) let isHover = tileOffset == 0 && hovered == .note(UInt8(m)) let path = roundedKeyPath(rect: rect, tl: 0, tr: 0, br: 1.2, bl: 1.2) - if isLit { + if isPlaybackLit { + playbackLit.setFill() + path.fill() + } else if isLit { if isDark { // Invert in dark mode — the saturated bright // sharp flips to a deep slate notch on press diff --git a/slab/menuband/Sources/MenuBand/MenuBandController.swift b/slab/menuband/Sources/MenuBand/MenuBandController.swift index 29814441b5..39471898cb 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandController.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandController.swift @@ -41,7 +41,14 @@ final class MenuBandController { // Visual state — accessed only on the main thread. private(set) var litNotes: Set = [] + /// Notes currently lit because they're being auto-played from a + /// dragged-in PDF. Rendered in red by KeyboardIconRenderer to + /// distinguish "the score is playing me back" from "I'm pressing + /// keys right now." Disjoint from `litNotes` because the source + /// of truth differs (synth callback vs user input pipeline). + private(set) var playbackLitNotes: Set = [] private var litDownAt: [UInt8: CFTimeInterval] = [:] + private var playbackChannel: [UInt8: UInt8] = [:] private let minVisibleSeconds: CFTimeInterval = 0.18 var onChange: (() -> Void)? @@ -1105,6 +1112,67 @@ final class MenuBandController { } } + // MARK: - Playback notes (PDF drag-in auto-play) + // + // Keep a separate channel so a dragged-in score's playback + // can light up the menubar piano in red without touching the + // normal `litNotes` user-input set. Sound emits the same way + // a tap would; only the visual state is parallel. + + /// Sound + light a note as part of an auto-playback session. + /// `displayNote` is the menubar-clamped key the renderer should + /// draw red — defaults to the played pitch when the caller + /// doesn't have an explicit display. + func startPlaybackNote(_ midiNote: UInt8, velocity: UInt8 = 100, + displayNote: UInt8? = nil) { + let synthCh = nextMelodicChannel() + playbackChannel[midiNote] = synthCh + let mc: UInt8 = 0 + if !midiMode { + synth.noteOn(midiNote, velocity: velocity, channel: synthCh) + } + midiNoteOn(midiNote, velocity: velocity, channel: mc) + let visualNote = displayNote ?? midiNote + let setLit = { [weak self] in + guard let self = self else { return } + if self.playbackLitNotes.insert(visualNote).inserted { + self.onLitChanged?() + } + } + if Thread.isMainThread { setLit() } else { DispatchQueue.main.async(execute: setLit) } + } + + /// Release a note previously started with `startPlaybackNote`. + func stopPlaybackNote(_ midiNote: UInt8, displayNote: UInt8? = nil) { + let synthCh = playbackChannel.removeValue(forKey: midiNote) ?? channel(for: midiNote) + if !midiMode { synth.noteOff(midiNote, channel: synthCh) } + midi.noteOff(midiNote, channel: 0) + let visualNote = displayNote ?? midiNote + DispatchQueue.main.async { [weak self] in + guard let self = self else { return } + if self.playbackLitNotes.remove(visualNote) != nil { + self.onLitChanged?() + } + } + } + + /// Panic — called when superseding a playback session so the + /// previous take doesn't strand notes. + func releaseAllPlaybackNotes() { + for (note, ch) in playbackChannel { + if !midiMode { synth.noteOff(note, channel: ch) } + midi.noteOff(note, channel: 0) + } + playbackChannel.removeAll() + DispatchQueue.main.async { [weak self] in + guard let self = self else { return } + if !self.playbackLitNotes.isEmpty { + self.playbackLitNotes.removeAll() + self.onLitChanged?() + } + } + } + // MARK: - Linger / bell-ring tail /// Shared release path for any note that was started under shift. diff --git a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift index 7faedc2aa9..4f8569a2f0 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift @@ -1104,7 +1104,19 @@ final class MenuBandPopoverViewController: NSViewController { // a separate event subscription. Released notes do nothing // here — the sheet is append-only by design (the user said // "as the user plays it plops them down"). - let currentHeld = Set(m.heldNoteEntries().map(\.midi)) + // + // Reverse the controller's `display = played - shift*12` + // clamp so the staff records the *played* pitch (what the + // synth actually sounded), not the menubar icon's clamped + // C4–B5 display window. Without this, the dragged-out PDF + // round-trips back to playback at the staff octave instead + // of the original octave — sounded wrong by 12 semitones + // every time the user had a non-zero octave shift. + let shiftSemitones = m.octaveShift * 12 + let currentHeld = Set(m.heldNoteEntries().map { entry -> UInt8 in + let played = Int(entry.midi) + shiftSemitones + return UInt8(max(0, min(127, played))) + }) let newOnsets = currentHeld.subtracting(lastSeenHeldMidis) let newReleases = lastSeenHeldMidis.subtracting(currentHeld) if let sheet = sheetView { diff --git a/slab/menuband/Sources/MenuBand/MidiDropTargetView.swift b/slab/menuband/Sources/MenuBand/MidiDropTargetView.swift index b894b09238..ddc41f9675 100644 --- a/slab/menuband/Sources/MenuBand/MidiDropTargetView.swift +++ b/slab/menuband/Sources/MenuBand/MidiDropTargetView.swift @@ -1,10 +1,13 @@ import AppKit -/// Transparent overlay that accepts a dragged `.mid` / `.midi` file -/// and forwards it to `onDrop`. Installed as a subview of the -/// menubar status item button (and, optionally, the popover content -/// view) so dragging a MIDI file onto Menu Band auto-plays it -/// through the synth. +/// Transparent overlay that accepts a dragged music file +/// (`.mid` / `.midi` for direct MIDI playback, or a Menu Band- +/// authored `.pdf` whose Info dictionary embeds the score's +/// MusicXML) and forwards it to `onDrop`. Installed as a subview +/// of the menubar status item button (and, optionally, the popover +/// content view) so dragging a music file onto Menu Band auto- +/// plays it through the synth — MIDI directly, PDFs after a +/// MusicXML→MIDI round-trip handled by AppDelegate. final class MidiDropTargetView: NSView { var onDrop: ((URL) -> Void)? @@ -34,7 +37,11 @@ final class MidiDropTargetView: NSView { return true } - /// Pull the first `.mid` / `.midi` URL off the drag pasteboard. + /// Pull the first acceptable music-file URL off the drag + /// pasteboard. Accepts `.mid`, `.midi`, and `.pdf` — extension + /// dispatch happens in the `onDrop` handler (AppDelegate + /// validates the PDF actually carries Menu Band metadata + /// before kicking off a render). private static func dragURL(from sender: NSDraggingInfo) -> URL? { let pb = sender.draggingPasteboard guard let urls = pb.readObjects(forClasses: [NSURL.self], @@ -43,7 +50,7 @@ final class MidiDropTargetView: NSView { } return urls.first(where: { url in let ext = url.pathExtension.lowercased() - return ext == "mid" || ext == "midi" + return ext == "mid" || ext == "midi" || ext == "pdf" }) } } diff --git a/slab/menuband/Sources/MenuBand/MidiFilePlayer.swift b/slab/menuband/Sources/MenuBand/MidiFilePlayer.swift index 1b399c700a..a44a50917a 100644 --- a/slab/menuband/Sources/MenuBand/MidiFilePlayer.swift +++ b/slab/menuband/Sources/MenuBand/MidiFilePlayer.swift @@ -184,6 +184,15 @@ final class MidiFilePlayer { if lhs.time != rhs.time { return lhs.time < rhs.time } return !lhs.isOn && rhs.isOn } + // Dump first few events so a noteOn-only summary lands in + // the log — invaluable for diagnosing PDF-drag playback + // (octaves wrong / tempo off / etc) without hooking up a + // MIDI monitor. Only the first 8 ons. + let firstOns = events.filter(\.isOn).prefix(8) + let summary = firstOns + .map { String(format: "%.2fs:%d", $0.time, Int($0.midi)) } + .joined(separator: ", ") + NSLog("MidiFilePlayer: first onsets — \(summary)") return events } } diff --git a/slab/menuband/Sources/MenuBand/Resources/verovio/sheet.html b/slab/menuband/Sources/MenuBand/Resources/verovio/sheet.html index 1f8ce3de5d..1a33c20344 100644 --- a/slab/menuband/Sources/MenuBand/Resources/verovio/sheet.html +++ b/slab/menuband/Sources/MenuBand/Resources/verovio/sheet.html @@ -225,13 +225,61 @@ } } } + // Emit a tempo directive in measure 1 so Verovio's + // renderToMIDI plays back at the right speed. Without + // this Verovio defaults to 120 BPM and notes get packed + // back-to-back at their notated duration — which doesn't + // match the wall-clock spacing the user actually played. + // + // Two sources of truth for "the user's tempo": + // 1. Active metronome → 60 / beatInterval gives BPM + // directly. Most accurate when running. + // 2. Free play → for each consecutive note pair, + // compute the ratio of real-time onset gap to the + // notated tick duration of the first note (in + // seconds at 120 BPM). The median ratio scales + // 120 BPM into the right playback tempo, so each + // notated quarter/eighth/16th lasts as long as the + // user's actual onset spacing demanded. + let inferredBpm = 120; + if (metronomeActive(now) && beatInterval > 0) { + inferredBpm = Math.round(60 / beatInterval); + } else if (notes.length >= 2) { + // 1 tick @ 120 BPM with TICKS_PER_BEAT=4: + // secs/tick = 60 / 120 / 4 = 0.125 + const SECS_PER_TICK_AT_120 = 0.125; + const ratios = []; + for (let i = 1; i < notes.length; i++) { + const real = notes[i].onsetAt - notes[i - 1].onsetAt; + if (real <= 0.05 || real > 4.0) continue; + const heldFor = (notes[i - 1].releasedAt ?? notes[i - 1].onsetAt + real) - notes[i - 1].onsetAt; + const ticks = durationOf(heldFor, now).ticks; + const notated = ticks * SECS_PER_TICK_AT_120; + if (notated <= 0) continue; + ratios.push(real / notated); + } + if (ratios.length >= 1) { + ratios.sort((a, b) => a - b); + const median = ratios[Math.floor(ratios.length / 2)]; + // ratio > 1 means real time was longer than notated + // → playback should be slower → lower BPM. + const bpm = Math.round(120 / median); + inferredBpm = Math.max(40, Math.min(200, bpm)); + } + } const head = (m === 0) ? ` ${TICKS_PER_BEAT} 0 G2 - ` : ''; + + + + quarter${inferredBpm} + + + ` : ''; measuresXml += `\n ${head}${body}\n `; } @@ -364,8 +412,16 @@ // ---- public API (called via webview.evaluateJavaScript) ---- - function noteOn(pitch) { - const now = performance.now() / 1000; + // `t` is an optional Swift-supplied timestamp (seconds in + // CACurrentMediaTime base). Swift captures the time at the + // input event itself — passing it in avoids the WebKit + // bridge's variable 5-50ms delivery latency, which otherwise + // jitters every recorded onsetAt and ruins playback timing. + // Falls back to performance.now() for callers that don't + // supply a time (test harnesses, future direct-from-JS + // input paths). + function noteOn(pitch, t) { + const now = (typeof t === 'number') ? t : performance.now() / 1000; notes.push({ pitch, isSharp: midiToStep(pitch).alter === 1, @@ -391,10 +447,11 @@ // the next note onset/release fires. } - function noteOff(pitch) { + function noteOff(pitch, t) { + const now = (typeof t === 'number') ? t : performance.now() / 1000; for (let i = notes.length - 1; i >= 0; i--) { if (notes[i].pitch === pitch && notes[i].releasedAt == null) { - notes[i].releasedAt = performance.now() / 1000; + notes[i].releasedAt = now; break; } } @@ -459,6 +516,36 @@ return buildMusicXML(); } + // Sample-accurate playback events. The notation system + // quantises durations to the 16th-grid which is great for + // legibility but loses the user's wall-clock timing on + // playback (notes pack back-to-back at their notated + // duration). Swift uses this list to schedule note-on/off + // at the EXACT relative seconds the user actually played, + // so dragging a PDF back in replays the original + // performance precisely — even when no notation could + // capture that rhythm. Times are seconds-from-first-onset. + function getPlaybackEvents() { + if (notes.length === 0) return '[]'; + const t0 = notes[0].onsetAt; + const out = notes.map(n => { + // Held notes export with off:null so Swift can clamp + // the duration at extract time (= "still held until + // the user dragged the score off"). Without this the + // exported sustain was a hardcoded 0.25s placeholder + // and held notes played back as staccatos. + const offRel = (n.releasedAt != null) + ? +(n.releasedAt - t0).toFixed(4) + : null; + return { + midi: n.pitch, + on: +(n.onsetAt - t0).toFixed(4), + off: offRel, + }; + }); + return JSON.stringify(out); + } + // Drag-back-in entry: parse a MusicXML payload (from a // previously-exported Menu Band PDF), re-render the staff // visually, and emit a MIDI rendering of the same content @@ -467,7 +554,15 @@ // empty string signals a Verovio failure (we still render // the SVG best-effort so the staff at least shows the // notation, but playback is skipped). + // + // Important: clear the local `notes` buffer FIRST so the + // dropped score replaces (not overlays) what was on screen. + // We bypass `clear()`'s queueRender so the next rerender + // doesn't overwrite our directly-loaded XML with an empty + // build from the (now-empty) notes array — the rebuild + // races with our renderToSVG and the staff goes blank. function loadXMLAndExportMIDI(xml) { + notes.length = 0; try { toolkit.loadData(xml); document.getElementById('score').innerHTML = @@ -505,7 +600,7 @@ } return { noteOn, noteOff, beat, clear, ready, getMusicXML, - loadXMLAndExportMIDI, loadNotes }; + getPlaybackEvents, loadXMLAndExportMIDI, loadNotes }; }()); Sheet.ready(); diff --git a/slab/menuband/Sources/MenuBand/SheetMusicView.swift b/slab/menuband/Sources/MenuBand/SheetMusicView.swift index f770a776cf..14b7cda998 100644 --- a/slab/menuband/Sources/MenuBand/SheetMusicView.swift +++ b/slab/menuband/Sources/MenuBand/SheetMusicView.swift @@ -38,31 +38,43 @@ final class SheetMusicView: NSView, WKNavigationDelegate, WKScriptMessageHandler // MARK: - "Menu Band PDF" embedded-score format // - // A Menu Band PDF is a regular PDF whose Info dictionary - // (PDFKit's `documentAttributes`) carries two extra keys: + // A Menu Band PDF is a regular PDF whose standard Info + // dictionary carries the round-trip payload: // - // • MenuBandFormat — schema version string. "1" today. - // Bump on any incompatible change to - // the embedded payload. - // • MenuBandMusicXML — full MusicXML representation of the - // score. Verovio's MusicXML output, so - // it round-trips through `loadData` → - // `renderToSVG` and `renderToMIDI` - // losslessly. + // • Subject — full MusicXML representation of the score + // (Verovio's MusicXML output; round-trips + // losslessly through `loadData` → SVG/MIDI). + // • Keywords — `["MenuBandFormat:1"]`. Identifies the PDF + // as a Menu Band score and carries the schema + // version. Bump on any incompatible change. + // • Title — "Menu Band score" (cosmetic, shown by Finder). + // • Creator — "Menu Band" (cosmetic, shown by Finder). + // + // Why standard fields and not custom Info keys: an earlier + // version stored the XML under `/MenuBandMusicXML` and the + // version under `/MenuBandFormat`. PDFKit's + // `documentAttributes` setter happily wrote those, but the + // SERIALIZER emitted them as PDF *strings* — `(MenuBandMusicXML)` + // — instead of PDF *names* — `/MenuBandMusicXML`. PDF spec + // requires Info dict keys to be names, so CoreGraphics's + // stricter parser rejected the whole dict on read with + // "found non-name key while building dictionary". `Subject` + // and `Keywords` are predefined PDFDocumentAttribute keys that + // PDFKit serializes correctly, so the round-trip works. // // Round-trip: - // drag OUT — `schedulePDFRefresh` writes both keys via + // drag OUT — `schedulePDFRefresh` writes the four fields via // `PDFDocument.documentAttributes` + `write(to:)`. - // PDFKit serializes the Info dict literal as - // `(MenuBandMusicXML)<...> (MenuBandFormat)(1)` - // inside the PDF; verified with `grep -a` on the - // binary. - // drag IN — `performDragOperation` reads back the same keys, - // hands the XML to `Sheet.loadXMLAndExportMIDI`, - // and routes Verovio's MIDI render through - // `MidiFilePlayer.play` so the score auto-plays. - private static let pdfFormatKey = "MenuBandFormat" - private static let pdfFormatVersion = "1" + // drag IN — `loadAndPlay` reads `Subject` (with a legacy- + // format fallback that grep-extracts the old + // `/MenuBandMusicXML` parenthesis-string from the + // raw bytes), hands the XML to + // `Sheet.loadXMLAndExportMIDI`, and routes + // Verovio's MIDI render through `MidiFilePlayer` + // so the score auto-plays. + private static let pdfFormatKeyword = "MenuBandFormat:1" + /// Legacy custom-key fallback — read-only, for PDFs exported + /// by versions before the move to standard Info fields. private static let pdfMusicXMLKey = "MenuBandMusicXML" /// 8.5×11 letter aspect ratio so the card looks like a real @@ -245,13 +257,32 @@ final class SheetMusicView: NSView, WKNavigationDelegate, WKScriptMessageHandler let pdfURL = tmpDir.appendingPathComponent("Menu-Band-\(stamp).pdf") NSLog("SheetMusicView: PDF refresh starting → \(pdfURL.lastPathComponent), webView.bounds=\(webView.bounds), xml=\(xmlAtRender.count) chars") - // Toggle the export-only stylesheet (kills the SVG noise - // filter + box shadows, which can't be vectorized into PDF - // and otherwise rasterize to 200+ MB at Retina DPI). The - // class is removed in the completion handler. - webView.evaluateJavaScript("document.body.classList.add('exporting')", - completionHandler: nil) + // Fetch the wall-clock event list FIRST so it's available + // when we write the PDF. Chained to avoid a race between + // the async eval and the async createPDF — without this + // chain the events JSON could be missing or stale when + // the file is finalised. + webView.evaluateJavaScript("Sheet.getPlaybackEvents()") { [weak self] eventsResult, _ in + guard let self = self else { return } + let eventsJSON = (eventsResult as? String) ?? "[]" + // Toggle the export-only stylesheet (kills the SVG noise + // filter + box shadows, which can't be vectorized into + // PDF and otherwise rasterize to 200+ MB at Retina DPI). + // Removed in the createPDF completion below. + self.webView.evaluateJavaScript( + "document.body.classList.add('exporting')", + completionHandler: nil) + self.runCreatePDF(to: pdfURL, + eventsJSON: eventsJSON, + xmlAtRender: xmlAtRender) + } + } + /// Inner half of the async chain — performs the actual PDF + /// render once the events list has been captured. + private func runCreatePDF(to pdfURL: URL, + eventsJSON: String, + xmlAtRender: String) { // Modern WKWebView async API — renders the page to a PDF // off the main runloop without entering a nested event // loop, so calling this during tracking is safe. @@ -272,18 +303,24 @@ final class SheetMusicView: NSView, WKNavigationDelegate, WKScriptMessageHandler } if let pdf = PDFDocument(url: pdfURL) { var attrs = pdf.documentAttributes ?? [:] - attrs[Self.pdfFormatKey] = Self.pdfFormatVersion - attrs[Self.pdfMusicXMLKey] = xmlAtRender + attrs[PDFDocumentAttribute.subjectAttribute] = xmlAtRender + attrs[PDFDocumentAttribute.keywordsAttribute] = [ + Self.pdfFormatKeyword, + "events:\(eventsJSON)", + ] attrs[PDFDocumentAttribute.creatorAttribute] = "Menu Band" attrs[PDFDocumentAttribute.titleAttribute] = "Menu Band score" pdf.documentAttributes = attrs pdf.write(to: pdfURL) } - // Drop the previous cached file so /tmp doesn't grow - // unbounded across many renders. - if let old = self.cachedPDFURL, old != pdfURL { - try? FileManager.default.removeItem(at: old) - } + // Don't delete the previous cached file even though + // it's superseded — `cachedPDFURL` is what the + // pasteboard writer hands to the OS at drag-start, + // and the drop target may not consult it until tens + // of ms later (especially for cross-app drops). A + // delete here races with that read and turns the + // dropped PDF into a "file not found" silent fail. + // /tmp is cleaned at boot, so the leak is bounded. self.cachedPDFURL = pdfURL case .failure(let error): NSLog("SheetMusicView: createPDF failed — \(error)") @@ -308,6 +345,20 @@ final class SheetMusicView: NSView, WKNavigationDelegate, WKScriptMessageHandler return .copy } + /// Clear the staff once the drag ends — only on a successful + /// drop (operation != []), so an aborted drag (drop on the + /// originating popover, drop outside any target, Esc-cancel) + /// leaves the in-progress score untouched. Treat the drop as + /// "I'm done with this take, start the next one fresh." + func draggingSession( + _ session: NSDraggingSession, + endedAt screenPoint: NSPoint, + operation: NSDragOperation + ) { + guard operation != [] else { return } + clearScore() + } + // NSFilePromiseProviderDelegate is no longer needed (eager render // path uses NSURL pasteboard writers directly), but keeping the // protocol conformance keeps compile-time API stable for any @@ -347,10 +398,35 @@ final class SheetMusicView: NSView, WKNavigationDelegate, WKScriptMessageHandler override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { guard let url = acceptablePDFURL(from: sender) else { return false } - guard let pdf = PDFDocument(url: url), - let attrs = pdf.documentAttributes, - let xml = attrs[Self.pdfMusicXMLKey] as? String, - !xml.isEmpty else { return false } + return loadAndPlay(pdfURL: url) + } + + /// Public entry point for "PDF score → re-render staff + auto- + /// play through the synth." Used by both `performDragOperation` + /// (drop on the score area inside the popover) AND by + /// AppDelegate's status-item drop handler (drop on the menubar + /// piano icon, mirroring the .mid drag-onto-menubar flow). Returns + /// false on any failure (not a Menu Band PDF, no MusicXML, JS + /// eval errored). The visual side renders best-effort even when + /// MIDI export fails — the user at least sees the staff redrawn. + @discardableResult + func loadAndPlay(pdfURL: URL) -> Bool { + let exists = FileManager.default.fileExists(atPath: pdfURL.path) + guard exists else { + NSLog("SheetMusicView: drop \(pdfURL.lastPathComponent) — file no longer exists at \(pdfURL.path)") + return false + } + guard let xml = Self.extractMusicXML(from: pdfURL), !xml.isEmpty else { + NSLog("SheetMusicView: drop \(pdfURL.lastPathComponent) — no Menu Band MusicXML found in PDF (neither /Subject nor legacy /MenuBandMusicXML)") + return false + } + NSLog("SheetMusicView: loadAndPlay \(pdfURL.lastPathComponent) — \(xml.count) chars of MusicXML") + // Read the wall-clock event list (Format v2). Verovio's MIDI + // render quantises onsets to the 16th-grid which throws + // playback timing off — the events list is what the user + // actually played, sample-accurate. Falls back to MIDI route + // when the PDF predates the events embedding. + let events = Self.extractPlaybackEvents(from: pdfURL) // Hand the embedded MusicXML to Verovio: it re-renders the // staff (same code path as the live transcription, just // seeded from XML instead of accumulated noteOn events) and @@ -378,15 +454,131 @@ final class SheetMusicView: NSView, WKNavigationDelegate, WKScriptMessageHandler NSLog("SheetMusicView: drag-in eval failed — \(error)") return } + // Prefer exact-timing playback from the embedded events list. + if let events = events, !events.isEmpty { + NSLog("SheetMusicView: drag-in playing \(events.count) events with sample-accurate timing") + self.playEvents(events) + return + } + // Legacy fallback: route Verovio's quantised MIDI through + // MidiFilePlayer. Only used for PDFs exported before the + // events list was embedded. guard let base64 = result as? String, !base64.isEmpty else { - NSLog("SheetMusicView: drag-in returned no MIDI — playback skipped") + NSLog("SheetMusicView: drag-in returned no MIDI — playback skipped (Verovio renderToMIDI may have failed; staff still re-rendered)") return } + NSLog("SheetMusicView: drag-in produced \(base64.count) chars of base64 MIDI — handing to player (legacy path)") self.playImportedMIDI(base64: base64) } return true } + /// One auto-play event extracted from a Menu Band PDF. + /// Times are seconds-from-first-onset (relative); replay + /// converts them to wall-clock deadlines via DispatchQueue. + struct PlaybackEvent { + let midi: UInt8 + let on: TimeInterval + let off: TimeInterval + } + + private var pendingPlaybackWork: [DispatchWorkItem] = [] + + /// Wall-clock-accurate replay. Each event is a single + /// `asyncAfter` for note-on plus another for note-off, so the + /// menubar piano lights red at exactly the moment the user + /// originally played the note. Supersedes any in-flight + /// playback (.mid drop, prior PDF, etc) before scheduling. + private func playEvents(_ events: [PlaybackEvent]) { + guard let menuBand = self.menuBand else { + NSLog("SheetMusicView: no MenuBandController — can't auto-play") + return + } + // Stop everything in flight — MIDI player events, prior + // PDF events, and any held playback notes — before we + // schedule the new run. + MidiFilePlayer.stop() + for w in pendingPlaybackWork { w.cancel() } + pendingPlaybackWork.removeAll() + menuBand.releaseAllPlaybackNotes() + + let now = DispatchTime.now() + var lastOff: TimeInterval = 0 + for event in events { + let midi = event.midi + let onWork = DispatchWorkItem { [weak menuBand] in + menuBand?.startPlaybackNote(midi, velocity: 100, displayNote: midi) + } + let offWork = DispatchWorkItem { [weak menuBand] in + menuBand?.stopPlaybackNote(midi, displayNote: midi) + } + pendingPlaybackWork.append(onWork) + pendingPlaybackWork.append(offWork) + // Nanosecond-precision DispatchTime arithmetic — the + // earlier `.milliseconds(Int(...))` rounded sub-ms + // detail off every onset/release. + DispatchQueue.main.asyncAfter( + deadline: now + .nanoseconds(Int(event.on * 1_000_000_000)), + execute: onWork) + DispatchQueue.main.asyncAfter( + deadline: now + .nanoseconds(Int(event.off * 1_000_000_000)), + execute: offWork) + lastOff = max(lastOff, event.off) + } + // Tail panic in case any note's off scheduling slipped. + let tail = DispatchWorkItem { [weak menuBand] in + menuBand?.releaseAllPlaybackNotes() + } + pendingPlaybackWork.append(tail) + DispatchQueue.main.asyncAfter( + deadline: now + .nanoseconds(Int((lastOff + 0.05) * 1_000_000_000)), + execute: tail) + NSLog("SheetMusicView: scheduled \(events.count) playback events over \(String(format: "%.2f", lastOff))s") + } + + private static func extractPlaybackEvents(from url: URL) -> [PlaybackEvent]? { + // Format v2 stores the JSON event list as a Keyword entry + // prefixed with "events:". PDFKit returns Keywords as either + // an array of strings or a single comma-joined string + // depending on how the PDF was authored — handle both. + guard let pdf = PDFDocument(url: url), + let attrs = pdf.documentAttributes else { return nil } + let raw = attrs[PDFDocumentAttribute.keywordsAttribute] + var keywords: [String] = [] + if let arr = raw as? [String] { + keywords = arr + } else if let s = raw as? String { + keywords = s.split(separator: ",").map { + $0.trimmingCharacters(in: .whitespaces) + } + } + guard let entry = keywords.first(where: { $0.hasPrefix("events:") }) else { + return nil + } + let json = String(entry.dropFirst("events:".count)) + guard let data = json.data(using: .utf8), + let arr = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] + else { return nil } + // "Still held at export time" notes carry off: null. Take + // them as "held until the latest released-note's release" + // so the sustain matches what the user actually held until + // they grabbed the drag. Falls back to on + 0.5s when no + // other note has a release timestamp to anchor against. + let maxRelease = arr.compactMap { $0["off"] as? Double }.max() ?? 0 + return arr.compactMap { dict -> PlaybackEvent? in + guard let m = dict["midi"] as? Int, + let on = dict["on"] as? Double else { return nil } + let off: Double + if let explicit = dict["off"] as? Double { + off = explicit + } else { + off = max(maxRelease, on + 0.5) + } + return PlaybackEvent(midi: UInt8(max(0, min(127, m))), + on: on, off: off) + } + } + /// Decode Verovio's base64-encoded MIDI rendering into a temp /// `.mid` file and play it through `MidiFilePlayer` so each /// note onset/release fires the same `startTapNote` / @@ -438,6 +630,98 @@ final class SheetMusicView: NSView, WKNavigationDelegate, WKScriptMessageHandler } } + /// Pull the MusicXML payload out of a Menu Band PDF. + /// Modern format: `documentAttributes[.subjectAttribute]` carries + /// the XML directly. Legacy format (early prototypes): the XML + /// was written under a custom `/MenuBandMusicXML` key — PDFKit + /// serialized those incorrectly so PDFDocument can't read them + /// back, but the bytes ARE in the file. As a fallback we scan + /// the raw PDF for the legacy parenthesis-string form. Returns + /// nil if neither form yields a non-empty payload that looks + /// like MusicXML. + private static func extractMusicXML(from url: URL) -> String? { + // Modern path: standard /Subject Info field. + if let pdf = PDFDocument(url: url), + let attrs = pdf.documentAttributes, + let subject = attrs[PDFDocumentAttribute.subjectAttribute] as? String, + subject.contains("score-partwise") || subject.contains("...) /Title (...) ... + // We find the literal "(MenuBandMusicXML)", skip whitespace + // + the next "(" that opens the value, then collect until + // the matching ")" — handling escaped \( and \) along the way. + guard let data = try? Data(contentsOf: url) else { return nil } + guard let needle = "(MenuBandMusicXML)".data(using: .ascii), + let needleRange = data.range(of: needle) else { return nil } + + // Walk forward looking for the opening '(' of the value. + var i = needleRange.upperBound + while i < data.count, data[i] == 0x20 || data[i] == 0x0A + || data[i] == 0x0D || data[i] == 0x09 { + i += 1 + } + guard i < data.count, data[i] == UInt8(ascii: "(") else { return nil } + i += 1 + let valueStart = i + + // Collect bytes until we hit the matching unescaped ')'. + // PDF strings allow \\, \(, \) escapes plus nested balanced + // parens (rare in practice). Track depth defensively. + var depth = 1 + var bytes: [UInt8] = [] + while i < data.count { + let b = data[i] + if b == UInt8(ascii: "\\") && i + 1 < data.count { + let next = data[i + 1] + // PDF string escapes: \n \r \t \b \f \( \) \\ + octal + switch next { + case UInt8(ascii: "n"): bytes.append(0x0A) + case UInt8(ascii: "r"): bytes.append(0x0D) + case UInt8(ascii: "t"): bytes.append(0x09) + case UInt8(ascii: "b"): bytes.append(0x08) + case UInt8(ascii: "f"): bytes.append(0x0C) + case UInt8(ascii: "("), UInt8(ascii: ")"), UInt8(ascii: "\\"): + bytes.append(next) + default: + // Octal escape \ddd — collect up to 3 octal digits. + if next >= UInt8(ascii: "0") && next <= UInt8(ascii: "7") { + var octal = 0 + var consumed = 0 + var j = i + 1 + while j < data.count, consumed < 3, + data[j] >= UInt8(ascii: "0"), + data[j] <= UInt8(ascii: "7") { + octal = octal * 8 + Int(data[j] - UInt8(ascii: "0")) + j += 1 + consumed += 1 + } + bytes.append(UInt8(octal & 0xFF)) + i = j + continue + } + // Unknown escape → drop the backslash, keep next. + bytes.append(next) + } + i += 2 + continue + } + if b == UInt8(ascii: "(") { depth += 1 } + if b == UInt8(ascii: ")") { + depth -= 1 + if depth == 0 { break } + } + bytes.append(b) + i += 1 + } + _ = valueStart + guard !bytes.isEmpty else { return nil } + return String(data: Data(bytes), encoding: .utf8) + } + private func acceptablePDFURL(from sender: NSDraggingInfo) -> URL? { guard let urls = sender.draggingPasteboard.readObjects( forClasses: [NSURL.self], @@ -533,12 +817,39 @@ final class SheetMusicView: NSView, WKNavigationDelegate, WKScriptMessageHandler // MARK: - Public API (called by MenuBandPopover) + // FIXME(timing/octaves): playback fidelity is still rough. + // + // Today's flow records each onset as a quarter (or whatever + // `durationOf` rounds it to) and Verovio's renderToMIDI replays + // them sequentially at 120 BPM. Two visible failures: + // + // • Sparse playing → notes back-to-back during playback, so + // a slow performance plays back fast. + // • Verovio's MIDI octaves can drift from what the user + // played (under investigation — see MidiFilePlayer log). + // + // Planned fix (jas, 2026-05-09): anchor the score timeline to + // the FIRST note onset, start a measure timer (4/4, default + // 120 BPM unless metronome is active), quantize all subsequent + // onsets to a 16th-note grid, and run a sliding 15-second + // buffer (~7.5 measures at 120 BPM = roughly one staff page). + // The MusicXML then carries a `` directive + // so Verovio's renderToMIDI replays at the same tempo the user + // performed at, with rests preserving inter-note silences. func recordNote(pitch: UInt8) { - send("Sheet.noteOn(\(pitch))") + // Capture wall-clock at the moment Swift sees the input, + // not when the JS bridge delivers our message. The bridge + // latency is variable (5–50ms) — without an explicit time + // every recorded onset jitters by that amount and replay + // sounds sloppy. + let t = CACurrentMediaTime() + NSLog("SheetMusicView: recordNote midi=\(pitch) t=\(String(format: "%.4f", t))") + send("Sheet.noteOn(\(pitch), \(t))") } func releaseNote(pitch: UInt8) { - send("Sheet.noteOff(\(pitch))") + let t = CACurrentMediaTime() + send("Sheet.noteOff(\(pitch), \(t))") } /// Forward a metronome beat both to the JS layer (so it can -- knotmirror 0.0.1