Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d6875da2cb | |||
| 5e6534a615 | |||
| 9ec92277de | |||
| 90dc00f323 | |||
| 8eb64f883f | |||
| 62b2f5dbec | |||
| 8519cabe42 | |||
| abc64df4d7 | |||
| 38d2107f64 |
@@ -60,6 +60,7 @@ These guards catch classes of regression that **`swift build` / `swift test` str
|
|||||||
**Generators**
|
**Generators**
|
||||||
- Generator protocol + DemandGenerator → `docs/protocols/generator.md`
|
- Generator protocol + DemandGenerator → `docs/protocols/generator.md`
|
||||||
- **Implementing a new Generator** → `docs/protocols/writing-generators.md` (§13 = shared helpers)
|
- **Implementing a new Generator** → `docs/protocols/writing-generators.md` (§13 = shared helpers)
|
||||||
|
- Inline custom per-sample DSP / single-sample feedback without a new Generator type (`SampleLoop` — pre-allocated output, typed `inout` feedback state, channel inference + broadcast) → `Sources/Lyrebird/Generators/Core/SampleLoop.swift`
|
||||||
- Built-in generator catalog → `docs/stdlib/generators.md`
|
- Built-in generator catalog → `docs/stdlib/generators.md`
|
||||||
- Multi-channel / `outputChannelCount` / channel-aware operators → `docs/stdlib/multichannel.md`
|
- Multi-channel / `outputChannelCount` / channel-aware operators → `docs/stdlib/multichannel.md`
|
||||||
- Musical math (MIDI↔Hz, dB, intervals) → `docs/stdlib/generators.md` (LyrebirdMusicMath section)
|
- Musical math (MIDI↔Hz, dB, intervals) → `docs/stdlib/generators.md` (LyrebirdMusicMath section)
|
||||||
@@ -92,9 +93,11 @@ These guards catch classes of regression that **`swift build` / `swift test` str
|
|||||||
**UI**
|
**UI**
|
||||||
- LyrebirdUI / parameter binding → `docs/ui/gui-system.md`
|
- LyrebirdUI / parameter binding → `docs/ui/gui-system.md`
|
||||||
- Live-compile scratchpad (`LyrebirdScratchView`, `LyrebirdLiveCompile`, `LyrebirdLiveCompileUI`) → `LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md`. **Lives in the separate `LiveCompile/` SwiftPM sub-package** (Phase 167) — cross-package dependency forces `libLyrebirdLiveCompile.dylib` to dynamic-link `libLyrebird.dylib` instead of statically embedding it, eliminating the ObjC class double-registration crash that aborted full `swift test` runs in the single-package layout. Build sub-package with `(cd LiveCompile && swift build)` / `(cd LiveCompile && swift test)`.
|
- Live-compile scratchpad (`LyrebirdScratchView`, `LyrebirdLiveCompile`, `LyrebirdLiveCompileUI`) → `LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md`. **Lives in the separate `LiveCompile/` SwiftPM sub-package** (Phase 167) — cross-package dependency forces `libLyrebirdLiveCompile.dylib` to dynamic-link `libLyrebird.dylib` instead of statically embedding it, eliminating the ObjC class double-registration crash that aborted full `swift test` runs in the single-package layout. Build sub-package with `(cd LiveCompile && swift build)` / `(cd LiveCompile && swift test)`.
|
||||||
|
- Interpreted graph-DSL (`LyrebirdGraphDSL` target — cross-platform, no swiftc) + its code-gen (`Tools/DSLRegistryGen`, separate SwiftPM package so swift-syntax stays out of the main build; run `scripts/generate-dsl-registry.sh`, committed output, `--check` drift guard) → `docs/tooling/graph-dsl-design.md`. Registry (`Sources/LyrebirdGraphDSL/Generated/GeneratedDSLRegistry.swift`) is generated from generator init signatures — regenerate + commit after changing a public generator init. In progress (LC-8); language/parser not yet built.
|
||||||
|
|
||||||
**Diagnostics**
|
**Diagnostics**
|
||||||
- User-visible messages (`LyrebirdMessage`, `LyrebirdMessageCenter`, `LyrebirdMessageView` / Banner) + node-tree mirror (`NodeTreeMirror`, `NodeTreeSnapshot`, `LyrebirdNodeTreeView`) → `docs/diagnostics-guide.md`
|
- User-visible messages (`LyrebirdMessage`, `LyrebirdMessageCenter`, `LyrebirdMessageView` / Banner) + node-tree mirror (`NodeTreeMirror`, `NodeTreeSnapshot`, `LyrebirdNodeTreeView`) → `docs/diagnostics-guide.md`
|
||||||
|
- Developer-side debugging (per-instance RT debug tap `SynthesizerBase.debugTap`, `GeneratorBase.debugTag`, LLDB breakpoint recipes for inspecting a live voice / generator) → `Sources/Lyrebird/Lyrebird.docc/Debugging.md`
|
||||||
|
|
||||||
**Planning**
|
**Planning**
|
||||||
- What to build next → `docs/00-working-order.md`
|
- What to build next → `docs/00-working-order.md`
|
||||||
|
|||||||
@@ -11,30 +11,11 @@
|
|||||||
C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; };
|
C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; };
|
||||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; };
|
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; };
|
||||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
|
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
|
||||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
|
||||||
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||||
|
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||||
|
C8D00000000000000000041 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000040 /* Assets.xcassets */; };
|
||||||
/* End PBXBuildFile section */
|
/* End PBXBuildFile section */
|
||||||
|
|
||||||
/* Begin PBXFileReference section */
|
|
||||||
C8D00000000000000000004 /* LyrebirdScratchDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdScratchDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
|
||||||
C8D00000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
|
||||||
C8D00000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
|
||||||
C8D00000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
|
||||||
C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratchDemo.entitlements; sourceTree = "<group>"; };
|
|
||||||
/* End PBXFileReference section */
|
|
||||||
|
|
||||||
/* Begin PBXFrameworksBuildPhase section */
|
|
||||||
C8D00000000000000000012 /* Frameworks */ = {
|
|
||||||
isa = PBXFrameworksBuildPhase;
|
|
||||||
buildActionMask = 2147483647;
|
|
||||||
files = (
|
|
||||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
|
|
||||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
|
|
||||||
);
|
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
|
||||||
};
|
|
||||||
/* End PBXFrameworksBuildPhase section */
|
|
||||||
|
|
||||||
/* Begin PBXCopyFilesBuildPhase section */
|
/* Begin PBXCopyFilesBuildPhase section */
|
||||||
C8D00000000000000000035 /* Embed Frameworks */ = {
|
C8D00000000000000000035 /* Embed Frameworks */ = {
|
||||||
isa = PBXCopyFilesBuildPhase;
|
isa = PBXCopyFilesBuildPhase;
|
||||||
@@ -50,11 +31,32 @@
|
|||||||
};
|
};
|
||||||
/* End PBXCopyFilesBuildPhase section */
|
/* End PBXCopyFilesBuildPhase section */
|
||||||
|
|
||||||
|
/* Begin PBXFileReference section */
|
||||||
|
C8D00000000000000000004 /* LyrebirdScratch.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdScratch.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
|
C8D00000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||||
|
C8D00000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||||
|
C8D00000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||||
|
C8D00000000000000000009 /* LyrebirdScratch.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratch.entitlements; sourceTree = "<group>"; };
|
||||||
|
C8D00000000000000000040 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||||
|
/* End PBXFileReference section */
|
||||||
|
|
||||||
|
/* Begin PBXFrameworksBuildPhase section */
|
||||||
|
C8D00000000000000000012 /* Frameworks */ = {
|
||||||
|
isa = PBXFrameworksBuildPhase;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
|
||||||
|
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
};
|
||||||
|
/* End PBXFrameworksBuildPhase section */
|
||||||
|
|
||||||
/* Begin PBXGroup section */
|
/* Begin PBXGroup section */
|
||||||
C8D00000000000000000002 = {
|
C8D00000000000000000002 = {
|
||||||
isa = PBXGroup;
|
isa = PBXGroup;
|
||||||
children = (
|
children = (
|
||||||
C8D00000000000000000005 /* LyrebirdScratchDemo */,
|
C8D00000000000000000005 /* LyrebirdScratch */,
|
||||||
C8D00000000000000000003 /* Products */,
|
C8D00000000000000000003 /* Products */,
|
||||||
);
|
);
|
||||||
sourceTree = "<group>";
|
sourceTree = "<group>";
|
||||||
@@ -62,45 +64,47 @@
|
|||||||
C8D00000000000000000003 /* Products */ = {
|
C8D00000000000000000003 /* Products */ = {
|
||||||
isa = PBXGroup;
|
isa = PBXGroup;
|
||||||
children = (
|
children = (
|
||||||
C8D00000000000000000004 /* LyrebirdScratchDemo.app */,
|
C8D00000000000000000004 /* LyrebirdScratch.app */,
|
||||||
);
|
);
|
||||||
name = Products;
|
name = Products;
|
||||||
sourceTree = "<group>";
|
sourceTree = "<group>";
|
||||||
};
|
};
|
||||||
C8D00000000000000000005 /* LyrebirdScratchDemo */ = {
|
C8D00000000000000000005 /* LyrebirdScratch */ = {
|
||||||
isa = PBXGroup;
|
isa = PBXGroup;
|
||||||
children = (
|
children = (
|
||||||
C8D00000000000000000007 /* main.swift */,
|
C8D00000000000000000007 /* main.swift */,
|
||||||
C8D00000000000000000008 /* AppDelegate.swift */,
|
C8D00000000000000000008 /* AppDelegate.swift */,
|
||||||
C8D00000000000000000006 /* Info.plist */,
|
C8D00000000000000000006 /* Info.plist */,
|
||||||
C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */,
|
C8D00000000000000000009 /* LyrebirdScratch.entitlements */,
|
||||||
|
C8D00000000000000000040 /* Assets.xcassets */,
|
||||||
);
|
);
|
||||||
path = LyrebirdScratchDemo;
|
path = LyrebirdScratch;
|
||||||
sourceTree = "<group>";
|
sourceTree = "<group>";
|
||||||
};
|
};
|
||||||
/* End PBXGroup section */
|
/* End PBXGroup section */
|
||||||
|
|
||||||
/* Begin PBXNativeTarget section */
|
/* Begin PBXNativeTarget section */
|
||||||
C8D00000000000000000014 /* LyrebirdScratchDemo */ = {
|
C8D00000000000000000014 /* LyrebirdScratch */ = {
|
||||||
isa = PBXNativeTarget;
|
isa = PBXNativeTarget;
|
||||||
buildConfigurationList = C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */;
|
buildConfigurationList = C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratch" */;
|
||||||
buildPhases = (
|
buildPhases = (
|
||||||
C8D00000000000000000011 /* Sources */,
|
C8D00000000000000000011 /* Sources */,
|
||||||
C8D00000000000000000012 /* Frameworks */,
|
C8D00000000000000000012 /* Frameworks */,
|
||||||
C8D00000000000000000013 /* Resources */,
|
C8D00000000000000000013 /* Resources */,
|
||||||
C8D00000000000000000035 /* Embed Frameworks */,
|
C8D00000000000000000035 /* Embed Frameworks */,
|
||||||
|
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */,
|
||||||
);
|
);
|
||||||
buildRules = (
|
buildRules = (
|
||||||
);
|
);
|
||||||
dependencies = (
|
dependencies = (
|
||||||
);
|
);
|
||||||
name = LyrebirdScratchDemo;
|
name = LyrebirdScratch;
|
||||||
packageProductDependencies = (
|
packageProductDependencies = (
|
||||||
C8D0000000000000000001D /* LyrebirdDynamic */,
|
C8D0000000000000000001D /* LyrebirdDynamic */,
|
||||||
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */,
|
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */,
|
||||||
);
|
);
|
||||||
productName = LyrebirdScratchDemo;
|
productName = LyrebirdScratch;
|
||||||
productReference = C8D00000000000000000004 /* LyrebirdScratchDemo.app */;
|
productReference = C8D00000000000000000004 /* LyrebirdScratch.app */;
|
||||||
productType = "com.apple.product-type.application";
|
productType = "com.apple.product-type.application";
|
||||||
};
|
};
|
||||||
/* End PBXNativeTarget section */
|
/* End PBXNativeTarget section */
|
||||||
@@ -111,14 +115,14 @@
|
|||||||
attributes = {
|
attributes = {
|
||||||
BuildIndependentTargetsInParallel = 1;
|
BuildIndependentTargetsInParallel = 1;
|
||||||
LastSwiftUpdateCheck = 1600;
|
LastSwiftUpdateCheck = 1600;
|
||||||
LastUpgradeCheck = 2620;
|
LastUpgradeCheck = 2660;
|
||||||
TargetAttributes = {
|
TargetAttributes = {
|
||||||
C8D00000000000000000014 = {
|
C8D00000000000000000014 = {
|
||||||
CreatedOnToolsVersion = 16.0;
|
CreatedOnToolsVersion = 16.0;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
buildConfigurationList = C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */;
|
buildConfigurationList = C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratch" */;
|
||||||
compatibilityVersion = "Xcode 14.0";
|
compatibilityVersion = "Xcode 14.0";
|
||||||
developmentRegion = en;
|
developmentRegion = en;
|
||||||
hasScannedForEncodings = 0;
|
hasScannedForEncodings = 0;
|
||||||
@@ -135,7 +139,7 @@
|
|||||||
projectDirPath = "";
|
projectDirPath = "";
|
||||||
projectRoot = "";
|
projectRoot = "";
|
||||||
targets = (
|
targets = (
|
||||||
C8D00000000000000000014 /* LyrebirdScratchDemo */,
|
C8D00000000000000000014 /* LyrebirdScratch */,
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
/* End PBXProject section */
|
/* End PBXProject section */
|
||||||
@@ -145,11 +149,30 @@
|
|||||||
isa = PBXResourcesBuildPhase;
|
isa = PBXResourcesBuildPhase;
|
||||||
buildActionMask = 2147483647;
|
buildActionMask = 2147483647;
|
||||||
files = (
|
files = (
|
||||||
|
C8D00000000000000000041 /* Assets.xcassets in Resources */,
|
||||||
);
|
);
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
};
|
};
|
||||||
/* End PBXResourcesBuildPhase section */
|
/* End PBXResourcesBuildPhase section */
|
||||||
|
|
||||||
|
/* Begin PBXShellScriptBuildPhase section */
|
||||||
|
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */ = {
|
||||||
|
isa = PBXShellScriptBuildPhase;
|
||||||
|
alwaysOutOfDate = 1;
|
||||||
|
buildActionMask = 2147483647;
|
||||||
|
files = (
|
||||||
|
);
|
||||||
|
inputPaths = (
|
||||||
|
);
|
||||||
|
name = "Bundle Lyrebird swiftmodules";
|
||||||
|
outputPaths = (
|
||||||
|
);
|
||||||
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
|
shellPath = /bin/sh;
|
||||||
|
shellScript = "# Bundle the Lyrebird module artifacts into the app so the live-compile scratchpad\n# can `import LyrebirdSynth` / `import LyrebirdLiveCompile` on any machine — they\n# otherwise resolve only from BUILT_PRODUCTS_DIR / the dev source tree, both absent\n# once the .app is exported. LiveSession stages Contents/Resources/LyrebirdArtifacts\n# at launch; artifactSourceDir() / discoverSPMModuleMaps() then find them.\nset -e\nART=\"${TARGET_BUILD_DIR}/${CONTENTS_FOLDER_PATH}/Resources/LyrebirdArtifacts\"\nDEST=\"${ART}/Modules\"\n/bin/rm -rf \"${ART}\"\n/bin/mkdir -p \"${DEST}\"\n# 1. Swift module interfaces the snippet imports (+ their transitive deps).\nfor m in LyrebirdSynth LyrebirdLiveCompile LyrebirdLiveCompileUI LyrebirdGraphDSLEmbedded; do\n SRC=\"${BUILT_PRODUCTS_DIR}/${m}.swiftmodule\"\n if [ -e \"${SRC}\" ]; then /bin/cp -R \"${SRC}\" \"${DEST}/\"; fi\ndone\n# 2. LyrebirdC C-shim Clang module (LyrebirdSynth depends on it; a snippet importing\n# LyrebirdSynth needs its module map + header). The SPM source map uses a header path\n# relative to the map dir, so map + include/ copied together stay self-contained and\n# relocatable — placed at LyrebirdArtifacts/LyrebirdC.build so discoverSPMModuleMaps()\n# finds it once staged.\nCSRC=\"${SRCROOT}/../../Sources/LyrebirdC\"\nif [ -f \"${CSRC}/module.modulemap\" ]; then\n CDEST=\"${ART}/LyrebirdC.build\"\n /bin/mkdir -p \"${CDEST}\"\n /bin/cp \"${CSRC}/module.modulemap\" \"${CDEST}/\"\n [ -d \"${CSRC}/include\" ] && /bin/cp -R \"${CSRC}/include\" \"${CDEST}/\"\nfi\necho \"Bundled Lyrebird modules + LyrebirdC shim into ${ART}\"\n";
|
||||||
|
};
|
||||||
|
/* End PBXShellScriptBuildPhase section */
|
||||||
|
|
||||||
/* Begin PBXSourcesBuildPhase section */
|
/* Begin PBXSourcesBuildPhase section */
|
||||||
C8D00000000000000000011 /* Sources */ = {
|
C8D00000000000000000011 /* Sources */ = {
|
||||||
isa = PBXSourcesBuildPhase;
|
isa = PBXSourcesBuildPhase;
|
||||||
@@ -166,19 +189,40 @@
|
|||||||
C8D00000000000000000016 /* Debug */ = {
|
C8D00000000000000000016 /* Debug */ = {
|
||||||
isa = XCBuildConfiguration;
|
isa = XCBuildConfiguration;
|
||||||
buildSettings = {
|
buildSettings = {
|
||||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements;
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
|
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||||
|
AUTOMATION_APPLE_EVENTS = NO;
|
||||||
|
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
||||||
|
CODE_SIGN_IDENTITY = "Apple Development";
|
||||||
|
CODE_SIGN_STYLE = Automatic;
|
||||||
COMBINE_HIDPI_IMAGES = YES;
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
|
CURRENT_PROJECT_VERSION = 2;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
ENABLE_HARDENED_RUNTIME = YES;
|
||||||
INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist;
|
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||||
|
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
|
||||||
|
ENABLE_RESOURCE_ACCESS_CAMERA = NO;
|
||||||
|
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
||||||
|
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
||||||
|
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||||
|
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||||
|
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||||
LD_RUNPATH_SEARCH_PATHS = (
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"@executable_path/../Frameworks",
|
"@executable_path/../Frameworks",
|
||||||
);
|
);
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo;
|
MARKETING_VERSION = 1.6.2;
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
|
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||||
|
RUNTIME_EXCEPTION_ALLOW_DYLD_ENVIRONMENT_VARIABLES = NO;
|
||||||
|
RUNTIME_EXCEPTION_ALLOW_JIT = NO;
|
||||||
|
RUNTIME_EXCEPTION_ALLOW_UNSIGNED_EXECUTABLE_MEMORY = NO;
|
||||||
|
RUNTIME_EXCEPTION_DEBUGGING_TOOL = NO;
|
||||||
|
RUNTIME_EXCEPTION_DISABLE_EXECUTABLE_PAGE_PROTECTION = NO;
|
||||||
|
RUNTIME_EXCEPTION_DISABLE_LIBRARY_VALIDATION = NO;
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||||
SWIFT_VERSION = 5.0;
|
SWIFT_VERSION = 5.0;
|
||||||
};
|
};
|
||||||
@@ -187,18 +231,39 @@
|
|||||||
C8D00000000000000000017 /* Release */ = {
|
C8D00000000000000000017 /* Release */ = {
|
||||||
isa = XCBuildConfiguration;
|
isa = XCBuildConfiguration;
|
||||||
buildSettings = {
|
buildSettings = {
|
||||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements;
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
|
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||||
|
AUTOMATION_APPLE_EVENTS = NO;
|
||||||
|
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
||||||
|
CODE_SIGN_IDENTITY = "Apple Development";
|
||||||
|
CODE_SIGN_STYLE = Automatic;
|
||||||
COMBINE_HIDPI_IMAGES = YES;
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
|
CURRENT_PROJECT_VERSION = 2;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
ENABLE_HARDENED_RUNTIME = YES;
|
||||||
INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist;
|
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||||
|
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
|
||||||
|
ENABLE_RESOURCE_ACCESS_CAMERA = NO;
|
||||||
|
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
||||||
|
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
||||||
|
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||||
|
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||||
|
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||||
LD_RUNPATH_SEARCH_PATHS = (
|
LD_RUNPATH_SEARCH_PATHS = (
|
||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"@executable_path/../Frameworks",
|
"@executable_path/../Frameworks",
|
||||||
);
|
);
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo;
|
MARKETING_VERSION = 1.6.2;
|
||||||
|
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
|
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||||
|
RUNTIME_EXCEPTION_ALLOW_DYLD_ENVIRONMENT_VARIABLES = NO;
|
||||||
|
RUNTIME_EXCEPTION_ALLOW_JIT = NO;
|
||||||
|
RUNTIME_EXCEPTION_ALLOW_UNSIGNED_EXECUTABLE_MEMORY = NO;
|
||||||
|
RUNTIME_EXCEPTION_DEBUGGING_TOOL = NO;
|
||||||
|
RUNTIME_EXCEPTION_DISABLE_EXECUTABLE_PAGE_PROTECTION = NO;
|
||||||
|
RUNTIME_EXCEPTION_DISABLE_LIBRARY_VALIDATION = NO;
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||||
SWIFT_VERSION = 5.0;
|
SWIFT_VERSION = 5.0;
|
||||||
};
|
};
|
||||||
@@ -239,6 +304,7 @@
|
|||||||
COPY_PHASE_STRIP = NO;
|
COPY_PHASE_STRIP = NO;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||||
|
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||||
ENABLE_TESTABILITY = YES;
|
ENABLE_TESTABILITY = YES;
|
||||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||||
@@ -263,9 +329,6 @@
|
|||||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||||
// Xcode 26 explicit-module-build regression: SPM dynamic-library
|
|
||||||
// framework binaries (LyrebirdDynamic / LyrebirdLiveCompileUIDynamic)
|
|
||||||
// are not emitted under the integrated driver. Classic driver fixes it.
|
|
||||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||||
};
|
};
|
||||||
name = Debug;
|
name = Debug;
|
||||||
@@ -305,6 +368,7 @@
|
|||||||
COPY_PHASE_STRIP = NO;
|
COPY_PHASE_STRIP = NO;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||||
|
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||||
ENABLE_NS_ASSERTIONS = NO;
|
ENABLE_NS_ASSERTIONS = NO;
|
||||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||||
@@ -322,7 +386,6 @@
|
|||||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||||
SWIFT_COMPILATION_MODE = wholemodule;
|
SWIFT_COMPILATION_MODE = wholemodule;
|
||||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||||
// Xcode 26 explicit-module-build regression — see Debug config.
|
|
||||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||||
};
|
};
|
||||||
name = Release;
|
name = Release;
|
||||||
@@ -330,7 +393,7 @@
|
|||||||
/* End XCBuildConfiguration section */
|
/* End XCBuildConfiguration section */
|
||||||
|
|
||||||
/* Begin XCConfigurationList section */
|
/* Begin XCConfigurationList section */
|
||||||
C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */ = {
|
C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratch" */ = {
|
||||||
isa = XCConfigurationList;
|
isa = XCConfigurationList;
|
||||||
buildConfigurations = (
|
buildConfigurations = (
|
||||||
C8D00000000000000000016 /* Debug */,
|
C8D00000000000000000016 /* Debug */,
|
||||||
@@ -339,7 +402,7 @@
|
|||||||
defaultConfigurationIsVisible = 0;
|
defaultConfigurationIsVisible = 0;
|
||||||
defaultConfigurationName = Release;
|
defaultConfigurationName = Release;
|
||||||
};
|
};
|
||||||
C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */ = {
|
C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratch" */ = {
|
||||||
isa = XCConfigurationList;
|
isa = XCConfigurationList;
|
||||||
buildConfigurations = (
|
buildConfigurations = (
|
||||||
C8D00000000000000000019 /* Debug */,
|
C8D00000000000000000019 /* Debug */,
|
||||||
@@ -16,9 +16,9 @@
|
|||||||
<BuildableReference
|
<BuildableReference
|
||||||
BuildableIdentifier = "primary"
|
BuildableIdentifier = "primary"
|
||||||
BlueprintIdentifier = "C8D00000000000000000014"
|
BlueprintIdentifier = "C8D00000000000000000014"
|
||||||
BuildableName = "LyrebirdScratchDemo.app"
|
BuildableName = "LyrebirdScratch.app"
|
||||||
BlueprintName = "LyrebirdScratchDemo"
|
BlueprintName = "LyrebirdScratch"
|
||||||
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
|
ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
|
||||||
</BuildableReference>
|
</BuildableReference>
|
||||||
</BuildActionEntry>
|
</BuildActionEntry>
|
||||||
</BuildActionEntries>
|
</BuildActionEntries>
|
||||||
@@ -31,7 +31,7 @@
|
|||||||
shouldAutocreateTestPlan = "YES">
|
shouldAutocreateTestPlan = "YES">
|
||||||
</TestAction>
|
</TestAction>
|
||||||
<LaunchAction
|
<LaunchAction
|
||||||
buildConfiguration = "Debug"
|
buildConfiguration = "Release"
|
||||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||||
launchStyle = "0"
|
launchStyle = "0"
|
||||||
@@ -45,9 +45,9 @@
|
|||||||
<BuildableReference
|
<BuildableReference
|
||||||
BuildableIdentifier = "primary"
|
BuildableIdentifier = "primary"
|
||||||
BlueprintIdentifier = "C8D00000000000000000014"
|
BlueprintIdentifier = "C8D00000000000000000014"
|
||||||
BuildableName = "LyrebirdScratchDemo.app"
|
BuildableName = "LyrebirdScratch.app"
|
||||||
BlueprintName = "LyrebirdScratchDemo"
|
BlueprintName = "LyrebirdScratch"
|
||||||
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
|
ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
|
||||||
</BuildableReference>
|
</BuildableReference>
|
||||||
</BuildableProductRunnable>
|
</BuildableProductRunnable>
|
||||||
</LaunchAction>
|
</LaunchAction>
|
||||||
@@ -62,9 +62,9 @@
|
|||||||
<BuildableReference
|
<BuildableReference
|
||||||
BuildableIdentifier = "primary"
|
BuildableIdentifier = "primary"
|
||||||
BlueprintIdentifier = "C8D00000000000000000014"
|
BlueprintIdentifier = "C8D00000000000000000014"
|
||||||
BuildableName = "LyrebirdScratchDemo.app"
|
BuildableName = "LyrebirdScratch.app"
|
||||||
BlueprintName = "LyrebirdScratchDemo"
|
BlueprintName = "LyrebirdScratch"
|
||||||
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
|
ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
|
||||||
</BuildableReference>
|
</BuildableReference>
|
||||||
</BuildableProductRunnable>
|
</BuildableProductRunnable>
|
||||||
</ProfileAction>
|
</ProfileAction>
|
||||||
@@ -20,6 +20,21 @@ import LyrebirdLiveCompileUI
|
|||||||
// this demo used was `LyrebirdWindow`, an `NSWindow`/`NSHostingController`
|
// this demo used was `LyrebirdWindow`, an `NSWindow`/`NSHostingController`
|
||||||
// wrapper with no `LyrebirdSynth` dependency — inlined below instead.
|
// wrapper with no `LyrebirdSynth` dependency — inlined below instead.
|
||||||
|
|
||||||
|
// Entitlements / signing posture (rationale kept here because Xcode strips
|
||||||
|
// comments from `LyrebirdScratch.entitlements` on every project resave):
|
||||||
|
//
|
||||||
|
// • App Sandbox is intentionally OFF. Live-compile shells out to `swiftc`
|
||||||
|
// (`posix_spawn`, disallowed under the sandbox) and `dlopen`s the resulting
|
||||||
|
// UNSIGNED snippet dylib (rejected by the sandbox). This is a direct-
|
||||||
|
// distribution developer tool, not a Mac App Store app; sandbox-off is the
|
||||||
|
// only viable configuration. (An XPC-worker split could revisit this.)
|
||||||
|
// • Hardened Runtime is ON, so the entitlement
|
||||||
|
// `com.apple.security.cs.disable-library-validation = true` is REQUIRED —
|
||||||
|
// without it dyld rejects `dlopen` of the unsigned, non-team-signed snippet
|
||||||
|
// dylib ("code signing blocked mmap()").
|
||||||
|
//
|
||||||
|
// Do not remove that entitlement or the app can't load compiled snippets.
|
||||||
|
|
||||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||||
|
|
||||||
let engine: SynthesisEngine
|
let engine: SynthesisEngine
|
||||||
@@ -31,6 +46,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
@MainActor
|
@MainActor
|
||||||
init(engine: SynthesisEngine) {
|
init(engine: SynthesisEngine) {
|
||||||
self.engine = engine
|
self.engine = engine
|
||||||
|
// Stage the Lyrebird compile artifacts into ~/Library/Application Support
|
||||||
|
// (ungated) before the session reads its default -I/-L/rpath. Without
|
||||||
|
// this the snippet compiler points swiftc at the SPM build dir under
|
||||||
|
// ~/Documents, tripping the macOS Documents-folder permission gate.
|
||||||
|
// Best-effort: if staging fails the session falls back to the build dir.
|
||||||
|
LiveSession.stageArtifacts()
|
||||||
self.session = LiveSession(engine: engine)
|
self.session = LiveSession(engine: engine)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,7 +60,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
do {
|
do {
|
||||||
try engine.start()
|
try engine.start()
|
||||||
} catch {
|
} catch {
|
||||||
print("[LyrebirdScratchDemo] Engine failed to start: \(error)")
|
print("[LyrebirdScratch] Engine failed to start: \(error)")
|
||||||
}
|
}
|
||||||
|
|
||||||
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session)
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session)
|
||||||
@@ -48,13 +69,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
menuController.installMainMenu()
|
menuController.installMainMenu()
|
||||||
self.menuController = menuController
|
self.menuController = menuController
|
||||||
|
|
||||||
let windowWidth: CGFloat = 720
|
|
||||||
let windowHeight: CGFloat = 560
|
|
||||||
let hosting: NSHostingController<LyrebirdScratchView> =
|
let hosting: NSHostingController<LyrebirdScratchView> =
|
||||||
NSHostingController(rootView: LyrebirdScratchView(model: model))
|
NSHostingController(rootView: LyrebirdScratchView(model: model))
|
||||||
let initialSize: CGSize = CGSize(width: windowWidth, height: windowHeight)
|
|
||||||
let win: NSWindow = NSWindow(
|
let win: NSWindow = NSWindow(
|
||||||
contentRect: NSRect(origin: .zero, size: initialSize),
|
contentRect: NSRect(origin: .zero, size: CGSize(width: 720, height: 560)),
|
||||||
styleMask: [.titled, .closable, .resizable, .miniaturizable],
|
styleMask: [.titled, .closable, .resizable, .miniaturizable],
|
||||||
backing: .buffered,
|
backing: .buffered,
|
||||||
defer: false
|
defer: false
|
||||||
@@ -63,7 +81,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
win.isReleasedWhenClosed = false
|
win.isReleasedWhenClosed = false
|
||||||
win.title = "Lyrebird — Live Scratch"
|
win.title = "Lyrebird — Live Scratch"
|
||||||
win.contentViewController = hosting
|
win.contentViewController = hosting
|
||||||
win.center()
|
// Base geometry: three-quarters of the screen wide, three-quarters tall,
|
||||||
|
// anchored to the left edge and vertically centered in the visible area
|
||||||
|
// (below the menu bar, above the Dock).
|
||||||
|
let visible: NSRect = (win.screen ?? NSScreen.main)?.visibleFrame
|
||||||
|
?? NSRect(x: 0, y: 0, width: 1440, height: 900)
|
||||||
|
let width: CGFloat = visible.width * 0.75
|
||||||
|
let height: CGFloat = visible.height * 0.75
|
||||||
|
let originX: CGFloat = visible.minX
|
||||||
|
let originY: CGFloat = visible.minY + (visible.height - height) / 2
|
||||||
|
win.setFrame(NSRect(x: originX, y: originY, width: width, height: height), display: true)
|
||||||
win.makeKeyAndOrderFront(nil)
|
win.makeKeyAndOrderFront(nil)
|
||||||
self.window = win
|
self.window = win
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{ "idiom" : "mac", "scale" : "1x", "size" : "16x16", "filename" : "icon_16.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "2x", "size" : "16x16", "filename" : "icon_32.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "1x", "size" : "32x32", "filename" : "icon_32.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "2x", "size" : "32x32", "filename" : "icon_64.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "1x", "size" : "128x128", "filename" : "icon_128.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "2x", "size" : "128x128", "filename" : "icon_256.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "1x", "size" : "256x256", "filename" : "icon_256.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "2x", "size" : "256x256", "filename" : "icon_512.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "1x", "size" : "512x512", "filename" : "icon_512.png" },
|
||||||
|
{ "idiom" : "mac", "scale" : "2x", "size" : "512x512", "filename" : "icon_1024.png" }
|
||||||
|
],
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 338 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 720 B |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"info" : { "author" : "xcode", "version" : 1 }
|
||||||
|
}
|
||||||
@@ -13,14 +13,14 @@
|
|||||||
<key>CFBundlePackageType</key>
|
<key>CFBundlePackageType</key>
|
||||||
<string>APPL</string>
|
<string>APPL</string>
|
||||||
<key>CFBundleShortVersionString</key>
|
<key>CFBundleShortVersionString</key>
|
||||||
<string>1.0</string>
|
<string>1.6.3</string>
|
||||||
<key>CFBundleVersion</key>
|
<key>CFBundleVersion</key>
|
||||||
<string>1</string>
|
<string>3</string>
|
||||||
<key>LSMinimumSystemVersion</key>
|
<key>LSMinimumSystemVersion</key>
|
||||||
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||||
<key>NSPrincipalClass</key>
|
|
||||||
<string>NSApplication</string>
|
|
||||||
<key>NSHumanReadableCopyright</key>
|
<key>NSHumanReadableCopyright</key>
|
||||||
<string>Copyright © 2026 Realized Sound. All rights reserved.</string>
|
<string>Copyright © 2026 Realized Sound. All rights reserved.</string>
|
||||||
|
<key>NSPrincipalClass</key>
|
||||||
|
<string>NSApplication</string>
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>com.apple.security.cs.disable-library-validation</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
||||||
<plist version="1.0">
|
|
||||||
<dict>
|
|
||||||
<!--
|
|
||||||
App Sandbox is intentionally OFF.
|
|
||||||
|
|
||||||
LyrebirdScratchDemo shells out to `swiftc` at runtime to compile user-
|
|
||||||
typed Swift snippets, then calls `dlopen` on the resulting unsigned dylib.
|
|
||||||
Both operations are blocked by the macOS App Sandbox:
|
|
||||||
|
|
||||||
- `posix_spawn` / `fork` for the swiftc subprocess is disallowed in a
|
|
||||||
sandboxed process (com.apple.security.temporary-exception.mach-lookup
|
|
||||||
grants exist for specific Apple tools only, not arbitrary executables).
|
|
||||||
- `dlopen` of a dylib that was not shipped with the app bundle and is
|
|
||||||
not code-signed with a matching team ID is rejected by the sandbox.
|
|
||||||
|
|
||||||
This app is a direct-distribution developer tool, not a Mac App Store
|
|
||||||
submission. Sandbox OFF is the only viable configuration for v1.
|
|
||||||
This could be revisited if an XPC-worker approach is adopted.
|
|
||||||
|
|
||||||
com.apple.security.app-sandbox key is absent (defaults false).
|
|
||||||
-->
|
|
||||||
|
|
||||||
<!--
|
|
||||||
Hardened Runtime — Disable Library Validation.
|
|
||||||
|
|
||||||
With Hardened Runtime enabled (ENABLE_HARDENED_RUNTIME = YES in the
|
|
||||||
Xcode project), `dlopen` of a dylib that was not signed with the same
|
|
||||||
Team ID as the host app is rejected by the dynamic linker.
|
|
||||||
|
|
||||||
LyrebirdScratchDemo writes snippet dylibs to a per-session temp dir
|
|
||||||
via `swiftc -emit-library`; those dylibs are unsigned (swiftc does not
|
|
||||||
sign them). The `CS_ALLOW_UNSIGNED_EXECUTABLE_MEMORY` (library-
|
|
||||||
validation disable) entitlement tells the kernel to skip the
|
|
||||||
code-signing check for loaded libraries, allowing `dlopen` to succeed.
|
|
||||||
|
|
||||||
Without this entitlement the app would crash with DYLD_PRINT_LIBRARIES
|
|
||||||
reporting: "Library not loaded: ... Reason: tried: ... no suitable image
|
|
||||||
found. Did find: ... code signing blocked mmap() of '...'"
|
|
||||||
-->
|
|
||||||
<key>com.apple.security.cs.disable-library-validation</key>
|
|
||||||
<true/>
|
|
||||||
</dict>
|
|
||||||
</plist>
|
|
||||||
@@ -368,6 +368,6 @@ The repo ships eight runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.
|
|||||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | `nrt` |
|
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | `nrt` |
|
||||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | `score` |
|
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | `score` |
|
||||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | `auv3` |
|
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | `auv3` |
|
||||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | live-coding scratchpad |
|
| [`LyrebirdScratch`](Demos/LyrebirdScratch/) | live-coding scratchpad |
|
||||||
|
|
||||||
See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for per-demo notes and gotchas.
|
See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for per-demo notes and gotchas.
|
||||||
|
|||||||
@@ -141,7 +141,7 @@ A container app + `.appex` extension target shipping **Realized Sound: LyrebirdF
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### LyrebirdScratchDemo — Live-Coding Scratchpad
|
### LyrebirdScratch — Live-Coding Scratchpad
|
||||||
|
|
||||||
A macOS app that compiles a typed Swift snippet against the live engine at ⌘↩. Backed by `LyrebirdScratchView` and `LiveSession` from the `LyrebirdLiveCompile` SPM target.
|
A macOS app that compiles a typed Swift snippet against the live engine at ⌘↩. Backed by `LyrebirdScratchView` and `LiveSession` from the `LyrebirdLiveCompile` SPM target.
|
||||||
|
|
||||||
@@ -149,13 +149,15 @@ A macOS app that compiles a typed Swift snippet against the live engine at ⌘
|
|||||||
- Type arbitrary Swift code in the editor pane. The snippet body has `context: SnippetContext` in scope.
|
- Type arbitrary Swift code in the editor pane. The snippet body has `context: SnippetContext` in scope.
|
||||||
- `context.engine` — the host `SynthesisEngine`, started at launch.
|
- `context.engine` — the host `SynthesisEngine`, started at launch.
|
||||||
- `context.play(synth)` — adds a `Synthesizer` to the engine and tracks it for cleanup.
|
- `context.play(synth)` — adds a `Synthesizer` to the engine and tracks it for cleanup.
|
||||||
|
- `context.play { <graph> }` — plays a bare generator graph, no `SynthesizerBase` subclass needed.
|
||||||
|
- `context.play(slot: "name") { <graph> }` — plays into a named slot; re-running that slot replaces just that voice in place while the rest keeps playing (persists across a ⌘↩ run).
|
||||||
- `context.reportMessage(_:)` — writes a string back to the host status bar.
|
- `context.reportMessage(_:)` — writes a string back to the host status bar.
|
||||||
- **⌘↩** — compile and replace. Removes synths from the previous run, compiles the snippet via `swiftc -emit-library`, `dlopen`s the resulting dylib, calls `lyrebird_snippet_entry`.
|
- **⌘↩** — compile and replace. Removes the previous run's anonymous synths (named slots persist), compiles the snippet via `swiftc -emit-library`, `dlopen`s the resulting dylib, calls `lyrebird_snippet_entry`.
|
||||||
- **⌘⇧↩** — compile additive. Prior synths stay in the engine.
|
- **⌘⇧↩** — compile additive. Prior synths stay in the engine.
|
||||||
- **Clear Synths** toolbar button — removes all tracked synths immediately.
|
- **Clear Synths** toolbar button — full reset: removes all tracked synths *and* every named slot immediately.
|
||||||
|
|
||||||
**Why this app cannot be sandboxed:**
|
**Why this app cannot be sandboxed:**
|
||||||
`swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. The entitlements file (`LyrebirdScratchDemo.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib.
|
`swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. The entitlements file (`LyrebirdScratch.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib.
|
||||||
|
|
||||||
**Dylib lifetime:** loaded dylibs are never unloaded. `Synthesizer` instances reference types from the dylib; unloading while they are active would crash. Every ⌘↩ evaluation writes a new uniquely-named dylib to a per-session temp dir. This is intentional v1 behaviour; a future release may revisit with an XPC worker approach.
|
**Dylib lifetime:** loaded dylibs are never unloaded. `Synthesizer` instances reference types from the dylib; unloading while they are active would crash. Every ⌘↩ evaluation writes a new uniquely-named dylib to a per-session temp dir. This is intentional v1 behaviour; a future release may revisit with an XPC worker approach.
|
||||||
|
|
||||||
@@ -200,6 +202,7 @@ final class MySynth: SynthesizerBase {
|
|||||||
|
|
||||||
| Topic | Doc |
|
| Topic | Doc |
|
||||||
|-------|-----|
|
|-------|-----|
|
||||||
|
| New to Swift? Intro for Lyrebird users | `docs/learning-swift/README.md` |
|
||||||
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
|
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
|
||||||
| Bus system, In/Out generators | `docs/engine/bus-system.md` |
|
| Bus system, In/Out generators | `docs/engine/bus-system.md` |
|
||||||
| Sample-accurate scheduling | `docs/engine/scheduling.md` |
|
| Sample-accurate scheduling | `docs/engine/scheduling.md` |
|
||||||
|
|||||||
@@ -46,10 +46,34 @@ let package = Package(
|
|||||||
.package(name: "Lyrebird", path: "..")
|
.package(name: "Lyrebird", path: "..")
|
||||||
],
|
],
|
||||||
targets: [
|
targets: [
|
||||||
|
// The interpreted graph-DSL, compiled from the main package's shared
|
||||||
|
// sources (a symlink at `Sources/LyrebirdGraphDSLEmbedded`) as a LOCAL
|
||||||
|
// target here rather than consumed as a main-package product.
|
||||||
|
//
|
||||||
|
// Why not the main-package product: any `LyrebirdGraphDSL` product —
|
||||||
|
// static OR dynamic — bakes a SECOND copy of `LyrebirdSynth` into its
|
||||||
|
// dylib (a same-package target dependency is always static-embedded), so
|
||||||
|
// both `libLyrebirdDynamic` and that product's dylib register Lyrebird's
|
||||||
|
// ObjC classes → double registration → spurious cast failures + SIGSEGV
|
||||||
|
// under `swift test`. Compiling the DSL as a local target here lets its
|
||||||
|
// `import LyrebirdSynth` resolve cross-package to the ONE shared
|
||||||
|
// `libLyrebirdDynamic`. Safe because the DSL is pure value types (no
|
||||||
|
// classes), so recompiling it in a second module registers nothing with
|
||||||
|
// the ObjC runtime. Distinct module name (`…Embedded`) avoids any clash
|
||||||
|
// with the main package's `LyrebirdGraphDSL` in a shared Xcode graph.
|
||||||
|
.target(
|
||||||
|
name: "LyrebirdGraphDSLEmbedded",
|
||||||
|
dependencies: [
|
||||||
|
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
|
||||||
|
],
|
||||||
|
path: "Sources/LyrebirdGraphDSLEmbedded"
|
||||||
|
),
|
||||||
.target(
|
.target(
|
||||||
name: "LyrebirdLiveCompile",
|
name: "LyrebirdLiveCompile",
|
||||||
dependencies: [
|
dependencies: [
|
||||||
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
|
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
|
||||||
|
// Instant, no-swiftc graph evaluation for the editor's DSL mode.
|
||||||
|
"LyrebirdGraphDSLEmbedded",
|
||||||
],
|
],
|
||||||
path: "Sources/LyrebirdLiveCompile"
|
path: "Sources/LyrebirdLiveCompile"
|
||||||
),
|
),
|
||||||
@@ -67,6 +91,7 @@ let package = Package(
|
|||||||
dependencies: [
|
dependencies: [
|
||||||
"LyrebirdLiveCompile",
|
"LyrebirdLiveCompile",
|
||||||
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
|
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
|
||||||
|
"LyrebirdGraphDSLEmbedded",
|
||||||
],
|
],
|
||||||
path: "Tests/LyrebirdLiveCompileTests"
|
path: "Tests/LyrebirdLiveCompileTests"
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
../../Sources/LyrebirdGraphDSL
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
// ArtifactStagingError.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
|
||||||
|
/// Errors raised while staging compile artifacts into Application Support.
|
||||||
|
enum ArtifactStagingError: Error {
|
||||||
|
/// The staging destination already exists, is non-empty, and does not look
|
||||||
|
/// like a prior staging root — refused rather than clobbered.
|
||||||
|
case destinationNotAStagingRoot(String)
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
// GraphDSLDiagnosticMapper.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdLiveCompile
|
||||||
|
//
|
||||||
|
// Turns a thrown `DSLParseError` / `DSLBuildError` into the same `[Diagnostic]`
|
||||||
|
// the swiftc path produces, so `LyrebirdScratchView`'s gutter renders DSL
|
||||||
|
// failures with no special-casing. Parse errors carry a source span → a real
|
||||||
|
// (line, column); build errors carry no span → `line: nil` with the message
|
||||||
|
// alone.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import LyrebirdGraphDSLEmbedded
|
||||||
|
|
||||||
|
/// Maps interpreted-graph-DSL errors to editor diagnostics.
|
||||||
|
enum GraphDSLDiagnosticMapper {
|
||||||
|
|
||||||
|
/// Convert `error` (a `DSLParseError`, a `DSLBuildError`, or anything else)
|
||||||
|
/// into one or more ``Diagnostic``s, resolving parse-error spans against
|
||||||
|
/// `source` for a 1-based line/column.
|
||||||
|
static func diagnostics(for error: Error, source: String) -> [Diagnostic] {
|
||||||
|
if let parse: DSLParseError = error as? DSLParseError {
|
||||||
|
let (line, column): (Int, Int) = lineColumn(of: parse.span.start, in: source)
|
||||||
|
return [Diagnostic(
|
||||||
|
line: line,
|
||||||
|
column: column,
|
||||||
|
severity: .error,
|
||||||
|
message: parse.description,
|
||||||
|
rawLine: line
|
||||||
|
)]
|
||||||
|
}
|
||||||
|
if let build: DSLBuildError = error as? DSLBuildError {
|
||||||
|
// Build errors carry no span; report at file scope.
|
||||||
|
return [Diagnostic(
|
||||||
|
line: nil,
|
||||||
|
column: 0,
|
||||||
|
severity: .error,
|
||||||
|
message: build.description,
|
||||||
|
rawLine: 0
|
||||||
|
)]
|
||||||
|
}
|
||||||
|
return [Diagnostic(
|
||||||
|
line: nil,
|
||||||
|
column: 0,
|
||||||
|
severity: .error,
|
||||||
|
message: "\(error)",
|
||||||
|
rawLine: 0
|
||||||
|
)]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Map a character `offset` into `source` to a 1-based (line, column).
|
||||||
|
/// An offset past the end clamps to the final position.
|
||||||
|
private static func lineColumn(of offset: Int, in source: String) -> (line: Int, column: Int) {
|
||||||
|
var line: Int = 1
|
||||||
|
var column: Int = 1
|
||||||
|
var seen: Int = 0
|
||||||
|
for character: Character in source {
|
||||||
|
if seen >= offset { break }
|
||||||
|
if character == "\n" {
|
||||||
|
line += 1
|
||||||
|
column = 1
|
||||||
|
} else {
|
||||||
|
column += 1
|
||||||
|
}
|
||||||
|
seen += 1
|
||||||
|
}
|
||||||
|
return (line, column)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// LSPCompletionItem.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdLiveCompile
|
||||||
|
//
|
||||||
|
// One parsed code-completion candidate from `sourcekit-lsp`. macOS only.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
|
||||||
|
/// One code-completion candidate returned by sourcekit-lsp.
|
||||||
|
public struct LSPCompletionItem: Sendable, Equatable {
|
||||||
|
/// Display label (e.g. `Audio`).
|
||||||
|
public let label: String
|
||||||
|
/// Type / signature detail (e.g. `OscSin.Audio`), if provided.
|
||||||
|
public let detail: String?
|
||||||
|
/// Text to insert when chosen. Falls back to `label` when the server gives
|
||||||
|
/// no explicit insert text.
|
||||||
|
public let insertText: String
|
||||||
|
/// LSP `CompletionItemKind` raw value, or `nil`. Lets the UI pick an icon.
|
||||||
|
public let kind: Int?
|
||||||
|
/// Server-provided sort key; the UI orders by this then by `label`.
|
||||||
|
public let sortText: String?
|
||||||
|
|
||||||
|
public init(
|
||||||
|
label: String,
|
||||||
|
detail: String?,
|
||||||
|
insertText: String,
|
||||||
|
kind: Int?,
|
||||||
|
sortText: String?
|
||||||
|
) {
|
||||||
|
self.label = label
|
||||||
|
self.detail = detail
|
||||||
|
self.insertText = insertText
|
||||||
|
self.kind = kind
|
||||||
|
self.sortText = sortText
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -190,10 +190,11 @@ public enum LiveCompiler {
|
|||||||
process.arguments = arguments
|
process.arguments = arguments
|
||||||
let stderrPipe: Pipe = Pipe()
|
let stderrPipe: Pipe = Pipe()
|
||||||
process.standardError = stderrPipe
|
process.standardError = stderrPipe
|
||||||
// stdout discarded — swiftc emits no useful output in -emit-library mode.
|
// stdout discarded — swiftc emits no useful output in the modes used
|
||||||
// Use FileHandle.nullDevice (not Pipe()) so the OS drops the bytes itself;
|
// here (-emit-library and -typecheck). Use FileHandle.nullDevice (not
|
||||||
// an undrained Pipe deadlocks against the blocking stderr read below if
|
// Pipe()) so the OS drops the bytes itself; an undrained Pipe deadlocks
|
||||||
// swiftc ever writes more than the pipe buffer (~64 KB) to stdout.
|
// against the blocking stderr read below if swiftc ever writes more than
|
||||||
|
// the pipe buffer (~64 KB) to stdout.
|
||||||
process.standardOutput = FileHandle.nullDevice
|
process.standardOutput = FileHandle.nullDevice
|
||||||
do {
|
do {
|
||||||
try process.run()
|
try process.run()
|
||||||
@@ -205,6 +206,53 @@ public enum LiveCompiler {
|
|||||||
let stderrString: String = String(data: stderrData, encoding: .utf8) ?? ""
|
let stderrString: String = String(data: stderrData, encoding: .utf8) ?? ""
|
||||||
return SwiftcResult(exitCode: process.terminationStatus, stderr: stderrString)
|
return SwiftcResult(exitCode: process.terminationStatus, stderr: stderrString)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Module-cache prewarm
|
||||||
|
|
||||||
|
/// Build the Clang/Swift module cache (the precompiled `.pcm` for the large
|
||||||
|
/// `LyrebirdSynth` interface and its dependencies) by **type-checking** a
|
||||||
|
/// trivial source that imports the same modules a real snippet does.
|
||||||
|
///
|
||||||
|
/// The cold cache build costs ~2–3 s and otherwise lands on the user's first
|
||||||
|
/// ⌘↩; running this once at session start (off-main) moves that cost into the
|
||||||
|
/// background, so the first real ``compile(source:extraSwiftcArgs:)`` hits a
|
||||||
|
/// warm cache (~0.1 s). `-typecheck` is enough — the `.pcm`s are produced
|
||||||
|
/// during import resolution, before codegen/link — and avoids emitting or
|
||||||
|
/// `dlopen`ing a dylib.
|
||||||
|
///
|
||||||
|
/// - Parameter extraSwiftcArgs: The module-resolution flags (`-I`,
|
||||||
|
/// `-Xcc -fmodule-map-file=…`) that point at the same modules the real
|
||||||
|
/// compile uses, so both warm the same (default) module cache.
|
||||||
|
/// `LiveSession` supplies these via its module-resolution args.
|
||||||
|
/// - Throws: `LiveCompileError` for a missing toolchain, IO failure, or a
|
||||||
|
/// non-zero type-check exit.
|
||||||
|
public static func prewarm(extraSwiftcArgs: [String]) throws {
|
||||||
|
let swiftc: String = try findSwiftc()
|
||||||
|
let id: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
|
||||||
|
let workDir: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("LyrebirdLiveCompile-prewarm-\(id)", isDirectory: true)
|
||||||
|
let sourcePath: String = workDir.appendingPathComponent("Prewarm.swift").path
|
||||||
|
let source: String = "import LyrebirdSynth\nimport LyrebirdLiveCompile\n"
|
||||||
|
do {
|
||||||
|
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
|
||||||
|
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
|
||||||
|
} catch {
|
||||||
|
throw LiveCompileError.ioFailed(underlying: "\(error)")
|
||||||
|
}
|
||||||
|
defer { try? FileManager.default.removeItem(at: workDir) }
|
||||||
|
|
||||||
|
var arguments: [String] = ["-typecheck", "-module-name", "LBPrewarm_\(id)"]
|
||||||
|
if let sdkPath: String = sdkPathViaXcrun() {
|
||||||
|
arguments.append(contentsOf: ["-sdk", sdkPath])
|
||||||
|
}
|
||||||
|
arguments += extraSwiftcArgs
|
||||||
|
arguments.append(sourcePath)
|
||||||
|
|
||||||
|
let result: LiveCompiler.SwiftcResult = try runSwiftc(executable: swiftc, arguments: arguments)
|
||||||
|
guard result.exitCode == 0 else {
|
||||||
|
throw LiveCompileError.compileFailed(exitCode: result.exitCode, stderr: result.stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -28,9 +28,10 @@ import LyrebirdSynth
|
|||||||
/// Swift 6 requires it to be `Sendable`. The conformance is sound by construction:
|
/// Swift 6 requires it to be `Sendable`. The conformance is sound by construction:
|
||||||
///
|
///
|
||||||
/// - `engine` and all `-I` / `-L` / `-l` / `rpath` configuration are immutable `let`.
|
/// - `engine` and all `-I` / `-L` / `-l` / `rpath` configuration are immutable `let`.
|
||||||
/// - The only mutable graph state — `trackedSynths` and `loadedSnippets` — is accessed
|
/// - The mutable graph state — `trackedSynths`, `loadedSnippets`, and the named-slot map
|
||||||
/// exclusively under `trackingLock` (`track`, `clearTracked`, `trackedSynthCount`,
|
/// `slottedSynths` — is accessed exclusively under `trackingLock` (`track`,
|
||||||
/// `runEntry`).
|
/// `clearTracked`, `trackedSynthCount`, `runEntry`, `assignSlot`, `clearSlot`,
|
||||||
|
/// `clearSlots`, `slotCount`, `slotNames`).
|
||||||
/// - `reportedSampleRate` / `lastSnippetMessage` are test-only side channels (`@testable`),
|
/// - `reportedSampleRate` / `lastSnippetMessage` are test-only side channels (`@testable`),
|
||||||
/// written by the single in-flight snippet entry under the documented
|
/// written by the single in-flight snippet entry under the documented
|
||||||
/// one-invocation-at-a-time precondition (see `compileAndRunAsync`) and read by tests
|
/// one-invocation-at-a-time precondition (see `compileAndRunAsync`) and read by tests
|
||||||
@@ -39,6 +40,14 @@ public final class LiveSession: @unchecked Sendable {
|
|||||||
|
|
||||||
public let engine: SynthesisEngine
|
public let engine: SynthesisEngine
|
||||||
|
|
||||||
|
/// Output-tapping oscilloscope capture for the editor's scope view. When a
|
||||||
|
/// fresh tap is installed at init (the engine is not yet running and has no
|
||||||
|
/// tap), this is that capture; if the engine already had a `scopeTap`, this
|
||||||
|
/// reuses it; it is `nil` only when no tap is present (attachment declined,
|
||||||
|
/// or the engine was already running with no tap). Must be installed before
|
||||||
|
/// `start()`.
|
||||||
|
public let scope: ScopeCapture?
|
||||||
|
|
||||||
/// `-I` paths threaded to `swiftc` for module discovery.
|
/// `-I` paths threaded to `swiftc` for module discovery.
|
||||||
public let importPaths: [URL]
|
public let importPaths: [URL]
|
||||||
|
|
||||||
@@ -53,27 +62,95 @@ public final class LiveSession: @unchecked Sendable {
|
|||||||
/// runtime without `DYLD_LIBRARY_PATH` ceremony.
|
/// runtime without `DYLD_LIBRARY_PATH` ceremony.
|
||||||
public let rpaths: [URL]
|
public let rpaths: [URL]
|
||||||
|
|
||||||
|
// Prewarm lifecycle — guarded by `trackingLock`. `_prewarmed` flips true
|
||||||
|
// when a prewarm completes; `_prewarming` guards a call in flight so
|
||||||
|
// repeat calls (e.g. a view re-appearing) don't spawn a second swiftc.
|
||||||
|
private var _prewarmed: Bool = false
|
||||||
|
private var _prewarming: Bool = false
|
||||||
|
|
||||||
/// Side-channel for snippet `context.reportSampleRate(_:)` calls. Tests read
|
/// Side-channel for snippet `context.reportSampleRate(_:)` calls. Tests read
|
||||||
/// via `@testable import`; not part of the public API.
|
/// via `@testable import`; not part of the public API.
|
||||||
internal var reportedSampleRate: Double?
|
internal var reportedSampleRate: Double?
|
||||||
|
|
||||||
/// Side-channel for snippet `context.reportMessage(_:)` calls. Tests read
|
/// Most recent snippet `context.reportMessage(_:)` value (tests read this via
|
||||||
/// via `@testable import`; not part of the public API.
|
/// `@testable import`). Backed by the internal message log (`_messageLog`).
|
||||||
internal var lastSnippetMessage: String?
|
internal var lastSnippetMessage: String? { _messageLog.last }
|
||||||
|
|
||||||
|
/// Accumulated `context.reportMessage(_:)` output (and host-side notices like
|
||||||
|
/// a dropped slot swap) since the last drain. Main-thread only — appended
|
||||||
|
/// during the synchronous snippet entry, drained by the host after each run.
|
||||||
|
private var _messageLog: [String] = []
|
||||||
|
|
||||||
|
/// Append a snippet/host message to the log. Main-thread only.
|
||||||
|
internal func appendMessage(_ message: String) {
|
||||||
|
_messageLog.append(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return and clear the accumulated messages. Called by the host after a run
|
||||||
|
/// to move them into its console.
|
||||||
|
public func drainMessages() -> [String] {
|
||||||
|
let out: [String] = _messageLog
|
||||||
|
_messageLog.removeAll()
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
// Tracked state — all access guarded by `trackingLock`.
|
// Tracked state — all access guarded by `trackingLock`.
|
||||||
private let trackingLock: NSLock = NSLock()
|
private let trackingLock: NSLock = NSLock()
|
||||||
private var trackedSynths: [any Synthesizer] = []
|
private var trackedSynths: [any Synthesizer] = []
|
||||||
private var loadedSnippets: [CompiledSnippet] = []
|
private var loadedSnippets: [CompiledSnippet] = []
|
||||||
|
|
||||||
|
// A named-slot occupant plus the sample time its add was scheduled at.
|
||||||
|
// The add time lets a later teardown schedule the occupant's removal no
|
||||||
|
// earlier than its own add, so a still-pending *scheduled* voice (quantized
|
||||||
|
// swap not yet fired) is never orphaned by an immediate clear or an earlier
|
||||||
|
// re-swap. See `removeSlotOccupant`.
|
||||||
|
private struct SlotEntry {
|
||||||
|
let synth: any Synthesizer
|
||||||
|
let addTime: SampleTime
|
||||||
|
}
|
||||||
|
|
||||||
|
// Named slots — `Pdef`-style persistent voices, keyed by name. Kept
|
||||||
|
// separate from the anonymous `trackedSynths` so they SURVIVE a
|
||||||
|
// non-additive re-evaluation: re-running a `context.play(slot: "bass") { … }`
|
||||||
|
// definition replaces just that voice in place (via `assignSlot`) instead of
|
||||||
|
// being cleared with the anonymous synths. Guarded by `trackingLock`.
|
||||||
|
private var slottedSynths: [String: SlotEntry] = [:]
|
||||||
|
|
||||||
|
// Swap-quantization config + pending-swap signal — all guarded by
|
||||||
|
// `trackingLock`. When `_swapClock` is set and `_swapQuantize` is not
|
||||||
|
// `.immediate`, a slot swap schedules the new voice's add and the old
|
||||||
|
// voice's removal at the next musical boundary instead of taking effect at
|
||||||
|
// once (latency masking). `_pendingSwapBeat` is the latest target beat of a
|
||||||
|
// not-yet-fired scheduled swap, surfaced via ``pendingSwapBeat``.
|
||||||
|
private var _swapClock: LyrebirdClock?
|
||||||
|
private var _swapQuantize: SwapQuantize = .immediate
|
||||||
|
private var _pendingSwapBeat: Double?
|
||||||
|
|
||||||
|
/// Samples per channel the scope captures per display frame.
|
||||||
|
private static let scopeBufferSize: Int = 1024
|
||||||
|
|
||||||
|
/// - Parameter attachScope: When `true` (default) and the engine is not yet
|
||||||
|
/// running and has no existing tap, install a ``ScopeCapture`` on the first
|
||||||
|
/// one or two output buses for the editor's scope view.
|
||||||
public init(
|
public init(
|
||||||
engine: SynthesisEngine,
|
engine: SynthesisEngine,
|
||||||
|
attachScope: Bool = true,
|
||||||
importPaths: [URL] = LiveSession.defaultImportPaths(),
|
importPaths: [URL] = LiveSession.defaultImportPaths(),
|
||||||
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
|
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
|
||||||
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
|
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
|
||||||
rpaths: [URL] = LiveSession.defaultRpaths()
|
rpaths: [URL] = LiveSession.defaultRpaths()
|
||||||
) {
|
) {
|
||||||
self.engine = engine
|
self.engine = engine
|
||||||
|
// Install the scope tap before the host calls `start()` (the RT thread
|
||||||
|
// caches `scopeTap` at start; setting it afterwards is a no-op).
|
||||||
|
if attachScope, !engine.isRunning, engine.scopeTap == nil, engine.numOutputChannels >= 1 {
|
||||||
|
let buses: [Int] = Array(0..<min(2, engine.numOutputChannels))
|
||||||
|
let capture: ScopeCapture = ScopeCapture(buses: buses, bufferSize: LiveSession.scopeBufferSize)
|
||||||
|
engine.scopeTap = capture
|
||||||
|
self.scope = capture
|
||||||
|
} else {
|
||||||
|
self.scope = engine.scopeTap
|
||||||
|
}
|
||||||
self.importPaths = importPaths
|
self.importPaths = importPaths
|
||||||
self.librarySearchPaths = librarySearchPaths
|
self.librarySearchPaths = librarySearchPaths
|
||||||
self.libraries = libraries
|
self.libraries = libraries
|
||||||
@@ -208,9 +285,367 @@ public final class LiveSession: @unchecked Sendable {
|
|||||||
trackedSynths.append(synth)
|
trackedSynths.append(synth)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Named slots
|
||||||
|
|
||||||
|
/// Number of named slots currently holding a synth. Thread-safe.
|
||||||
|
public var slotCount: Int {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
return slottedSynths.count
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Names of the currently-populated slots. Thread-safe.
|
||||||
|
public var slotNames: [String] {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
return Array(slottedSynths.keys)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Install `synth` into the named `slot` immediately, replacing any synth
|
||||||
|
/// previously held there.
|
||||||
|
///
|
||||||
|
/// Internal hook for the immediate path of ``swapSlot(_:synth:)``. **Call
|
||||||
|
/// after `engine.add(synth)` has succeeded** — the new voice is live before
|
||||||
|
/// the old one is torn down, so a slot replacement is a brief overlap rather
|
||||||
|
/// than a silent gap. The previous occupant is removed via
|
||||||
|
/// ``removeSlotOccupant(_:desired:)`` (scheduled no earlier than its own
|
||||||
|
/// add, so a still-pending scheduled voice is never orphaned). Thread-safe;
|
||||||
|
/// `engine.remove` runs outside the lock.
|
||||||
|
func assignSlot(_ name: String, synth: any Synthesizer) {
|
||||||
|
let now: SampleTime = engine.currentTime
|
||||||
|
let previous: SlotEntry?
|
||||||
|
do {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
previous = slottedSynths[name]
|
||||||
|
slottedSynths[name] = SlotEntry(synth: synth, addTime: now)
|
||||||
|
}
|
||||||
|
if let previous: SlotEntry = previous {
|
||||||
|
removeSlotOccupant(previous, desired: now)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove every named-slot synth from the engine and clear all slots.
|
||||||
|
/// Anonymous tracked synths are untouched — pair with ``clearTracked()``
|
||||||
|
/// for a full reset.
|
||||||
|
public func clearSlots() {
|
||||||
|
let now: SampleTime = engine.currentTime
|
||||||
|
let snapshot: [SlotEntry]
|
||||||
|
do {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
snapshot = Array(slottedSynths.values)
|
||||||
|
slottedSynths.removeAll()
|
||||||
|
}
|
||||||
|
for entry: SlotEntry in snapshot {
|
||||||
|
removeSlotOccupant(entry, desired: now)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the synth in the named `slot` (if any) from the engine and clear
|
||||||
|
/// the slot. No-op when the slot is empty. Returns `true` if a synth was
|
||||||
|
/// removed.
|
||||||
|
@discardableResult
|
||||||
|
public func clearSlot(_ name: String) -> Bool {
|
||||||
|
let now: SampleTime = engine.currentTime
|
||||||
|
let previous: SlotEntry?
|
||||||
|
do {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
previous = slottedSynths.removeValue(forKey: name)
|
||||||
|
}
|
||||||
|
if let previous: SlotEntry = previous {
|
||||||
|
removeSlotOccupant(previous, desired: now)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// **Gracefully release** the synth in the named `slot` (trigger its
|
||||||
|
/// envelope release phase) and drop the slot handle, so the voice tails out
|
||||||
|
/// and then frees itself via its own done-action — rather than being hard-cut
|
||||||
|
/// like ``clearSlot(_:)``. This is the live-coding "let go of this voice"
|
||||||
|
/// gesture: pair it with ``SnippetContext/play(slot:_:)-…`` to start a
|
||||||
|
/// persistent voice under a name and release it later from a separate
|
||||||
|
/// evaluation.
|
||||||
|
///
|
||||||
|
/// The handle is dropped **only if the release succeeds**, so a voice with no
|
||||||
|
/// gate to release (its `release(engine:)` throws) stays in the slot and can
|
||||||
|
/// still be stopped with ``clearSlot(_:)`` — it is never orphaned.
|
||||||
|
///
|
||||||
|
/// On success the voice is moved from the slot map into the anonymous
|
||||||
|
/// tracked list, so it remains reachable by ``clearTracked()`` / ``resetAll()``
|
||||||
|
/// (the toolbar "Clear Synths"). A well-behaved voice self-frees via its
|
||||||
|
/// done-action before then; a mis-configured one that never self-frees is
|
||||||
|
/// still reclaimable rather than leaked until a process restart. (A later
|
||||||
|
/// hard `engine.remove` on an already-self-freed synth is a harmless no-op.)
|
||||||
|
///
|
||||||
|
/// - Parameter name: Slot to release.
|
||||||
|
/// - Returns: `true` if a gated voice was released; `false` if the slot was
|
||||||
|
/// empty or its occupant had no gate (reported via `lastSnippetMessage`).
|
||||||
|
///
|
||||||
|
/// The identity guard below (`… === entry.synth`) is load-bearing, not
|
||||||
|
/// defensive dead code: `clearSlot` / `clearSlots` / `resetAll` are
|
||||||
|
/// nonisolated and may run on another thread while this `release(engine:)`
|
||||||
|
/// call is in flight on the main actor.
|
||||||
|
@MainActor
|
||||||
|
@discardableResult
|
||||||
|
public func releaseSlot(_ name: String) -> Bool {
|
||||||
|
let entry: SlotEntry?
|
||||||
|
do {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
entry = slottedSynths[name]
|
||||||
|
}
|
||||||
|
guard let entry: SlotEntry = entry else { return false }
|
||||||
|
do {
|
||||||
|
try entry.synth.release(engine: engine)
|
||||||
|
// Released — free the name for reuse and keep the voice reachable by
|
||||||
|
// the tracked-synth sweep (its safety net until it self-frees).
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
if slottedSynths[name]?.synth === entry.synth {
|
||||||
|
slottedSynths[name] = nil
|
||||||
|
trackedSynths.append(entry.synth)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
appendMessage(
|
||||||
|
"slot '\(name)': release failed (\(error)) — use clearSlot() to stop it")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove a slot occupant, scheduling the removal no earlier than the
|
||||||
|
/// occupant's own add time (`max(desired, addTime)`) so a still-pending
|
||||||
|
/// scheduled add is never orphaned. `desired` is the caller's intended
|
||||||
|
/// removal time — a swap boundary, or the current time for an immediate
|
||||||
|
/// teardown. Because the occupant's add is always enqueued before this
|
||||||
|
/// removal and the engine's per-block event sort is stable at equal times,
|
||||||
|
/// an add and removal landing on the same sample apply add-then-removal, so
|
||||||
|
/// the voice is always cleaned up. Runs outside `trackingLock`.
|
||||||
|
@discardableResult
|
||||||
|
private func removeSlotOccupant(_ entry: SlotEntry, desired: SampleTime) -> Bool {
|
||||||
|
let removeAt: SampleTime = max(desired, entry.addTime)
|
||||||
|
return engine.remove(entry.synth, at: removeAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Session reset + snippet accounting
|
||||||
|
|
||||||
|
/// Panic / clear-everything valve: remove every snippet-played synth — both
|
||||||
|
/// the anonymous tracked ones (``clearTracked()``) and every named slot
|
||||||
|
/// (``clearSlots()``) — from the engine, and clear the pending-swap signal.
|
||||||
|
/// Stops all snippet audio and gives a clean slate without tearing down the
|
||||||
|
/// engine.
|
||||||
|
///
|
||||||
|
/// It does **not** reclaim the compiled snippet dylibs — see
|
||||||
|
/// ``loadedSnippetCount``. Reclaiming that memory would require `dlclose`,
|
||||||
|
/// which is unsafe for these Swift dylibs: `dlopen` registers their type
|
||||||
|
/// metadata and protocol-conformance records into process-global runtime
|
||||||
|
/// caches that `dlclose` does not deregister, so unmapping the dylib leaves
|
||||||
|
/// those caches dangling. Mapped snippet memory is therefore reclaimed only
|
||||||
|
/// by restarting the process. (The interpreted-graph path on the roadmap
|
||||||
|
/// avoids dylibs entirely and is the structural fix.)
|
||||||
|
///
|
||||||
|
/// - Precondition: same one-invocation-at-a-time caveat as
|
||||||
|
/// ``compileAndRunAsync(_:additive:)``. Calling this concurrently with an
|
||||||
|
/// in-flight compile can interleave the internal `clearTracked()` with a
|
||||||
|
/// not-yet-completed `runEntry`, missing a just-added synth (which then
|
||||||
|
/// leaks until process restart). The built-in ``LyrebirdScratchModel``
|
||||||
|
/// serialises through its `isCompiling` flag. This is also not a single
|
||||||
|
/// atomic critical section — the synth removal and the pending-swap clear
|
||||||
|
/// take `trackingLock` separately — which is acceptable for a panic valve.
|
||||||
|
public func resetAll() {
|
||||||
|
clearTracked()
|
||||||
|
clearSlots()
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
_pendingSwapBeat = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Number of compiled snippet dylibs currently mapped into the process.
|
||||||
|
///
|
||||||
|
/// Each ⌘↩ compiles a new dylib that stays mapped for the process's lifetime
|
||||||
|
/// (unloading is unsafe — see ``resetAll()``), so within a session this only
|
||||||
|
/// grows. Exposed for host observability, e.g. a "restart to reclaim memory"
|
||||||
|
/// nudge after a very long session. Thread-safe.
|
||||||
|
public var loadedSnippetCount: Int {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
return loadedSnippets.count
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Swap quantization (on-beat latency masking)
|
||||||
|
|
||||||
|
/// Clock that slot swaps quantize against. When `nil` (default), swaps are
|
||||||
|
/// always immediate regardless of ``swapQuantize``. Setting it clears any
|
||||||
|
/// pending-swap signal (``pendingSwapBeat``). Thread-safe.
|
||||||
|
public var swapClock: LyrebirdClock? {
|
||||||
|
get { trackingLock.lock(); defer { trackingLock.unlock() }; return _swapClock }
|
||||||
|
set {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
_swapClock = newValue
|
||||||
|
_pendingSwapBeat = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When a named-slot swap becomes audible. Defaults to ``SwapQuantize/immediate``.
|
||||||
|
/// Only takes effect when ``swapClock`` is also set. Setting it clears any
|
||||||
|
/// pending-swap signal (``pendingSwapBeat``). Thread-safe.
|
||||||
|
public var swapQuantize: SwapQuantize {
|
||||||
|
get { trackingLock.lock(); defer { trackingLock.unlock() }; return _swapQuantize }
|
||||||
|
set {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
_swapQuantize = newValue
|
||||||
|
_pendingSwapBeat = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Target beat of the latest scheduled-but-not-yet-fired slot swap, or `nil`
|
||||||
|
/// when none is pending (immediate mode, the boundary has already passed, or
|
||||||
|
/// the swap config changed). Self-clearing: returns `nil` once the clock
|
||||||
|
/// reaches the target beat. Drives the editor's `.queued` readiness state.
|
||||||
|
///
|
||||||
|
/// When several slots have swaps pending at different beats this reports the
|
||||||
|
/// latest of them — treat it as "some swap is still outstanding", not "this
|
||||||
|
/// specific run's swap". Thread-safe, but not atomic against a concurrent
|
||||||
|
/// swap: the `_swapClock` snapshot and the `clock.currentBeat` read happen in
|
||||||
|
/// separate critical sections, so a swap scheduled between them may not yet
|
||||||
|
/// be reflected. Fine for the main-actor UI that consumes it.
|
||||||
|
public var pendingSwapBeat: Double? {
|
||||||
|
let target: Double?
|
||||||
|
let clock: LyrebirdClock?
|
||||||
|
do {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
target = _pendingSwapBeat
|
||||||
|
clock = _swapClock
|
||||||
|
}
|
||||||
|
guard let target: Double = target, let clock: LyrebirdClock = clock else { return nil }
|
||||||
|
return clock.currentBeat < target ? target : nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Install `synth` into the named `slot`, quantizing the swap per
|
||||||
|
/// ``swapQuantize`` / ``swapClock``.
|
||||||
|
///
|
||||||
|
/// Immediate mode (`.immediate` or no clock): adds `synth` now and removes
|
||||||
|
/// the previous slot synth now (via ``assignSlot(_:synth:)``). Quantized
|
||||||
|
/// mode: schedules `synth`'s add and the previous synth's removal at the same
|
||||||
|
/// upcoming boundary sample time, so the swap is glitch-free and on-grid,
|
||||||
|
/// and records the target beat for ``pendingSwapBeat``.
|
||||||
|
///
|
||||||
|
/// Backs ``SnippetContext/play(slot:_:)``. `@MainActor` because it touches
|
||||||
|
/// the engine's node tree (`add`/`schedule`/`remove`).
|
||||||
|
///
|
||||||
|
/// - Throws: `EngineAddError` if the engine rejects the add/schedule; the
|
||||||
|
/// prior slot synth is left in place on throw.
|
||||||
|
@MainActor
|
||||||
|
func swapSlot(_ name: String, synth: any Synthesizer) throws {
|
||||||
|
let clock: LyrebirdClock?
|
||||||
|
let quantize: SwapQuantize
|
||||||
|
do {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
clock = _swapClock
|
||||||
|
quantize = _swapQuantize
|
||||||
|
}
|
||||||
|
if let clock: LyrebirdClock = clock, let beat: Double = quantize.targetBeat(clock: clock) {
|
||||||
|
let time: SampleTime = clock.sampleTime(beat: beat)
|
||||||
|
try engine.schedule(synth, at: time)
|
||||||
|
scheduleSlotReplace(name, newSynth: synth, at: time, targetBeat: beat)
|
||||||
|
} else {
|
||||||
|
try engine.add(synth)
|
||||||
|
assignSlot(name, synth: synth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commit a scheduled slot replacement: swap the dictionary entry, schedule
|
||||||
|
/// removal of the previous synth at the boundary `time` (no earlier than its
|
||||||
|
/// own add), and record the pending target beat. Call only after
|
||||||
|
/// `engine.schedule(new, at: time)` succeeded. `engine.remove` runs outside
|
||||||
|
/// the lock; a dropped removal (pending queue full) is surfaced via
|
||||||
|
/// `lastSnippetMessage` rather than silently leaving an overlap.
|
||||||
|
private func scheduleSlotReplace(
|
||||||
|
_ name: String,
|
||||||
|
newSynth: any Synthesizer,
|
||||||
|
at time: SampleTime,
|
||||||
|
targetBeat: Double
|
||||||
|
) {
|
||||||
|
let previous: SlotEntry?
|
||||||
|
do {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
previous = slottedSynths[name]
|
||||||
|
slottedSynths[name] = SlotEntry(synth: newSynth, addTime: time)
|
||||||
|
_pendingSwapBeat = max(_pendingSwapBeat ?? targetBeat, targetBeat)
|
||||||
|
}
|
||||||
|
if let previous: SlotEntry = previous {
|
||||||
|
let removed: Bool = removeSlotOccupant(previous, desired: time)
|
||||||
|
if !removed {
|
||||||
|
appendMessage(
|
||||||
|
"slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Prewarm
|
||||||
|
|
||||||
|
/// `true` once a ``prewarm()`` has **succeeded** for this session. A prewarm
|
||||||
|
/// that failed (e.g. missing toolchain) leaves this `false` so a later call
|
||||||
|
/// retries. Thread-safe.
|
||||||
|
public var isPrewarmed: Bool {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
return _prewarmed
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Warm the module cache in the background so the first real ⌘↩ is fast.
|
||||||
|
///
|
||||||
|
/// The cold `LyrebirdSynth` `.pcm` build costs ~2–3 s; without a prewarm it
|
||||||
|
/// lands on the user's first compile. This kicks a detached, `.utility`
|
||||||
|
/// type-check of a trivial import-only snippet (via
|
||||||
|
/// ``LiveCompiler/prewarm(extraSwiftcArgs:)``) that warms swiftc's default
|
||||||
|
/// module cache, so the first `compileAndRunAsync` hits a warm cache
|
||||||
|
/// (~0.1 s). All the work — including the filesystem walk that builds the
|
||||||
|
/// compiler flags — runs on the detached task, not the caller's thread.
|
||||||
|
///
|
||||||
|
/// Idempotent: a call while a prewarm has already succeeded or is in flight
|
||||||
|
/// is a no-op. A *failed* prewarm leaves ``isPrewarmed`` `false` (a later
|
||||||
|
/// call retries); the real compile then simply pays the build itself, so the
|
||||||
|
/// failure is non-fatal and intentionally not thrown.
|
||||||
|
///
|
||||||
|
/// - Returns: The detached `Task`, so callers/tests can `await` its `value`.
|
||||||
|
/// The no-op case returns an already-scheduled empty task.
|
||||||
|
@discardableResult
|
||||||
|
public func prewarm() -> Task<Void, Never> {
|
||||||
|
let shouldRun: Bool
|
||||||
|
do {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
shouldRun = !_prewarmed && !_prewarming
|
||||||
|
if shouldRun { _prewarming = true }
|
||||||
|
}
|
||||||
|
guard shouldRun else { return Task {} }
|
||||||
|
return Task.detached(priority: .utility) { [weak self] in
|
||||||
|
guard let self: LiveSession = self else { return }
|
||||||
|
// Off-main: build the flags (a small filesystem walk) here rather
|
||||||
|
// than on the caller (this method is a synchronous `nonisolated`
|
||||||
|
// call, so anything before the detached task runs on the caller).
|
||||||
|
let args: [String] = self.makeModuleResolutionArgs()
|
||||||
|
do {
|
||||||
|
try LiveCompiler.prewarm(extraSwiftcArgs: args)
|
||||||
|
self.finishPrewarm(succeeded: true)
|
||||||
|
} catch {
|
||||||
|
self.finishPrewarm(succeeded: false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record a ``prewarm()`` outcome: clear the in-flight flag, and mark warmed
|
||||||
|
/// only on success so a failed attempt can retry.
|
||||||
|
private func finishPrewarm(succeeded: Bool) {
|
||||||
|
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||||
|
_prewarming = false
|
||||||
|
if succeeded { _prewarmed = true }
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - swiftc flag construction
|
// MARK: - swiftc flag construction
|
||||||
|
|
||||||
private func makeSwiftcArgs() -> [String] {
|
/// Module-resolution flags shared by the real compile and the prewarm:
|
||||||
|
/// `-I` import paths plus the Xcode + bare-SPM Clang module maps. No linker
|
||||||
|
/// flags — a `-typecheck` prewarm needs none. Deliberately does **not** pin
|
||||||
|
/// `-module-cache-path`: prewarm and the real compile both use swiftc's
|
||||||
|
/// default cache, so the prewarm warms exactly the cache the compile reads.
|
||||||
|
/// (Pinning a dedicated cache built fresh diverges its module metadata from
|
||||||
|
/// the already-loaded `libLyrebirdLiveCompileDynamic`, which turns the test
|
||||||
|
/// bundle's benign ObjC class-duplication warning into a hard cast crash.)
|
||||||
|
private func makeModuleResolutionArgs() -> [String] {
|
||||||
var args: [String] = []
|
var args: [String] = []
|
||||||
for path: URL in importPaths {
|
for path: URL in importPaths {
|
||||||
args += ["-I", path.path]
|
args += ["-I", path.path]
|
||||||
@@ -222,6 +657,19 @@ public final class LiveSession: @unchecked Sendable {
|
|||||||
for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) {
|
for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) {
|
||||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||||
}
|
}
|
||||||
|
// Bare-SPM (`swift build` / `swift test`) layout: C-target module maps
|
||||||
|
// live at `<buildDir>/<CTarget>.build/module.modulemap`, which the Xcode
|
||||||
|
// discovery above does not cover. Surface them so a snippet's
|
||||||
|
// `import LyrebirdSynth` can resolve the underlying `LyrebirdC` clang
|
||||||
|
// module outside Xcode too.
|
||||||
|
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
|
||||||
|
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||||
|
}
|
||||||
|
return args
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeSwiftcArgs() -> [String] {
|
||||||
|
var args: [String] = makeModuleResolutionArgs()
|
||||||
// When a Lyrebird dylib exists in any -L path, link against it
|
// When a Lyrebird dylib exists in any -L path, link against it
|
||||||
// (-l<name>) and bake an rpath. When no dylib is found (Xcode SPM
|
// (-l<name>) and bake an rpath. When no dylib is found (Xcode SPM
|
||||||
// case — modules statically linked into the host app), use
|
// case — modules statically linked into the host app), use
|
||||||
@@ -279,6 +727,33 @@ public final class LiveSession: @unchecked Sendable {
|
|||||||
return found
|
return found
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Locate SPM-generated Clang module maps for a `swift build` / `swift test`
|
||||||
|
/// layout. Each C target's map is emitted at
|
||||||
|
/// `<buildDir>/<CTarget>.build/module.modulemap`; the umbrella header path
|
||||||
|
/// inside is absolute, so the map alone is enough to resolve the module (no
|
||||||
|
/// extra `-I` needed). Empty under an Xcode SPM layout, where
|
||||||
|
/// `discoverClangModuleMaps` handles the `GeneratedModuleMaps` location
|
||||||
|
/// instead.
|
||||||
|
static func discoverSPMModuleMaps(in importPaths: [URL]) -> [URL] {
|
||||||
|
var found: [URL] = []
|
||||||
|
var visited: Set<String> = Set<String>()
|
||||||
|
for base: URL in importPaths {
|
||||||
|
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
|
||||||
|
at: base,
|
||||||
|
includingPropertiesForKeys: nil
|
||||||
|
) else { continue }
|
||||||
|
for entry: URL in entries where entry.pathExtension == "build" {
|
||||||
|
let probe: URL = entry.appendingPathComponent("module.modulemap")
|
||||||
|
if FileManager.default.fileExists(atPath: probe.path),
|
||||||
|
!visited.contains(probe.path) {
|
||||||
|
visited.insert(probe.path)
|
||||||
|
found.append(probe)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Build-dir discovery
|
// MARK: - Build-dir discovery
|
||||||
|
|
||||||
/// Best-effort discovery of the SPM `.build/<triple>/<config>` directory
|
/// Best-effort discovery of the SPM `.build/<triple>/<config>` directory
|
||||||
@@ -334,19 +809,36 @@ public final class LiveSession: @unchecked Sendable {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Prefer a populated staged artifacts dir (App Support, ungated) over the
|
||||||
|
/// SPM build dir (which lives under `~/Documents` in a dev checkout). Hosts
|
||||||
|
/// that want staging call ``stageArtifacts(from:to:)`` before constructing
|
||||||
|
/// the session; these defaults then resolve to the staged copy.
|
||||||
|
private static func resolvedArtifactsDir() -> URL? {
|
||||||
|
// Prefer the staged dir only when it is populated AND current relative to
|
||||||
|
// the live build dir — so a stale copy left by a different build (or a
|
||||||
|
// partial stage) never masquerades as the resolved artifacts for a host
|
||||||
|
// that did not itself stage.
|
||||||
|
if let staged: URL = stagedArtifactsDir(),
|
||||||
|
isArtifactsDirPopulated(staged),
|
||||||
|
stagedDirIsCurrent(staged) {
|
||||||
|
return staged
|
||||||
|
}
|
||||||
|
return currentBuildDir()
|
||||||
|
}
|
||||||
|
|
||||||
public static func defaultImportPaths() -> [URL] {
|
public static func defaultImportPaths() -> [URL] {
|
||||||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
guard let dir: URL = resolvedArtifactsDir() else { return [] }
|
||||||
return [buildDir, buildDir.appendingPathComponent("Modules")]
|
return [dir, dir.appendingPathComponent("Modules")]
|
||||||
}
|
}
|
||||||
|
|
||||||
public static func defaultLibrarySearchPaths() -> [URL] {
|
public static func defaultLibrarySearchPaths() -> [URL] {
|
||||||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
guard let dir: URL = resolvedArtifactsDir() else { return [] }
|
||||||
return [buildDir]
|
return [dir]
|
||||||
}
|
}
|
||||||
|
|
||||||
public static func defaultRpaths() -> [URL] {
|
public static func defaultRpaths() -> [URL] {
|
||||||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
guard let dir: URL = resolvedArtifactsDir() else { return [] }
|
||||||
return [buildDir]
|
return [dir]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,355 @@
|
|||||||
|
// LiveSessionArtifactStaging.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// Snippet compilation needs the Lyrebird module artifacts (swiftmodules, the
|
||||||
|
// Lyrebird dylibs, and the C-shim Clang module map + its umbrella header). In a
|
||||||
|
// dev checkout those live in the SPM build dir under `~/Documents`, so a
|
||||||
|
// non-sandboxed host reading them — and the `swiftc` it spawns reading them —
|
||||||
|
// trips the macOS "wants to access your Documents folder" TCC gate.
|
||||||
|
//
|
||||||
|
// Staging copies the minimal artifact set into
|
||||||
|
// `~/Library/Application Support/LyrebirdScratch/LiveCompile/`, an ungated
|
||||||
|
// location, and rewrites the C module map's absolute umbrella-header path to the
|
||||||
|
// staged copy. The default `-I` / `-L` / rpath resolution then prefers the
|
||||||
|
// staged dir, so a shipped app compiles snippets without ever touching a
|
||||||
|
// permission-gated folder.
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
|
||||||
|
extension LiveSession {
|
||||||
|
|
||||||
|
/// Name of the artifacts subdirectory a host may ship inside its app bundle
|
||||||
|
/// (`<App>.app/Contents/Resources/<name>`). Staging prefers this over the
|
||||||
|
/// dev build dir when present, so a shipped app never reads outside its
|
||||||
|
/// bundle or App Support.
|
||||||
|
public static let bundledArtifactsDirName: String = "LyrebirdArtifacts"
|
||||||
|
|
||||||
|
/// `~/Library/Application Support/LyrebirdScratch/LiveCompile` — the ungated
|
||||||
|
/// destination for staged compile artifacts. `nil` only if the Application
|
||||||
|
/// Support directory can't be resolved.
|
||||||
|
public static func stagedArtifactsDir() -> URL? {
|
||||||
|
guard let base: URL = FileManager.default.urls(
|
||||||
|
for: .applicationSupportDirectory,
|
||||||
|
in: .userDomainMask
|
||||||
|
).first else { return nil }
|
||||||
|
return base
|
||||||
|
.appendingPathComponent("LyrebirdScratch", isDirectory: true)
|
||||||
|
.appendingPathComponent("LiveCompile", isDirectory: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `dir` is a usable compile root: it has a `Modules/` directory
|
||||||
|
/// holding at least one `.swiftmodule`.
|
||||||
|
public static func isArtifactsDirPopulated(_ dir: URL) -> Bool {
|
||||||
|
let modules: URL = dir.appendingPathComponent("Modules", isDirectory: true)
|
||||||
|
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
|
||||||
|
at: modules,
|
||||||
|
includingPropertiesForKeys: nil
|
||||||
|
) else { return false }
|
||||||
|
return entries.contains { $0.pathExtension == "swiftmodule" }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where to stage FROM. Prefers a `LyrebirdArtifacts` directory shipped in
|
||||||
|
/// the app bundle's `Resources` (self-contained, never under a gated
|
||||||
|
/// folder); falls back to the dev SPM build dir.
|
||||||
|
public static func artifactSourceDir() -> URL? {
|
||||||
|
if let resources: URL = Bundle.main.resourceURL {
|
||||||
|
let bundled: URL = resources.appendingPathComponent(
|
||||||
|
bundledArtifactsDirName,
|
||||||
|
isDirectory: true
|
||||||
|
)
|
||||||
|
if isArtifactsDirPopulated(bundled) { return bundled }
|
||||||
|
}
|
||||||
|
return currentBuildDir()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copy the minimal artifact set from `source` (default: ``artifactSourceDir()``)
|
||||||
|
/// into `destination` (default: ``stagedArtifactsDir()``), rewriting the C
|
||||||
|
/// module map to point at a staged copy of its umbrella header. Idempotent:
|
||||||
|
/// skips the copy when the destination is already newer than the source.
|
||||||
|
/// Best-effort — returns the staged dir on success, `nil` on any failure or
|
||||||
|
/// when no source/destination could be resolved.
|
||||||
|
///
|
||||||
|
/// - Note: In a dev checkout the source is the build dir under `~/Documents`,
|
||||||
|
/// so the one-time copy still reads that gated folder; every subsequent
|
||||||
|
/// launch reuses the staged copy and reads only App Support. A shipped app
|
||||||
|
/// whose `Resources/LyrebirdArtifacts` is populated never reads a gated
|
||||||
|
/// folder at all.
|
||||||
|
@discardableResult
|
||||||
|
public static func stageArtifacts(
|
||||||
|
from source: URL? = nil,
|
||||||
|
to destination: URL? = nil
|
||||||
|
) -> URL? {
|
||||||
|
guard let dest: URL = destination ?? stagedArtifactsDir() else { return nil }
|
||||||
|
guard let src: URL = source ?? artifactSourceDir() else { return nil }
|
||||||
|
do {
|
||||||
|
try stageArtifactsThrowing(from: src, to: dest)
|
||||||
|
} catch {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return isArtifactsDirPopulated(dest) ? dest : nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Implementation
|
||||||
|
|
||||||
|
static let stageReceiptName: String = ".stage-receipt"
|
||||||
|
|
||||||
|
/// Slack in the receipt-vs-source stamp comparison. A `Date` stores seconds
|
||||||
|
/// since 2001; the receipt records `timeIntervalSince1970`, so reconstructing
|
||||||
|
/// it adds then subtracts the ~978-million-second epoch offset — floating-
|
||||||
|
/// point arithmetic at that magnitude perturbs the sub-second fraction, so a
|
||||||
|
/// bit-exact `>=` can spuriously read "stale" (the string encoding itself is
|
||||||
|
/// exact; the loss is in the epoch conversion, not the receipt). mtime
|
||||||
|
/// staleness needs no sub-second resolution — a rebuild moves mtimes by far
|
||||||
|
/// more than a second.
|
||||||
|
private static let stageStampToleranceSeconds: TimeInterval = 1.0
|
||||||
|
|
||||||
|
/// Whether a staged dir at `dest` is current relative to the artifact source
|
||||||
|
/// it would stage from. When no source is discoverable (a shipped app with no
|
||||||
|
/// build dir and no bundled artifacts), any populated staged dir is trusted.
|
||||||
|
/// Otherwise the receipt must be at or after the source's newest artifact —
|
||||||
|
/// so a staged copy left by a *different* build (or a partial stage that never
|
||||||
|
/// wrote a receipt) is ignored and the resolver falls back to the build dir.
|
||||||
|
/// Compared against ``artifactSourceDir()`` (not the build dir directly) so
|
||||||
|
/// the base matches what ``stageArtifacts(from:to:)`` actually copies from.
|
||||||
|
static func stagedDirIsCurrent(_ dest: URL) -> Bool {
|
||||||
|
guard let source: URL = artifactSourceDir() else { return true }
|
||||||
|
guard let prior: Date = stageReceiptDate(dest.appendingPathComponent(stageReceiptName, isDirectory: false))
|
||||||
|
else { return false }
|
||||||
|
return prior.timeIntervalSince1970 >= sourceArtifactStamp(source).timeIntervalSince1970 - stageStampToleranceSeconds
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func stageArtifactsThrowing(from src: URL, to dest: URL) throws {
|
||||||
|
let fm: FileManager = FileManager.default
|
||||||
|
let srcStamp: Date = sourceArtifactStamp(src)
|
||||||
|
|
||||||
|
// Up to date? A populated dest whose receipt is at or after the source's
|
||||||
|
// newest artifact mtime needs no re-copy.
|
||||||
|
if isArtifactsDirPopulated(dest),
|
||||||
|
let prior: Date = stageReceiptDate(dest.appendingPathComponent(stageReceiptName, isDirectory: false)),
|
||||||
|
prior.timeIntervalSince1970 >= srcStamp.timeIntervalSince1970 - stageStampToleranceSeconds {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refuse to clobber a directory we did not create: an existing, non-empty
|
||||||
|
// `dest` must look like a prior staging root (a receipt or a `Modules/`
|
||||||
|
// dir) before we replace it. Guards a typo'd `to:` from wiping real data.
|
||||||
|
if fm.fileExists(atPath: dest.path), !isReplaceableStagingDest(dest) {
|
||||||
|
throw ArtifactStagingError.destinationNotAStagingRoot(dest.path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build everything in a private sibling temp dir, then atomically swap it
|
||||||
|
// over `dest`. `dest` is therefore only ever fully-complete or absent — a
|
||||||
|
// failed/partial stage never leaves a dir that *looks* valid, and two
|
||||||
|
// stagers racing the same `dest` can't observe a half-written tree.
|
||||||
|
let staging: URL = dest.deletingLastPathComponent()
|
||||||
|
.appendingPathComponent(".\(dest.lastPathComponent).staging-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
try fm.createDirectory(at: staging, withIntermediateDirectories: true)
|
||||||
|
defer { try? fm.removeItem(at: staging) }
|
||||||
|
|
||||||
|
// 1. Swift modules.
|
||||||
|
let srcModules: URL = src.appendingPathComponent("Modules", isDirectory: true)
|
||||||
|
if fm.fileExists(atPath: srcModules.path) {
|
||||||
|
try fm.copyItem(at: srcModules, to: staging.appendingPathComponent("Modules", isDirectory: true))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Lyrebird dylibs (the snippet links these and bakes an rpath here;
|
||||||
|
// at dlopen dyld matches the already-loaded install name, so the copy is
|
||||||
|
// a link-time search target, not a second loaded image).
|
||||||
|
for dylib: URL in lyrebirdDylibs(in: src) {
|
||||||
|
try? fm.copyItem(at: dylib, to: staging.appendingPathComponent(dylib.lastPathComponent))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.5. Self-contained C-shim module dirs (`<Module>.build/` holding a
|
||||||
|
// `module.modulemap` whose header path is relative to the map — as shipped
|
||||||
|
// in the app bundle's LyrebirdArtifacts). Copy the whole dir verbatim so the
|
||||||
|
// relative header resolves at the staged location; no path rewrite needed.
|
||||||
|
// (The absolute-`umbrella header` dev-build maps are handled separately in
|
||||||
|
// step 3 — a relative-header map is skipped there, so no double-write.)
|
||||||
|
copySelfContainedModuleMapDirs(from: src, writeInto: staging)
|
||||||
|
|
||||||
|
// 3. C module maps + their umbrella headers. Files are written under the
|
||||||
|
// temp `staging` dir, but the umbrella path baked into each map must
|
||||||
|
// reference the FINAL `dest` (where they land after the atomic swap) —
|
||||||
|
// the temp dir is deleted.
|
||||||
|
stageClangModuleMaps(from: src, writeInto: staging, finalRoot: dest)
|
||||||
|
|
||||||
|
// Receipt: store the source stamp so the next call can skip an unchanged
|
||||||
|
// source.
|
||||||
|
let stampText: String = String(srcStamp.timeIntervalSince1970)
|
||||||
|
try stampText.write(
|
||||||
|
to: staging.appendingPathComponent(stageReceiptName, isDirectory: false),
|
||||||
|
atomically: true,
|
||||||
|
encoding: .utf8
|
||||||
|
)
|
||||||
|
|
||||||
|
// Re-check the clobber guard immediately before the swap: the copy phase
|
||||||
|
// above is a window in which something could have materialized a
|
||||||
|
// non-staging directory at `dest`. Holding the guard across the whole
|
||||||
|
// operation, not just at entry, keeps `replaceItemAt` from silently
|
||||||
|
// wiping a dir we would have refused.
|
||||||
|
if fm.fileExists(atPath: dest.path), !isReplaceableStagingDest(dest) {
|
||||||
|
throw ArtifactStagingError.destinationNotAStagingRoot(dest.path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Atomic swap into place.
|
||||||
|
if fm.fileExists(atPath: dest.path) {
|
||||||
|
_ = try fm.replaceItemAt(dest, withItemAt: staging)
|
||||||
|
} else {
|
||||||
|
try fm.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||||
|
do {
|
||||||
|
try fm.moveItem(at: staging, to: dest)
|
||||||
|
} catch {
|
||||||
|
// A concurrent stager may have created `dest` between the check
|
||||||
|
// and the move; if it is now a valid root, treat as success.
|
||||||
|
guard isArtifactsDirPopulated(dest) else { throw error }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Lyrebird dylibs present at the top level of `src`.
|
||||||
|
private static func lyrebirdDylibs(in src: URL) -> [URL] {
|
||||||
|
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
|
||||||
|
at: src,
|
||||||
|
includingPropertiesForKeys: nil
|
||||||
|
) else { return [] }
|
||||||
|
return entries.filter {
|
||||||
|
$0.pathExtension == "dylib" && $0.lastPathComponent.hasPrefix("libLyrebird")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `dest` is safe to replace when it doesn't exist, is empty, or looks like
|
||||||
|
/// a prior staging root (has a receipt or a `Modules/` dir).
|
||||||
|
private static func isReplaceableStagingDest(_ dest: URL) -> Bool {
|
||||||
|
let fm: FileManager = FileManager.default
|
||||||
|
guard fm.fileExists(atPath: dest.path) else { return true }
|
||||||
|
if fm.fileExists(atPath: dest.appendingPathComponent(stageReceiptName).path) { return true }
|
||||||
|
if fm.fileExists(atPath: dest.appendingPathComponent("Modules").path) { return true }
|
||||||
|
let contents: [URL] = (try? fm.contentsOfDirectory(at: dest, includingPropertiesForKeys: nil)) ?? []
|
||||||
|
return contents.isEmpty
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For each `<Module>.build/module.modulemap` under `src` whose umbrella
|
||||||
|
/// header exists, copy the header's `include` directory into
|
||||||
|
/// `writeInto/<Module>.headers` and write a staged map whose umbrella path
|
||||||
|
/// points at `finalRoot/<Module>.headers/<header>` — the location those files
|
||||||
|
/// occupy after the caller's atomic swap of `writeInto` onto `finalRoot`.
|
||||||
|
/// Best-effort per map: a map with no resolvable umbrella header, or one that
|
||||||
|
/// fails to copy, is skipped without aborting the rest.
|
||||||
|
/// Copy each `<Module>.build/` directory under `src` that holds a
|
||||||
|
/// `module.modulemap` **without** an `umbrella header` directive — i.e. a
|
||||||
|
/// self-contained map whose `header "…"` path is relative to the map's own
|
||||||
|
/// directory (as bundled in the app's `LyrebirdArtifacts`). The whole dir is
|
||||||
|
/// copied verbatim (map + adjacent headers), so the relative path resolves at
|
||||||
|
/// the staged location and `discoverSPMModuleMaps` finds the copied map. Maps
|
||||||
|
/// with an absolute `umbrella header` are left for ``stageClangModuleMaps``.
|
||||||
|
private static func copySelfContainedModuleMapDirs(from src: URL, writeInto staging: URL) {
|
||||||
|
let fm: FileManager = FileManager.default
|
||||||
|
guard let entries: [URL] = try? fm.contentsOfDirectory(
|
||||||
|
at: src,
|
||||||
|
includingPropertiesForKeys: nil
|
||||||
|
) else { return }
|
||||||
|
|
||||||
|
for buildDir: URL in entries where buildDir.pathExtension == "build" {
|
||||||
|
let map: URL = buildDir.appendingPathComponent("module.modulemap", isDirectory: false)
|
||||||
|
guard fm.fileExists(atPath: map.path),
|
||||||
|
let text: String = try? String(contentsOf: map, encoding: .utf8),
|
||||||
|
umbrellaHeaderPath(in: text) == nil // self-contained (relative header) only
|
||||||
|
else { continue }
|
||||||
|
let stagedDir: URL = staging.appendingPathComponent(buildDir.lastPathComponent, isDirectory: true)
|
||||||
|
try? fm.removeItem(at: stagedDir)
|
||||||
|
try? fm.copyItem(at: buildDir, to: stagedDir)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func stageClangModuleMaps(from src: URL, writeInto staging: URL, finalRoot dest: URL) {
|
||||||
|
let fm: FileManager = FileManager.default
|
||||||
|
guard let entries: [URL] = try? fm.contentsOfDirectory(
|
||||||
|
at: src,
|
||||||
|
includingPropertiesForKeys: nil
|
||||||
|
) else { return }
|
||||||
|
|
||||||
|
for buildDir: URL in entries where buildDir.pathExtension == "build" {
|
||||||
|
let map: URL = buildDir.appendingPathComponent("module.modulemap", isDirectory: false)
|
||||||
|
guard fm.fileExists(atPath: map.path),
|
||||||
|
let text: String = try? String(contentsOf: map, encoding: .utf8),
|
||||||
|
let umbrella: String = umbrellaHeaderPath(in: text)
|
||||||
|
else { continue }
|
||||||
|
|
||||||
|
let headerURL: URL = URL(fileURLWithPath: umbrella)
|
||||||
|
guard fm.fileExists(atPath: headerURL.path) else { continue }
|
||||||
|
|
||||||
|
let includeDir: URL = headerURL.deletingLastPathComponent()
|
||||||
|
let moduleName: String = buildDir.deletingPathExtension().lastPathComponent
|
||||||
|
let headerName: String = headerURL.lastPathComponent
|
||||||
|
// Files go under the temp staging dir…
|
||||||
|
let stagedHeaders: URL = staging.appendingPathComponent("\(moduleName).headers", isDirectory: true)
|
||||||
|
let stagedMapDir: URL = staging.appendingPathComponent(buildDir.lastPathComponent, isDirectory: true)
|
||||||
|
// …but the baked umbrella path names their final resting place.
|
||||||
|
let finalHeader: URL = dest
|
||||||
|
.appendingPathComponent("\(moduleName).headers", isDirectory: true)
|
||||||
|
.appendingPathComponent(headerName, isDirectory: false)
|
||||||
|
let rewritten: String = text.replacingOccurrences(of: umbrella, with: finalHeader.path)
|
||||||
|
do {
|
||||||
|
try? fm.removeItem(at: stagedHeaders)
|
||||||
|
try fm.copyItem(at: includeDir, to: stagedHeaders)
|
||||||
|
try fm.createDirectory(at: stagedMapDir, withIntermediateDirectories: true)
|
||||||
|
try rewritten.write(
|
||||||
|
to: stagedMapDir.appendingPathComponent("module.modulemap", isDirectory: false),
|
||||||
|
atomically: true,
|
||||||
|
encoding: .utf8
|
||||||
|
)
|
||||||
|
} catch {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract the path inside `umbrella header "..."` from a Clang module map.
|
||||||
|
static func umbrellaHeaderPath(in modulemap: String) -> String? {
|
||||||
|
guard let marker: Range<String.Index> = modulemap.range(of: "umbrella header") else { return nil }
|
||||||
|
let after: Substring = modulemap[marker.upperBound...]
|
||||||
|
guard let open: String.Index = after.firstIndex(of: "\"") else { return nil }
|
||||||
|
let afterOpen: Substring = after[after.index(after: open)...]
|
||||||
|
guard let close: String.Index = afterOpen.firstIndex(of: "\"") else { return nil }
|
||||||
|
return String(afterOpen[..<close])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Newest modification date among the artifacts we actually copy — a cheap
|
||||||
|
/// staleness proxy that avoids walking the whole build tree. Derives the
|
||||||
|
/// dylib set from the same wildcard scan the copy step uses, so a new/renamed
|
||||||
|
/// Lyrebird dylib can't slip past the freshness check.
|
||||||
|
///
|
||||||
|
/// It does not probe the C module map or its umbrella header directly: a
|
||||||
|
/// header edit forces `swift build` to rebuild the downstream swiftmodules
|
||||||
|
/// too, which moves `Modules/`'s mtime — so a header change is caught
|
||||||
|
/// transitively. (A hand-edited header with no rebuild would not re-stage,
|
||||||
|
/// but that state never occurs from a normal build.)
|
||||||
|
private static func sourceArtifactStamp(_ src: URL) -> Date {
|
||||||
|
let fm: FileManager = FileManager.default
|
||||||
|
var newest: Date = Date.distantPast
|
||||||
|
var probes: [URL] = [src.appendingPathComponent("Modules", isDirectory: true)]
|
||||||
|
probes += lyrebirdDylibs(in: src)
|
||||||
|
for probe: URL in probes {
|
||||||
|
if let attrs: [FileAttributeKey: Any] = try? fm.attributesOfItem(atPath: probe.path),
|
||||||
|
let date: Date = attrs[.modificationDate] as? Date,
|
||||||
|
date > newest {
|
||||||
|
newest = date
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return newest
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func stageReceiptDate(_ receipt: URL) -> Date? {
|
||||||
|
guard let text: String = try? String(contentsOf: receipt, encoding: .utf8),
|
||||||
|
let interval: TimeInterval = TimeInterval(text.trimmingCharacters(in: .whitespacesAndNewlines))
|
||||||
|
else { return nil }
|
||||||
|
return Date(timeIntervalSince1970: interval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -23,6 +23,12 @@ public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
|
|||||||
/// missing entry symbol, IO failure.
|
/// missing entry symbol, IO failure.
|
||||||
case compilerError(LiveCompileError)
|
case compilerError(LiveCompileError)
|
||||||
|
|
||||||
|
/// The interpreted graph-DSL failed to lex/parse/build or its graphs were
|
||||||
|
/// rejected by the engine. `diagnostics` are already mapped to user-source
|
||||||
|
/// coordinates (a parse error resolves to a line/column; a build error has
|
||||||
|
/// `line: nil`). No swiftc is involved — this is the instant DSL path.
|
||||||
|
case graphDSLFailed(diagnostics: [Diagnostic], underlying: Error)
|
||||||
|
|
||||||
public var description: String {
|
public var description: String {
|
||||||
switch self {
|
switch self {
|
||||||
case .snippetCompileFailed(let diagnostics, let underlying):
|
case .snippetCompileFailed(let diagnostics, let underlying):
|
||||||
@@ -36,6 +42,15 @@ public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
|
|||||||
return "snippet compile failed:\n\(summary)"
|
return "snippet compile failed:\n\(summary)"
|
||||||
case .compilerError(let underlying):
|
case .compilerError(let underlying):
|
||||||
return "live compile error: \(underlying)"
|
return "live compile error: \(underlying)"
|
||||||
|
case .graphDSLFailed(let diagnostics, let underlying):
|
||||||
|
if diagnostics.isEmpty {
|
||||||
|
return "graph DSL failed:\n\(underlying)"
|
||||||
|
}
|
||||||
|
let summary: String = diagnostics.map { diag -> String in
|
||||||
|
let location: String = diag.line.map { "\($0):\(diag.column)" } ?? "?"
|
||||||
|
return "\(location) \(diag.severity.rawValue): \(diag.message)"
|
||||||
|
}.joined(separator: "\n")
|
||||||
|
return "graph DSL failed:\n\(summary)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
// LiveSessionGraphDSL.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdLiveCompile
|
||||||
|
//
|
||||||
|
// The editor's instant, no-swiftc evaluation path. `runGraphDSL` lexes, parses,
|
||||||
|
// and builds interpreted graph-DSL source into `ClosureSynthesizer`s and plays
|
||||||
|
// them through the SAME tracking + named-slot machinery `compileAndRun` uses, so
|
||||||
|
// non-additive re-evaluation, slot hot-swap, and `resetAll()` behave identically
|
||||||
|
// across the Swift and DSL paths. The only difference is speed: a graph edit
|
||||||
|
// re-evaluates in microseconds instead of a swiftc round-trip.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdGraphDSLEmbedded
|
||||||
|
|
||||||
|
extension LiveSession {
|
||||||
|
|
||||||
|
/// Evaluate interpreted graph-DSL `source` and play each statement.
|
||||||
|
///
|
||||||
|
/// Mirrors ``compileAndRun(_:additive:)`` but with no compiler: the source is
|
||||||
|
/// interpreted in-process. Each statement becomes one output —
|
||||||
|
///
|
||||||
|
/// - an anonymous statement (`OscSin(freq: 440) * 0.1`) is added to the
|
||||||
|
/// engine and tracked, so a later non-additive run removes it;
|
||||||
|
/// - a named statement (`bass = OscSawtooth(freq: 55) * 0.2`) is installed into
|
||||||
|
/// the matching named slot via ``swapSlot(_:synth:)`` — a persistent,
|
||||||
|
/// hot-swappable voice that survives a non-additive re-evaluation and is
|
||||||
|
/// replaced in place on the next run.
|
||||||
|
///
|
||||||
|
/// The whole program is lexed/parsed/built **before** any engine mutation, so
|
||||||
|
/// a syntax or build error leaves the currently-playing graph untouched — a
|
||||||
|
/// *malformed* edit never drops audio. Once the program is valid, playback is
|
||||||
|
/// best-effort per statement: an engine-level rejection of one statement
|
||||||
|
/// (e.g. `.pendingQueueFull`) is collected and surfaced but does not abort
|
||||||
|
/// the others, matching ``SnippetContext/play(_:)``.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - source: DSL program text (one statement per line).
|
||||||
|
/// - additive: When `false` (default), removes every previously tracked
|
||||||
|
/// anonymous synth before playing (named slots persist). When `true`,
|
||||||
|
/// leaves prior synths in place.
|
||||||
|
/// - resources: Host resource table resolving bare-identifier references
|
||||||
|
/// (e.g. buffers). Defaults to an empty table.
|
||||||
|
/// - Throws: ``LiveSessionError/graphDSLFailed(diagnostics:underlying:)`` with
|
||||||
|
/// editor-ready diagnostics for a lex/parse/build failure (before any
|
||||||
|
/// mutation), or for one or more per-statement engine rejections (after the
|
||||||
|
/// surviving statements have gone live).
|
||||||
|
@MainActor
|
||||||
|
public func runGraphDSL(
|
||||||
|
_ source: String,
|
||||||
|
additive: Bool = false,
|
||||||
|
resources: DSLResourceResolver = DSLEmptyResources()
|
||||||
|
) throws {
|
||||||
|
// Build everything first — no engine mutation until we know the whole
|
||||||
|
// program is valid.
|
||||||
|
let outputs: [DSLOutput]
|
||||||
|
do {
|
||||||
|
outputs = try DSLInterpreter.evaluate(source, resources: resources)
|
||||||
|
} catch {
|
||||||
|
throw LiveSessionError.graphDSLFailed(
|
||||||
|
diagnostics: GraphDSLDiagnosticMapper.diagnostics(for: error, source: source),
|
||||||
|
underlying: error
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !additive { clearTracked() }
|
||||||
|
|
||||||
|
// Play every statement. An engine-level rejection of ONE statement
|
||||||
|
// (e.g. `.pendingQueueFull`) must not abort the rest — the others still
|
||||||
|
// go live, mirroring `SnippetContext.play`'s per-statement best-effort
|
||||||
|
// behavior. Failures are collected and surfaced together; the graphs
|
||||||
|
// that added successfully keep playing.
|
||||||
|
var failures: [Diagnostic] = []
|
||||||
|
var firstError: Error?
|
||||||
|
for output: DSLOutput in outputs {
|
||||||
|
let synth: ClosureSynthesizer = ClosureSynthesizer {
|
||||||
|
// The graph is already built (eagerly, by the interpreter); the
|
||||||
|
// closure just hands it to `build()`. Each `DSLOutput.graph` is
|
||||||
|
// owned by exactly one synth, so this never shares a graph.
|
||||||
|
output.graph
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
if let slot: String = output.slot {
|
||||||
|
try swapSlot(slot, synth: synth)
|
||||||
|
} else {
|
||||||
|
try engine.add(synth)
|
||||||
|
track(synth)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
if firstError == nil { firstError = error }
|
||||||
|
failures.append(contentsOf: GraphDSLDiagnosticMapper.diagnostics(for: error, source: source))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let firstError: Error = firstError {
|
||||||
|
throw LiveSessionError.graphDSLFailed(diagnostics: failures, underlying: firstError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
// SnippetCompletionService.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdLiveCompile
|
||||||
|
//
|
||||||
|
// Bridges the live-coding editor to `sourcekit-lsp` (via ``SourceKitLSPClient``)
|
||||||
|
// so the user gets real Swift code completion — the same symbols the snippet
|
||||||
|
// would see at compile time (`context`, `LyrebirdSynth` generators, …).
|
||||||
|
//
|
||||||
|
// It maintains a small on-disk workspace: the snippet is written WRAPPED in the
|
||||||
|
// same `SnippetHarness` preamble the compiler uses, next to a
|
||||||
|
// `compile_commands.json` carrying the module-resolution flags derived from the
|
||||||
|
// host `LiveSession`. sourcekit-lsp's compilation-database build system reads
|
||||||
|
// that file, which is what lets `import LyrebirdSynth` and the injected
|
||||||
|
// `context: SnippetContext` resolve for an otherwise free-standing file.
|
||||||
|
//
|
||||||
|
// macOS only.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Provides code completion for a live-coding editor buffer.
|
||||||
|
public actor SnippetCompletionService {
|
||||||
|
|
||||||
|
private let _client: SourceKitLSPClient
|
||||||
|
private let _session: LiveSession
|
||||||
|
private let _workspace: URL
|
||||||
|
private let _fileURL: URL
|
||||||
|
private let _fileURI: String
|
||||||
|
|
||||||
|
// Version counter for `didChange`, and the offset (from the last wrap) that
|
||||||
|
// maps a user-body line to its line in the wrapped document.
|
||||||
|
private var _version: Int = 1
|
||||||
|
private var _userBodyLineOffset: Int = 1
|
||||||
|
private var _started: Bool = false
|
||||||
|
|
||||||
|
/// - Parameters:
|
||||||
|
/// - session: Host session whose `importPaths` / `librarySearchPaths` /
|
||||||
|
/// `libraries` are reused verbatim, so completion sees exactly the
|
||||||
|
/// modules the real compile links.
|
||||||
|
/// - client: LSP client to drive (injectable for tests).
|
||||||
|
public init(
|
||||||
|
session: LiveSession,
|
||||||
|
client: SourceKitLSPClient = SourceKitLSPClient()
|
||||||
|
) {
|
||||||
|
self._client = client
|
||||||
|
self._session = session
|
||||||
|
// URL computation only — no filesystem or subprocess I/O here, so the
|
||||||
|
// synchronous init never blocks its caller (the @MainActor model).
|
||||||
|
self._workspace = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("lyrebird-completion-" + UUID().uuidString, isDirectory: true)
|
||||||
|
self._fileURL = _workspace.appendingPathComponent("snippet.swift")
|
||||||
|
self._fileURI = "file://" + _fileURL.path
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create the workspace directory, a seed snippet file, and the
|
||||||
|
/// `compile_commands.json` describing how to compile it. Runs on the actor
|
||||||
|
/// executor (off the main thread) — it shells out to `xcrun` for the SDK
|
||||||
|
/// path, which must not block the UI.
|
||||||
|
private func _writeWorkspace() {
|
||||||
|
try? FileManager.default.createDirectory(at: _workspace, withIntermediateDirectories: true)
|
||||||
|
let seed: WrappedSnippet = SnippetHarness.wrap(userBody: "\n")
|
||||||
|
try? seed.source.write(to: _fileURL, atomically: true, encoding: .utf8)
|
||||||
|
|
||||||
|
let arguments: [String] = SnippetCompletionService.compileArguments(
|
||||||
|
session: _session, file: _fileURL.path)
|
||||||
|
let entry: [String: Any] = [
|
||||||
|
"directory": _workspace.path,
|
||||||
|
"file": _fileURL.path,
|
||||||
|
"arguments": arguments
|
||||||
|
]
|
||||||
|
if let data: Data = try? JSONSerialization.data(withJSONObject: [entry], options: [.prettyPrinted]) {
|
||||||
|
try? data.write(to: _workspace.appendingPathComponent("compile_commands.json"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build the swiftc invocation for the compilation database: the `-I`
|
||||||
|
/// module paths, C-target module maps, and link flags from `session`, plus
|
||||||
|
/// the explicit `-sdk` / `-target` sourcekit-lsp needs for a free-standing
|
||||||
|
/// file (swiftc infers those during a normal build, but the LSP does not).
|
||||||
|
static func compileArguments(session: LiveSession, file: String) -> [String] {
|
||||||
|
var args: [String] = ["swiftc", file]
|
||||||
|
for path: URL in session.importPaths {
|
||||||
|
args += ["-I", path.path]
|
||||||
|
}
|
||||||
|
for url: URL in LiveSession.discoverClangModuleMaps(in: session.importPaths) {
|
||||||
|
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||||
|
}
|
||||||
|
for url: URL in LiveSession.discoverSPMModuleMaps(in: session.importPaths) {
|
||||||
|
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||||
|
}
|
||||||
|
for path: URL in session.librarySearchPaths {
|
||||||
|
args += ["-L", path.path]
|
||||||
|
}
|
||||||
|
for lib: String in session.libraries {
|
||||||
|
args += ["-l\(lib)"]
|
||||||
|
}
|
||||||
|
if let sdk: String = sdkPath() {
|
||||||
|
args += ["-sdk", sdk]
|
||||||
|
}
|
||||||
|
args += ["-target", targetTriple()]
|
||||||
|
return args
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func sdkPath() -> String? {
|
||||||
|
let p: Process = Process()
|
||||||
|
p.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
|
||||||
|
p.arguments = ["--show-sdk-path", "--sdk", "macosx"]
|
||||||
|
let out: Pipe = Pipe()
|
||||||
|
p.standardOutput = out
|
||||||
|
p.standardError = Pipe()
|
||||||
|
try? p.run()
|
||||||
|
p.waitUntilExit()
|
||||||
|
let data: Data = out.fileHandleForReading.readDataToEndOfFile()
|
||||||
|
let path: String? = String(data: data, encoding: .utf8)?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
return (path?.isEmpty == false) ? path : nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Minimum-deployment target triple. Arch matches the running process;
|
||||||
|
/// the OS floor matches the package's `macOS 15` minimum.
|
||||||
|
private static func targetTriple() -> String {
|
||||||
|
#if arch(arm64)
|
||||||
|
let arch: String = "arm64"
|
||||||
|
#else
|
||||||
|
let arch: String = "x86_64"
|
||||||
|
#endif
|
||||||
|
return "\(arch)-apple-macosx15.0"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Launch sourcekit-lsp and open the (empty) document. Call once before the
|
||||||
|
/// first ``completions(userBody:line:character:)``. Idempotent.
|
||||||
|
public func start() async throws {
|
||||||
|
guard !_started else { return }
|
||||||
|
// Build the workspace (SDK lookup + file writes) here, on the actor
|
||||||
|
// executor, so the blocking `xcrun` call never lands on the main thread.
|
||||||
|
_writeWorkspace()
|
||||||
|
try await _client.start(rootURI: "file://" + _workspace.path)
|
||||||
|
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: "\n")
|
||||||
|
_userBodyLineOffset = wrapped.userBodyLineOffset
|
||||||
|
_client.didOpen(uri: _fileURI, text: wrapped.source, version: _version)
|
||||||
|
_started = true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request completions for `userBody` at the user-space `line` / `character`
|
||||||
|
/// (both zero-based, in the user's own text — not the wrapped document).
|
||||||
|
///
|
||||||
|
/// The body is re-synced to the server first, then the cursor is mapped
|
||||||
|
/// through the harness offset into the wrapped document.
|
||||||
|
public func completions(userBody: String, line: Int, character: Int) async throws -> [LSPCompletionItem] {
|
||||||
|
if !_started { try await start() }
|
||||||
|
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody)
|
||||||
|
_userBodyLineOffset = wrapped.userBodyLineOffset
|
||||||
|
_version += 1
|
||||||
|
_client.didChange(uri: _fileURI, text: wrapped.source, version: _version)
|
||||||
|
// User line 0 sits at wrapped line `userBodyLineOffset - 1` (0-based);
|
||||||
|
// the column is unchanged (the preamble adds only whole lines).
|
||||||
|
let wrappedLine: Int = line + (_userBodyLineOffset - 1)
|
||||||
|
return try await _client.completion(uri: _fileURI, line: wrappedLine, character: character)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shut down the server and remove the workspace. Safe to call more than once.
|
||||||
|
public func stop() {
|
||||||
|
shutdownSynchronously()
|
||||||
|
_started = false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Synchronous teardown usable from `deinit` and non-async contexts (a test
|
||||||
|
/// `defer`): terminate the LSP client and delete the temp workspace. Touches
|
||||||
|
/// only `let` members, so it is safe to run `nonisolated`. Idempotent.
|
||||||
|
public nonisolated func shutdownSynchronously() {
|
||||||
|
_client.shutdown()
|
||||||
|
try? FileManager.default.removeItem(at: _workspace)
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
shutdownSynchronously()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -43,11 +43,134 @@ public final class SnippetContext {
|
|||||||
session.track(synth)
|
session.track(synth)
|
||||||
return true
|
return true
|
||||||
} catch {
|
} catch {
|
||||||
session.lastSnippetMessage = "engine.add failed: \(error)"
|
session.appendMessage("engine.add failed: \(error)")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Play `synth` into a **named slot**, replacing whatever synth was there
|
||||||
|
/// before — the `Pdef`-style hot-swap primitive.
|
||||||
|
///
|
||||||
|
/// Unlike ``play(_:)``, a slotted synth is *not* torn down by the next
|
||||||
|
/// non-additive re-evaluation. Re-running a `play(slot:)` for the same name
|
||||||
|
/// swaps that one voice in place (the new voice starts before the old is
|
||||||
|
/// removed — a brief overlap, no gap), while other slots keep playing.
|
||||||
|
/// This lets you mutate one voice at a time, live.
|
||||||
|
///
|
||||||
|
/// ```swift
|
||||||
|
/// context.play(slot: "bass") { OscSaw.Audio(freq: 55, mul: 0.2) }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Clear a slot with `context.session.clearSlot("bass")`, or all slots with
|
||||||
|
/// `context.session.clearSlots()`.
|
||||||
|
///
|
||||||
|
/// The swap is immediate by default, or quantized to the next beat/bar when
|
||||||
|
/// the session has a ``LiveSession/swapClock`` and a non-`.immediate`
|
||||||
|
/// ``LiveSession/swapQuantize`` — see ``LiveSession/swapSlot(_:synth:)``.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - name: Slot identifier. Re-using a name replaces that slot's synth.
|
||||||
|
/// - synth: The `Synthesizer` to install.
|
||||||
|
/// - Returns: `true` if the engine accepted the add/schedule; `false` if it
|
||||||
|
/// threw (in which case the prior slot synth is left in place).
|
||||||
|
@discardableResult
|
||||||
|
@MainActor public func play(slot name: String, _ synth: any Synthesizer) -> Bool {
|
||||||
|
do {
|
||||||
|
try session.swapSlot(name, synth: synth)
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
session.appendMessage("play(slot: \"\(name)\") failed: \(error)")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Play a bare generator graph into a **named slot** — the `Pdef`-style
|
||||||
|
/// hot-swap primitive with no `SynthesizerBase` subclass to declare.
|
||||||
|
///
|
||||||
|
/// See ``play(slot:_:)`` for the slot semantics.
|
||||||
|
///
|
||||||
|
/// ```swift
|
||||||
|
/// context.play(slot: "lead") { Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0) }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - name: Slot identifier. Re-using a name replaces that slot's synth.
|
||||||
|
/// - bus: Output bus the graph is written to (multi-channel sources
|
||||||
|
/// continue into following buses). Defaults to `0`.
|
||||||
|
/// - make: Builds and returns the output graph. Called once, inside the
|
||||||
|
/// synthesizer's `build()`.
|
||||||
|
/// - Returns: `true` if the engine accepted the enqueue; `false` otherwise.
|
||||||
|
@discardableResult
|
||||||
|
@MainActor public func play(
|
||||||
|
slot name: String,
|
||||||
|
bus: any ValidBus = 0,
|
||||||
|
_ make: @escaping () -> any ValidGeneratorInput
|
||||||
|
) -> Bool {
|
||||||
|
play(slot: name, ClosureSynthesizer(bus: bus, make))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a bare generator graph to the engine — the fastest path to sound in
|
||||||
|
/// a snippet, with no `SynthesizerBase` subclass to declare.
|
||||||
|
///
|
||||||
|
/// ```swift
|
||||||
|
/// context.play { OscSin.Audio(freq: 440, mul: 0.1) }
|
||||||
|
/// context.play(bus: 0) { Pan2(input: saw, pan: 0) }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Wraps `make` in a ``ClosureSynthesizer`` and forwards to ``play(_:)`` —
|
||||||
|
/// the synth is tracked for cleanup on the next non-additive re-evaluation
|
||||||
|
/// just like any other. Construct the generators inside the closure.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - bus: Output bus the graph is written to (multi-channel sources
|
||||||
|
/// continue into following buses). Defaults to `0`.
|
||||||
|
/// - make: Builds and returns the output graph. Called once, inside the
|
||||||
|
/// synthesizer's `build()`.
|
||||||
|
/// - Returns: `true` if the engine accepted the enqueue; `false` if
|
||||||
|
/// `engine.add` threw.
|
||||||
|
@discardableResult
|
||||||
|
@MainActor public func play(
|
||||||
|
bus: any ValidBus = 0,
|
||||||
|
_ make: @escaping () -> any ValidGeneratorInput
|
||||||
|
) -> Bool {
|
||||||
|
play(ClosureSynthesizer(bus: bus, make))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// **Gracefully release** the voice in a named slot — trigger its envelope
|
||||||
|
/// release phase and let it tail out and free itself — then drop the slot.
|
||||||
|
///
|
||||||
|
/// The live-coding "start a voice, let go of it later" gesture: name a slot
|
||||||
|
/// with ``play(slot:_:)``, then release it from a *separate* evaluation (e.g.
|
||||||
|
/// select the line and hit ⌘E):
|
||||||
|
///
|
||||||
|
/// ```swift
|
||||||
|
/// context.play(slot: "pad") { EnvGen(gate: 1, ...) * OscSaw.Audio(freq: 110) }
|
||||||
|
/// // …later, in another evaluation:
|
||||||
|
/// context.release(slot: "pad")
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// The released voice must free itself (an `EnvGen`/gate with a free-on-done
|
||||||
|
/// action) to leave the engine. For an immediate hard stop instead, use
|
||||||
|
/// ``free(slot:)``.
|
||||||
|
///
|
||||||
|
/// - Parameter name: Slot to release.
|
||||||
|
/// - Returns: `true` if a gated voice was released; `false` if the slot was
|
||||||
|
/// empty or its occupant has no gate.
|
||||||
|
@discardableResult
|
||||||
|
@MainActor public func release(slot name: String) -> Bool {
|
||||||
|
session.releaseSlot(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// **Immediately** stop and remove the voice in a named slot — a hard cut,
|
||||||
|
/// no release tail. The counterpart to ``release(slot:)``.
|
||||||
|
///
|
||||||
|
/// - Parameter name: Slot to free.
|
||||||
|
/// - Returns: `true` if a voice was removed; `false` if the slot was empty.
|
||||||
|
@discardableResult
|
||||||
|
@MainActor public func free(slot name: String) -> Bool {
|
||||||
|
session.clearSlot(name)
|
||||||
|
}
|
||||||
|
|
||||||
/// Snippet-side hook for test verification: report the engine's sample rate
|
/// Snippet-side hook for test verification: report the engine's sample rate
|
||||||
/// back through the session so tests can confirm the `context.engine`
|
/// back through the session so tests can confirm the `context.engine`
|
||||||
/// linkage compiled and called correctly.
|
/// linkage compiled and called correctly.
|
||||||
@@ -58,7 +181,7 @@ public final class SnippetContext {
|
|||||||
/// Snippet-side hook for test verification: record an arbitrary message
|
/// Snippet-side hook for test verification: record an arbitrary message
|
||||||
/// back on the session. Lets tests confirm the snippet body executed.
|
/// back on the session. Lets tests confirm the snippet body executed.
|
||||||
public func reportMessage(_ message: String) {
|
public func reportMessage(_ message: String) {
|
||||||
session.lastSnippetMessage = message
|
session.appendMessage(message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ public enum SnippetHarness {
|
|||||||
/// `compileAndRun` is `@MainActor`).
|
/// `compileAndRun` is `@MainActor`).
|
||||||
public static func wrap(userBody: String) -> WrappedSnippet {
|
public static func wrap(userBody: String) -> WrappedSnippet {
|
||||||
let preamble: String = """
|
let preamble: String = """
|
||||||
|
import Foundation
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
import LyrebirdLiveCompile
|
import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,413 @@
|
|||||||
|
// SourceKitLSPClient.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdLiveCompile
|
||||||
|
//
|
||||||
|
// A minimal LSP JSON-RPC client that drives the toolchain's `sourcekit-lsp`
|
||||||
|
// executable over stdio to provide Swift code completion for the live-coding
|
||||||
|
// editor. Only the handful of requests the editor needs are implemented:
|
||||||
|
// `initialize` / `initialized`, `textDocument/didOpen` / `didChange`, and
|
||||||
|
// `textDocument/completion`.
|
||||||
|
//
|
||||||
|
// macOS only — the whole live-compile surface shells out to the toolchain.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Nanoseconds in one second — for `Task.sleep`.
|
||||||
|
private let nanosecondsPerSecond: Double = 1_000_000_000
|
||||||
|
|
||||||
|
/// Drives `sourcekit-lsp` over stdio.
|
||||||
|
///
|
||||||
|
/// `@unchecked Sendable`: the process handles and the pending-request table are
|
||||||
|
/// guarded by `_lock`; a dedicated background reader thread parses framed
|
||||||
|
/// messages and completes the continuations stored under that lock. Public
|
||||||
|
/// methods are `async` and safe to call from any task.
|
||||||
|
public final class SourceKitLSPClient: @unchecked Sendable {
|
||||||
|
|
||||||
|
private let _process: Process = Process()
|
||||||
|
private let _stdin: Pipe = Pipe()
|
||||||
|
private let _stdout: Pipe = Pipe()
|
||||||
|
|
||||||
|
private let _lock: NSLock = NSLock()
|
||||||
|
private var _nextID: Int = 1
|
||||||
|
// Response continuations keyed by request id, completed by the reader thread.
|
||||||
|
// The payload is the raw response-body `Data` (Sendable); callers parse it.
|
||||||
|
private var _pending: [Int: CheckedContinuation<Data, Error>] = [:]
|
||||||
|
private var _running: Bool = false
|
||||||
|
// Accumulates stdout bytes until a full `Content-Length`-framed message is available.
|
||||||
|
private var _readBuffer: Data = Data()
|
||||||
|
|
||||||
|
/// Default request timeout in seconds. Completion should be well under this;
|
||||||
|
/// the ceiling guards against a wedged server.
|
||||||
|
public static let defaultRequestTimeout: TimeInterval = 15.0
|
||||||
|
|
||||||
|
// `nil` = resolve from the toolchain lazily in `start()`. Kept lazy so the
|
||||||
|
// synchronous `init` — evaluated in the caller's isolation, often the main
|
||||||
|
// actor via `SnippetCompletionService`'s default argument — never shells out
|
||||||
|
// to `xcrun`.
|
||||||
|
private let _explicitExecutableURL: URL?
|
||||||
|
private let _launchArguments: [String]
|
||||||
|
private let _requestTimeout: TimeInterval
|
||||||
|
|
||||||
|
/// - Parameters:
|
||||||
|
/// - executableURL: Path to `sourcekit-lsp`. When `nil` (default) it is
|
||||||
|
/// resolved from the toolchain via `xcrun` inside `start()` — not in
|
||||||
|
/// `init`, so construction never blocks its caller.
|
||||||
|
/// - arguments: Launch arguments for the executable (default none).
|
||||||
|
/// - requestTimeout: Per-request ceiling in seconds before ``request`` fails
|
||||||
|
/// with ``SourceKitLSPError/timedOut(method:)``.
|
||||||
|
public init(
|
||||||
|
executableURL: URL? = nil,
|
||||||
|
arguments: [String] = [],
|
||||||
|
requestTimeout: TimeInterval = SourceKitLSPClient.defaultRequestTimeout
|
||||||
|
) {
|
||||||
|
self._explicitExecutableURL = executableURL
|
||||||
|
self._launchArguments = arguments
|
||||||
|
self._requestTimeout = requestTimeout
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
// Safety net: a client dropped without an explicit `shutdown()` would
|
||||||
|
// otherwise orphan the `sourcekit-lsp` subprocess and leave the reader
|
||||||
|
// thread blocked in `availableData`. `shutdown()` is idempotent.
|
||||||
|
shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve `sourcekit-lsp` from the active toolchain via `xcrun`, falling
|
||||||
|
/// back to the conventional Xcode path.
|
||||||
|
private static func resolveExecutable() -> URL {
|
||||||
|
let xcrun: Process = Process()
|
||||||
|
xcrun.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
|
||||||
|
xcrun.arguments = ["--find", "sourcekit-lsp"]
|
||||||
|
let out: Pipe = Pipe()
|
||||||
|
xcrun.standardOutput = out
|
||||||
|
xcrun.standardError = Pipe()
|
||||||
|
try? xcrun.run()
|
||||||
|
xcrun.waitUntilExit()
|
||||||
|
let data: Data = out.fileHandleForReading.readDataToEndOfFile()
|
||||||
|
if let path: String = String(data: data, encoding: .utf8)?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines), !path.isEmpty {
|
||||||
|
return URL(fileURLWithPath: path)
|
||||||
|
}
|
||||||
|
return URL(fileURLWithPath:
|
||||||
|
"/usr/bin/sourcekit-lsp") // last resort; run(...) will surface a launch error
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Lifecycle
|
||||||
|
|
||||||
|
/// Launch the server, run the `initialize` handshake against `rootURI`, and
|
||||||
|
/// send `initialized`. Call once per client — the caller (e.g.
|
||||||
|
/// ``SnippetCompletionService``) guards against a second call; a repeat call
|
||||||
|
/// here would re-`run()` the process. Resolving the executable (an `xcrun`
|
||||||
|
/// lookup when no explicit path was given) happens here, off the constructing
|
||||||
|
/// caller's thread.
|
||||||
|
public func start(rootURI: String) async throws {
|
||||||
|
_process.executableURL = _explicitExecutableURL ?? SourceKitLSPClient.resolveExecutable()
|
||||||
|
_process.arguments = _launchArguments
|
||||||
|
_process.standardInput = _stdin
|
||||||
|
_process.standardOutput = _stdout
|
||||||
|
_process.standardError = Pipe() // discard server logging
|
||||||
|
do {
|
||||||
|
try _process.run()
|
||||||
|
} catch {
|
||||||
|
throw SourceKitLSPError.launchFailed("\(error)")
|
||||||
|
}
|
||||||
|
_setRunning(true)
|
||||||
|
_startReader()
|
||||||
|
|
||||||
|
let params: [String: Any] = [
|
||||||
|
"processId": Int(ProcessInfo.processInfo.processIdentifier),
|
||||||
|
"rootUri": rootURI,
|
||||||
|
"capabilities": [
|
||||||
|
"textDocument": [
|
||||||
|
"completion": [
|
||||||
|
"completionItem": ["snippetSupport": false]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
_ = try await request(method: "initialize", params: params)
|
||||||
|
notify(method: "initialized", params: [:])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Terminate the server. Safe to call multiple times.
|
||||||
|
public func shutdown() {
|
||||||
|
_lock.lock()
|
||||||
|
let wasRunning: Bool = _running
|
||||||
|
_lock.unlock()
|
||||||
|
_failAllPending(with: SourceKitLSPError.notRunning)
|
||||||
|
guard wasRunning else { return }
|
||||||
|
// Send the graceful `exit` while still marked running (`_send` gates on
|
||||||
|
// `_running`), then flip the flag and terminate.
|
||||||
|
notify(method: "exit", params: [:])
|
||||||
|
_setRunning(false)
|
||||||
|
_process.terminate()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove and fail every in-flight request continuation with `error`.
|
||||||
|
/// Under `_lock`, so it never double-resumes against the reader's dispatch.
|
||||||
|
private func _failAllPending(with error: Error) {
|
||||||
|
_lock.lock()
|
||||||
|
let pending: [Int: CheckedContinuation<Data, Error>] = _pending
|
||||||
|
_pending.removeAll()
|
||||||
|
_lock.unlock()
|
||||||
|
for (_, cont): (Int, CheckedContinuation<Data, Error>) in pending {
|
||||||
|
cont.resume(throwing: error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Document sync
|
||||||
|
|
||||||
|
/// Open `text` as a Swift document at `uri`.
|
||||||
|
public func didOpen(uri: String, text: String, version: Int = 1) {
|
||||||
|
notify(method: "textDocument/didOpen", params: [
|
||||||
|
"textDocument": [
|
||||||
|
"uri": uri, "languageId": "swift", "version": version, "text": text
|
||||||
|
]
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replace the full contents of `uri` with `text` (whole-document sync).
|
||||||
|
public func didChange(uri: String, text: String, version: Int) {
|
||||||
|
notify(method: "textDocument/didChange", params: [
|
||||||
|
"textDocument": ["uri": uri, "version": version],
|
||||||
|
"contentChanges": [["text": text]]
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Completion
|
||||||
|
|
||||||
|
/// Request completions at a zero-based `line` / `character` in `uri`.
|
||||||
|
/// Returns the parsed items (possibly empty).
|
||||||
|
public func completion(uri: String, line: Int, character: Int) async throws -> [LSPCompletionItem] {
|
||||||
|
let body: Data = try await request(method: "textDocument/completion", params: [
|
||||||
|
"textDocument": ["uri": uri],
|
||||||
|
"position": ["line": line, "character": character]
|
||||||
|
])
|
||||||
|
let message: [String: Any] = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
|
||||||
|
// The result is either a CompletionList ({ items: [...] }) or a bare
|
||||||
|
// CompletionItem[].
|
||||||
|
let rawItems: [Any]
|
||||||
|
if let dict: [String: Any] = message["result"] as? [String: Any],
|
||||||
|
let items: [Any] = dict["items"] as? [Any] {
|
||||||
|
rawItems = items
|
||||||
|
} else if let arr: [Any] = message["result"] as? [Any] {
|
||||||
|
rawItems = arr
|
||||||
|
} else {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
var out: [LSPCompletionItem] = []
|
||||||
|
out.reserveCapacity(rawItems.count)
|
||||||
|
for case let item as [String: Any] in rawItems {
|
||||||
|
guard let label: String = item["label"] as? String else { continue }
|
||||||
|
let detail: String? = item["detail"] as? String
|
||||||
|
let insert: String = (item["insertText"] as? String)
|
||||||
|
?? (item["filterText"] as? String)
|
||||||
|
?? label
|
||||||
|
let kind: Int? = item["kind"] as? Int
|
||||||
|
let sortText: String? = item["sortText"] as? String
|
||||||
|
out.append(LSPCompletionItem(
|
||||||
|
label: label, detail: detail, insertText: insert, kind: kind, sortText: sortText))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - JSON-RPC plumbing
|
||||||
|
|
||||||
|
// Lock-protected mutations, factored into sync helpers so no `NSLock` call
|
||||||
|
// happens inside an `async` function (forbidden under Swift 6).
|
||||||
|
|
||||||
|
private func _setRunning(_ value: Bool) {
|
||||||
|
_lock.lock(); defer { _lock.unlock() }
|
||||||
|
_running = value
|
||||||
|
}
|
||||||
|
|
||||||
|
private func _isRunning() -> Bool {
|
||||||
|
_lock.lock(); defer { _lock.unlock() }
|
||||||
|
return _running
|
||||||
|
}
|
||||||
|
|
||||||
|
private func _claimRequestID() -> Int? {
|
||||||
|
_lock.lock(); defer { _lock.unlock() }
|
||||||
|
guard _running else { return nil }
|
||||||
|
let id: Int = _nextID; _nextID += 1
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
private func _storePending(_ id: Int, _ cont: CheckedContinuation<Data, Error>) {
|
||||||
|
_lock.lock(); defer { _lock.unlock() }
|
||||||
|
_pending[id] = cont
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove a pending request AND resume its continuation with `error`.
|
||||||
|
/// Resuming is essential: a task-group child suspended on
|
||||||
|
/// `withCheckedThrowingContinuation` is not woken by `cancelAll()`, so
|
||||||
|
/// merely dropping the entry would leave `request(...)`'s group awaiting a
|
||||||
|
/// child that never completes — a deadlock. `removeValue` under `_lock` means
|
||||||
|
/// only one side (this drop, or the reader's dispatch) ever holds the
|
||||||
|
/// continuation, so there is no double-resume.
|
||||||
|
private func _dropPending(_ id: Int, resumingWith error: Error) {
|
||||||
|
_lock.lock()
|
||||||
|
let cont: CheckedContinuation<Data, Error>? = _pending.removeValue(forKey: id)
|
||||||
|
_lock.unlock()
|
||||||
|
cont?.resume(throwing: error)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send a request and await its response body (`Data`). Times out per
|
||||||
|
/// ``requestTimeout``.
|
||||||
|
private func request(method: String, params: [String: Any]) async throws -> Data {
|
||||||
|
guard let id: Int = _claimRequestID() else { throw SourceKitLSPError.notRunning }
|
||||||
|
// Frame the message to `Data` synchronously here so the child task
|
||||||
|
// captures only Sendable state (`framed`, `id`), never the non-Sendable
|
||||||
|
// `[String: Any]` params.
|
||||||
|
guard let framed: Data = _frame(id: id, method: method, params: params) else {
|
||||||
|
throw SourceKitLSPError.serverError(code: -1, message: "could not encode \(method)")
|
||||||
|
}
|
||||||
|
let timeoutSeconds: TimeInterval = _requestTimeout
|
||||||
|
return try await withThrowingTaskGroup(of: Data.self) { group in
|
||||||
|
group.addTask { [weak self] in
|
||||||
|
guard let self: SourceKitLSPClient else { throw SourceKitLSPError.notRunning }
|
||||||
|
return try await withCheckedThrowingContinuation { cont in
|
||||||
|
self._storePending(id, cont)
|
||||||
|
// Close the store-vs-EOF window: if the server died between
|
||||||
|
// `_claimRequestID` and here, the reader already drained the
|
||||||
|
// pending table, so fail this one now instead of waiting for
|
||||||
|
// the timeout. `_dropPending` removes under the lock, so it
|
||||||
|
// can't double-resume against a concurrent reader/shutdown.
|
||||||
|
guard self._isRunning() else {
|
||||||
|
self._dropPending(id, resumingWith: SourceKitLSPError.notRunning)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
self._send(framed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
group.addTask {
|
||||||
|
try await Task.sleep(nanoseconds: UInt64(timeoutSeconds * nanosecondsPerSecond))
|
||||||
|
throw SourceKitLSPError.timedOut(method: method)
|
||||||
|
}
|
||||||
|
defer { group.cancelAll() }
|
||||||
|
do {
|
||||||
|
guard let first: Data = try await group.next() else {
|
||||||
|
throw SourceKitLSPError.timedOut(method: method)
|
||||||
|
}
|
||||||
|
return first
|
||||||
|
} catch {
|
||||||
|
// On timeout / failure, resume and drop the still-pending request
|
||||||
|
// continuation so its child task completes (cancelAll() alone does
|
||||||
|
// not wake a suspended continuation) and the group can return.
|
||||||
|
_dropPending(id, resumingWith: error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func notify(method: String, params: [String: Any]) {
|
||||||
|
if let framed: Data = _frame(id: nil, method: method, params: params) {
|
||||||
|
_send(framed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a `Content-Length`-framed JSON-RPC message. Pure; no shared state.
|
||||||
|
private func _frame(id: Int?, method: String, params: [String: Any]) -> Data? {
|
||||||
|
var payload: [String: Any] = ["jsonrpc": "2.0", "method": method, "params": params]
|
||||||
|
if let id: Int = id { payload["id"] = id }
|
||||||
|
guard let body: Data = try? JSONSerialization.data(withJSONObject: payload) else { return nil }
|
||||||
|
var framed: Data = Data("Content-Length: \(body.count)\r\n\r\n".utf8)
|
||||||
|
framed.append(body)
|
||||||
|
return framed
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write a pre-framed message to the server's stdin, unless shut down.
|
||||||
|
private func _send(_ framed: Data) {
|
||||||
|
_lock.lock()
|
||||||
|
let running: Bool = _running
|
||||||
|
_lock.unlock()
|
||||||
|
guard running else { return }
|
||||||
|
_stdin.fileHandleForWriting.write(framed)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Reader
|
||||||
|
|
||||||
|
private func _startReader() {
|
||||||
|
let handle: FileHandle = _stdout.fileHandleForReading
|
||||||
|
let thread: Thread = Thread { [weak self] in
|
||||||
|
while true {
|
||||||
|
guard let self: SourceKitLSPClient else { return }
|
||||||
|
self._lock.lock(); let running: Bool = self._running; self._lock.unlock()
|
||||||
|
guard running else { return }
|
||||||
|
let chunk: Data = handle.availableData
|
||||||
|
if chunk.isEmpty {
|
||||||
|
// EOF — the server exited. Mark not-running so later `_send`s
|
||||||
|
// don't write to a dead pipe (EPIPE/SIGPIPE), and fail any
|
||||||
|
// in-flight requests instead of letting them hang to timeout.
|
||||||
|
self._setRunning(false)
|
||||||
|
self._failAllPending(with: SourceKitLSPError.notRunning)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
self._lock.lock()
|
||||||
|
self._readBuffer.append(chunk)
|
||||||
|
let bodies: [Data] = self._drainMessagesLocked()
|
||||||
|
self._lock.unlock()
|
||||||
|
for body: Data in bodies {
|
||||||
|
self._dispatch(body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
thread.name = "lyrebird.sourcekit-lsp.reader"
|
||||||
|
thread.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Slice out as many complete `Content-Length`-framed message bodies as are
|
||||||
|
/// buffered, returning each raw JSON body. Caller holds `_lock`.
|
||||||
|
private func _drainMessagesLocked() -> [Data] {
|
||||||
|
var out: [Data] = []
|
||||||
|
let headerTerminator: Data = Data("\r\n\r\n".utf8)
|
||||||
|
while true {
|
||||||
|
guard let headerEnd: Range<Data.Index> = _readBuffer.range(of: headerTerminator) else { break }
|
||||||
|
let header: String = String(data: _readBuffer[_readBuffer.startIndex..<headerEnd.lowerBound],
|
||||||
|
encoding: .utf8) ?? ""
|
||||||
|
var contentLength: Int = 0
|
||||||
|
for line: Substring in header.split(separator: "\r\n") {
|
||||||
|
let parts: [Substring] = line.split(separator: ":", maxSplits: 1)
|
||||||
|
if parts.count == 2, parts[0].trimmingCharacters(in: .whitespaces) == "Content-Length" {
|
||||||
|
contentLength = Int(parts[1].trimmingCharacters(in: .whitespaces)) ?? 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let bodyStart: Data.Index = headerEnd.upperBound
|
||||||
|
let available: Int = _readBuffer.distance(from: bodyStart, to: _readBuffer.endIndex)
|
||||||
|
guard available >= contentLength else { break } // wait for more bytes
|
||||||
|
let bodyEnd: Data.Index = _readBuffer.index(bodyStart, offsetBy: contentLength)
|
||||||
|
out.append(Data(_readBuffer[bodyStart..<bodyEnd]))
|
||||||
|
_readBuffer.removeSubrange(_readBuffer.startIndex..<bodyEnd)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
private func _dispatch(_ body: Data) {
|
||||||
|
guard let message: [String: Any] = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any]
|
||||||
|
else { return }
|
||||||
|
// Only responses (carrying our request id) are of interest; server
|
||||||
|
// notifications (diagnostics, logging) and server→client requests are
|
||||||
|
// ignored. sourcekit-lsp tolerates unanswered server requests here.
|
||||||
|
guard let id: Int = message["id"] as? Int else { return }
|
||||||
|
_lock.lock()
|
||||||
|
let cont: CheckedContinuation<Data, Error>? = _pending.removeValue(forKey: id)
|
||||||
|
_lock.unlock()
|
||||||
|
guard let cont: CheckedContinuation<Data, Error> = cont else { return }
|
||||||
|
|
||||||
|
if let error: [String: Any] = message["error"] as? [String: Any] {
|
||||||
|
let code: Int = error["code"] as? Int ?? 0
|
||||||
|
let msg: String = error["message"] as? String ?? "unknown"
|
||||||
|
cont.resume(throwing: SourceKitLSPError.serverError(code: code, message: msg))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Hand the raw body back; the caller parses `result` for its own shape.
|
||||||
|
cont.resume(returning: body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// SourceKitLSPError.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdLiveCompile
|
||||||
|
//
|
||||||
|
// Errors surfaced by ``SourceKitLSPClient``. macOS only.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
|
||||||
|
/// A failure from the `sourcekit-lsp` client.
|
||||||
|
public enum SourceKitLSPError: Error, CustomStringConvertible {
|
||||||
|
/// The `sourcekit-lsp` executable could not be launched (bad path, missing
|
||||||
|
/// toolchain, spawn failure). Thrown from ``SourceKitLSPClient/start(rootURI:)``.
|
||||||
|
case launchFailed(String)
|
||||||
|
/// A request was made against a client that was never started or has been
|
||||||
|
/// shut down (or the server exited). Also used to fail in-flight requests
|
||||||
|
/// when the server dies.
|
||||||
|
case notRunning
|
||||||
|
/// A request exceeded the client's per-request timeout. Guards against a
|
||||||
|
/// wedged server; carries the LSP method that timed out.
|
||||||
|
case timedOut(method: String)
|
||||||
|
/// The server returned a JSON-RPC error response, carrying its code and
|
||||||
|
/// message.
|
||||||
|
case serverError(code: Int, message: String)
|
||||||
|
|
||||||
|
public var description: String {
|
||||||
|
switch self {
|
||||||
|
case .launchFailed(let m): return "sourcekit-lsp failed to launch: \(m)"
|
||||||
|
case .notRunning: return "sourcekit-lsp is not running"
|
||||||
|
case .timedOut(let m): return "sourcekit-lsp timed out on \(m)"
|
||||||
|
case .serverError(let c, let m): return "sourcekit-lsp error \(c): \(m)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
// SwapQuantize.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdLiveCompile
|
||||||
|
//
|
||||||
|
// `SwapQuantize` chooses when a named-slot swap becomes audible: immediately, or
|
||||||
|
// aligned to the next beat / bar of a `LyrebirdClock`. Quantizing the swap to a
|
||||||
|
// musical boundary is what masks compile latency — the `swiftc` build finishes a
|
||||||
|
// few hundred ms after ⌘↩, then the swap lands exactly on the downbeat rather
|
||||||
|
// than whenever the compile happened to finish.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
|
/// When a ``LiveSession`` named-slot swap becomes audible.
|
||||||
|
///
|
||||||
|
/// Set on ``LiveSession/swapQuantize`` together with a ``LiveSession/swapClock``.
|
||||||
|
/// With no clock, or `.immediate`, a swap takes effect right away. `.nextBeat` /
|
||||||
|
/// `.nextBar` schedule the new voice's add and the old voice's removal at the
|
||||||
|
/// same upcoming boundary sample time, so the swap is glitch-free and on-grid.
|
||||||
|
public enum SwapQuantize: Sendable, Equatable {
|
||||||
|
|
||||||
|
/// Swap immediately, as soon as the snippet runs.
|
||||||
|
case immediate
|
||||||
|
|
||||||
|
/// Swap on the next whole beat boundary.
|
||||||
|
case nextBeat
|
||||||
|
|
||||||
|
/// Swap on the next bar boundary, where a bar is `beatsPerBar` beats.
|
||||||
|
case nextBar(beatsPerBar: Int)
|
||||||
|
|
||||||
|
/// The absolute clock beat this quantization targets from *now*, or `nil`
|
||||||
|
/// for `.immediate`. `.nextBeat` returns the next whole beat; `.nextBar`
|
||||||
|
/// returns the next multiple of `beatsPerBar` beats.
|
||||||
|
///
|
||||||
|
/// Reads `clock.currentBeat` once; the returned beat is strictly in the
|
||||||
|
/// future for a running clock (a whole-numbered current beat rounds up to
|
||||||
|
/// the following boundary, matching `LyrebirdClock.nextBeat`).
|
||||||
|
public func targetBeat(clock: LyrebirdClock) -> Double? {
|
||||||
|
switch self {
|
||||||
|
case .immediate:
|
||||||
|
return nil
|
||||||
|
case .nextBeat:
|
||||||
|
return floor(clock.currentBeat) + 1.0
|
||||||
|
case .nextBar(let beatsPerBar):
|
||||||
|
let bar: Double = Double(max(1, beatsPerBar))
|
||||||
|
return (floor(clock.currentBeat / bar) + 1.0) * bar
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
// SwiftFormatter.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdLiveCompile — snippet source formatting.
|
||||||
|
//
|
||||||
|
// Shells out to the toolchain's `swift-format` (the same way `LiveCompiler`
|
||||||
|
// shells to `swiftc`) to pretty-print a snippet. macOS only — iOS cannot exec
|
||||||
|
// subprocesses. Writes the source to a temp file and runs `swift-format format
|
||||||
|
// <file>`, capturing stdout — avoids the write-stdin/read-stdout pipe deadlock
|
||||||
|
// a streaming approach risks on large output.
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
|
||||||
|
/// Stateless `swift-format` wrapper.
|
||||||
|
public enum SwiftFormatter {
|
||||||
|
|
||||||
|
/// Format `source` and return the pretty-printed result. Runs synchronously
|
||||||
|
/// (spawns `swift-format`); call off the main thread.
|
||||||
|
///
|
||||||
|
/// - Parameter source: Swift source to format. Top-level snippet code is
|
||||||
|
/// accepted — `swift-format` formats whatever parses.
|
||||||
|
/// - Returns: The formatted source.
|
||||||
|
/// - Throws: ``SwiftFormatterError`` for a missing tool, a non-zero exit
|
||||||
|
/// (typically a parse error), or an I/O failure.
|
||||||
|
public static func format(source: String) throws -> String {
|
||||||
|
let tool: String = try findSwiftFormat()
|
||||||
|
|
||||||
|
let id: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
|
||||||
|
let workDir: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("LyrebirdSwiftFormat-\(id)", isDirectory: true)
|
||||||
|
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
|
||||||
|
do {
|
||||||
|
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
|
||||||
|
} catch {
|
||||||
|
throw SwiftFormatterError.ioFailed("\(error)")
|
||||||
|
}
|
||||||
|
// Register cleanup as soon as the dir exists, so a later write failure
|
||||||
|
// doesn't leak it.
|
||||||
|
defer { try? FileManager.default.removeItem(at: workDir) }
|
||||||
|
do {
|
||||||
|
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
|
||||||
|
} catch {
|
||||||
|
throw SwiftFormatterError.ioFailed("\(error)")
|
||||||
|
}
|
||||||
|
|
||||||
|
let process: Process = Process()
|
||||||
|
process.executableURL = URL(fileURLWithPath: tool)
|
||||||
|
process.arguments = ["format", sourcePath]
|
||||||
|
let stdoutPipe: Pipe = Pipe()
|
||||||
|
let stderrPipe: Pipe = Pipe()
|
||||||
|
process.standardOutput = stdoutPipe
|
||||||
|
process.standardError = stderrPipe
|
||||||
|
do {
|
||||||
|
try process.run()
|
||||||
|
} catch {
|
||||||
|
throw SwiftFormatterError.ioFailed("swift-format launch failed: \(error)")
|
||||||
|
}
|
||||||
|
// Drain stdout AND stderr concurrently before waiting. `swift-format` can
|
||||||
|
// emit both a large formatted buffer and (on a broken snippet) a large
|
||||||
|
// diagnostic stream; reading them sequentially would deadlock if the
|
||||||
|
// stream we aren't reading yet fills its OS pipe buffer while the child
|
||||||
|
// blocks writing to it.
|
||||||
|
let outHandle: FileHandle = stdoutPipe.fileHandleForReading
|
||||||
|
let errHandle: FileHandle = stderrPipe.fileHandleForReading
|
||||||
|
let group: DispatchGroup = DispatchGroup()
|
||||||
|
let drainQueue: DispatchQueue = DispatchQueue(
|
||||||
|
label: "net.realizedsound.lyrebird.swift-format-drain",
|
||||||
|
attributes: .concurrent
|
||||||
|
)
|
||||||
|
var outData: Data = Data()
|
||||||
|
var errData: Data = Data()
|
||||||
|
group.enter()
|
||||||
|
drainQueue.async { outData = outHandle.readDataToEndOfFile(); group.leave() }
|
||||||
|
group.enter()
|
||||||
|
drainQueue.async { errData = errHandle.readDataToEndOfFile(); group.leave() }
|
||||||
|
group.wait()
|
||||||
|
process.waitUntilExit()
|
||||||
|
|
||||||
|
guard process.terminationStatus == 0 else {
|
||||||
|
let stderr: String = String(data: errData, encoding: .utf8) ?? ""
|
||||||
|
throw SwiftFormatterError.formatFailed(exitCode: process.terminationStatus, stderr: stderr)
|
||||||
|
}
|
||||||
|
guard let formatted: String = String(data: outData, encoding: .utf8) else {
|
||||||
|
throw SwiftFormatterError.ioFailed("swift-format produced non-UTF8 output")
|
||||||
|
}
|
||||||
|
return formatted
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a `swift-format` executable is available on this machine.
|
||||||
|
public static var isAvailable: Bool {
|
||||||
|
(try? findSwiftFormat()) != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Tool resolution
|
||||||
|
|
||||||
|
/// First-success search: `xcrun -f swift-format`, then hard-coded paths.
|
||||||
|
static func findSwiftFormat() throws -> String {
|
||||||
|
if let viaXcrun: String = swiftFormatViaXcrun() {
|
||||||
|
return viaXcrun
|
||||||
|
}
|
||||||
|
let candidates: [String] = [
|
||||||
|
"/usr/bin/swift-format",
|
||||||
|
"/usr/local/bin/swift-format",
|
||||||
|
"/opt/homebrew/bin/swift-format",
|
||||||
|
]
|
||||||
|
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
throw SwiftFormatterError.toolNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func swiftFormatViaXcrun() -> String? {
|
||||||
|
let xcrunPath: String = "/usr/bin/xcrun"
|
||||||
|
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
|
||||||
|
let process: Process = Process()
|
||||||
|
process.executableURL = URL(fileURLWithPath: xcrunPath)
|
||||||
|
process.arguments = ["-f", "swift-format"]
|
||||||
|
let stdout: Pipe = Pipe()
|
||||||
|
process.standardOutput = stdout
|
||||||
|
process.standardError = FileHandle.nullDevice
|
||||||
|
do {
|
||||||
|
try process.run()
|
||||||
|
process.waitUntilExit()
|
||||||
|
} catch {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
guard process.terminationStatus == 0 else { return nil }
|
||||||
|
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
|
||||||
|
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
|
||||||
|
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
return trimmed.isEmpty ? nil : trimmed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// SwiftFormatterError.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
|
||||||
|
/// Errors raised while formatting snippet source with `swift-format`.
|
||||||
|
public enum SwiftFormatterError: Error {
|
||||||
|
/// No `swift-format` executable could be located (no Xcode / toolchain, or
|
||||||
|
/// an older toolchain that predates the bundled formatter).
|
||||||
|
case toolNotFound
|
||||||
|
/// `swift-format` exited non-zero — usually a parse error in the source.
|
||||||
|
case formatFailed(exitCode: Int32, stderr: String)
|
||||||
|
/// A filesystem or process I/O failure.
|
||||||
|
case ioFailed(String)
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// SwiftToolchainStatus.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
|
||||||
|
/// Result of probing for a usable Swift toolchain (the Swift scratchpad compiles
|
||||||
|
/// snippets by shelling out to `swiftc`, which requires Xcode or the Command Line
|
||||||
|
/// Tools). The Graph DSL mode does not need a toolchain, so a `.missing*` status is
|
||||||
|
/// a soft condition — it gates only the Swift-compile path. Produced by ``ToolchainProbe``.
|
||||||
|
public enum SwiftToolchainStatus: Equatable, Sendable {
|
||||||
|
/// `swiftc` and the macOS SDK both resolve — the Swift scratchpad can compile.
|
||||||
|
case available
|
||||||
|
/// No developer tools at all (`xcode-select -p` fails and `swiftc` is unresolved).
|
||||||
|
/// Fix: install the Command Line Tools (`xcode-select --install`) or Xcode.
|
||||||
|
case missingDeveloperTools
|
||||||
|
/// A developer directory is selected but `swiftc` could not be resolved.
|
||||||
|
/// Fix: install/repair Xcode or the Command Line Tools.
|
||||||
|
case missingSwiftc
|
||||||
|
/// `swiftc` resolves but the macOS SDK does not — usually an incomplete Xcode.
|
||||||
|
/// Fix: install a full Xcode.
|
||||||
|
case missingSDK
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
// ToolchainProbe.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Detects whether a usable Swift toolchain is present, so the app can warn the user
|
||||||
|
/// (with install guidance) instead of only failing into the console on the first Run.
|
||||||
|
///
|
||||||
|
/// The resolvers are injectable so the `.missing*` branches can be unit-tested without
|
||||||
|
/// actually uninstalling the toolchain; the defaults wrap the real `LiveCompiler`
|
||||||
|
/// resolution (`xcrun -f swiftc`, `xcrun --show-sdk-path`) plus `xcode-select -p`.
|
||||||
|
///
|
||||||
|
/// **Not RT-related.** Runs `xcrun` / `xcode-select` subprocesses — call off the main
|
||||||
|
/// thread (a couple of fast execs).
|
||||||
|
public struct ToolchainProbe: Sendable {
|
||||||
|
|
||||||
|
private let swiftcResolver: @Sendable () -> String?
|
||||||
|
private let sdkResolver: @Sendable () -> String?
|
||||||
|
private let developerDirResolver: @Sendable () -> String?
|
||||||
|
|
||||||
|
/// - Parameters:
|
||||||
|
/// - swiftcResolver: Returns the `swiftc` path, or `nil` when unresolved.
|
||||||
|
/// - sdkResolver: Returns the macOS SDK path, or `nil` when unresolved.
|
||||||
|
/// - developerDirResolver: Returns the active developer dir (`xcode-select -p`),
|
||||||
|
/// or `nil` when no developer directory is configured.
|
||||||
|
public init(
|
||||||
|
swiftcResolver: @escaping @Sendable () -> String? = ToolchainProbe.defaultSwiftcResolver,
|
||||||
|
sdkResolver: @escaping @Sendable () -> String? = ToolchainProbe.defaultSDKResolver,
|
||||||
|
developerDirResolver: @escaping @Sendable () -> String? = ToolchainProbe.developerDirViaXcodeSelect
|
||||||
|
) {
|
||||||
|
self.swiftcResolver = swiftcResolver
|
||||||
|
self.sdkResolver = sdkResolver
|
||||||
|
self.developerDirResolver = developerDirResolver
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Default `swiftc` resolver — wraps the internal `LiveCompiler.findSwiftc()` so the
|
||||||
|
/// public `init` default argument does not reference internal API.
|
||||||
|
public static func defaultSwiftcResolver() -> String? { try? LiveCompiler.findSwiftc() }
|
||||||
|
|
||||||
|
/// Default macOS SDK resolver — wraps the internal `LiveCompiler.sdkPathViaXcrun()`.
|
||||||
|
public static func defaultSDKResolver() -> String? { LiveCompiler.sdkPathViaXcrun() }
|
||||||
|
|
||||||
|
/// Classify the current toolchain state.
|
||||||
|
public func status() -> SwiftToolchainStatus {
|
||||||
|
let swiftc: String? = swiftcResolver()
|
||||||
|
let sdk: String? = sdkResolver()
|
||||||
|
if swiftc != nil && sdk != nil { return .available }
|
||||||
|
if swiftc == nil {
|
||||||
|
// No swiftc: distinguish "no developer tools at all" from "tools present
|
||||||
|
// but swiftc unresolved" by whether a developer dir is configured.
|
||||||
|
return developerDirResolver() == nil ? .missingDeveloperTools : .missingSwiftc
|
||||||
|
}
|
||||||
|
// swiftc resolves but the SDK does not.
|
||||||
|
return .missingSDK
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Active developer directory via `xcode-select -p`, or `nil` when unset / xcode-select
|
||||||
|
/// is missing / returns non-zero.
|
||||||
|
public static func developerDirViaXcodeSelect() -> String? {
|
||||||
|
let xcodeSelectPath: String = "/usr/bin/xcode-select"
|
||||||
|
guard FileManager.default.isExecutableFile(atPath: xcodeSelectPath) else { return nil }
|
||||||
|
let process: Process = Process()
|
||||||
|
process.executableURL = URL(fileURLWithPath: xcodeSelectPath)
|
||||||
|
process.arguments = ["-p"]
|
||||||
|
let stdout: Pipe = Pipe()
|
||||||
|
process.standardOutput = stdout
|
||||||
|
process.standardError = FileHandle.nullDevice
|
||||||
|
do {
|
||||||
|
try process.run()
|
||||||
|
process.waitUntilExit()
|
||||||
|
} catch {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
guard process.terminationStatus == 0 else { return nil }
|
||||||
|
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
|
||||||
|
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
|
||||||
|
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
return trimmed.isEmpty ? nil : trimmed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
// EditorPositionMapping.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdUI/LiveCompile
|
||||||
|
//
|
||||||
|
// Maps an `NSTextView` UTF-16 insertion offset to a zero-based (line, character)
|
||||||
|
// position. LSP positions are UTF-16-based, matching `NSTextView`'s own offsets,
|
||||||
|
// so no re-encoding is needed — only newline counting.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
|
||||||
|
/// Convert a UTF-16 offset into `text` to a zero-based `(line, character)`
|
||||||
|
/// where `character` is a UTF-16 code-unit column — the coordinate space
|
||||||
|
/// `sourcekit-lsp` expects. An offset past the end clamps to the final position.
|
||||||
|
func editorLineAndUTF16Char(in text: String, utf16Offset: Int) -> (line: Int, character: Int) {
|
||||||
|
let units: String.UTF16View = text.utf16
|
||||||
|
var idx: String.UTF16View.Index = units.startIndex
|
||||||
|
var consumed: Int = 0
|
||||||
|
var line: Int = 0
|
||||||
|
var character: Int = 0
|
||||||
|
let newline: UInt16 = 10
|
||||||
|
while consumed < utf16Offset, idx < units.endIndex {
|
||||||
|
if units[idx] == newline {
|
||||||
|
line += 1
|
||||||
|
character = 0
|
||||||
|
} else {
|
||||||
|
character += 1
|
||||||
|
}
|
||||||
|
idx = units.index(after: idx)
|
||||||
|
consumed += 1
|
||||||
|
}
|
||||||
|
return (line, character)
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -19,6 +19,13 @@ The view is macOS-only — `LyrebirdLiveCompile` shells out to `swiftc`, which i
|
|||||||
unavailable on iOS. The nested `LiveCompile/` sub-package declares
|
unavailable on iOS. The nested `LiveCompile/` sub-package declares
|
||||||
`platforms: [.macOS(.v15)]` and cannot be added to an iOS target.
|
`platforms: [.macOS(.v15)]` and cannot be added to an iOS target.
|
||||||
|
|
||||||
|
> Note: **Swift mode needs a Swift toolchain** (Xcode or the Command Line Tools) —
|
||||||
|
> it compiles snippets with `swiftc`. At launch the app probes for one
|
||||||
|
> (`ToolchainProbe`) and, if none is found, shows an alert (once per launch) with
|
||||||
|
> install guidance (Install Command Line Tools / Get Xcode). **Graph DSL mode needs no
|
||||||
|
> toolchain** — it interprets generator-graph expressions in-process — so it's the
|
||||||
|
> zero-install fallback.
|
||||||
|
|
||||||
## Hosting
|
## Hosting
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
@@ -41,11 +48,42 @@ window.open {
|
|||||||
|
|
||||||
| Shortcut | Action |
|
| Shortcut | Action |
|
||||||
|----------|--------|
|
|----------|--------|
|
||||||
| ⌘↩ | Compile + run. Removes synths from the previous run before executing. |
|
| ⌘↩ | Compile + run the **whole buffer**. Removes the previous run's *anonymous* synths first (named slots persist). |
|
||||||
| ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. |
|
| ⌘⇧↩ | Compile + run the whole buffer additively. Keeps previously played synths in the engine. |
|
||||||
|
| ⌘E | Compile + run just the **selection**, always additively — adds it to whatever is already playing. No-op with no selection. Works in both Swift and Graph DSL modes. |
|
||||||
|
| Esc / F5 | Invoke code completion at the caret (Swift mode). Manual only — never auto-triggered on `.`. See the Code completion section below. |
|
||||||
|
| ⌥⌘F | **Format Code** — pretty-print the buffer with the toolchain's `swift-format`. No-op on a blank buffer; a parse error is logged to the console and leaves the text untouched. |
|
||||||
|
| ⌥⌘R | **Render to File…** — bounce the selection (or the whole buffer) to an audio file offline instead of playing it live. The save dialog carries a **Format** popup (WAV 32-bit float / 16-bit / 24-bit, AIFF, CAF, RF64 WAV for files past 4 GB, or compressed AAC / Apple Lossless `.m4a`) and a **Duration** field; it remembers the last format. Renders faster-than-real-time via `NRTDriver` at the live engine's sample rate and channel count, then reveals the file in Finder. Only **sample-clock** timing renders — see *NRT: sample-clock timing only* under Functional snippets & scheduling. |
|
||||||
|
|
||||||
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
|
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
|
||||||
`LiveSession.clearTracked()` directly.
|
``LyrebirdScratchModel/clearTracked()`` — a full reset that removes both the
|
||||||
|
anonymous tracked synths and every named slot.
|
||||||
|
|
||||||
|
**Run Selection (⌘E)** evaluates only the highlighted text and *adds* it to the
|
||||||
|
running graph, without touching the rest of the buffer or the whole-buffer
|
||||||
|
re-evaluation baseline (the buffer's clean/dirty status still reflects the last
|
||||||
|
whole run). This is the live-coding "evaluate this line/region" gesture: audition
|
||||||
|
a single voice or tweak, layer it in, keep going. It reads the editor selection
|
||||||
|
via ``LyrebirdScratchModel/updateSelection(_:)`` and runs it through
|
||||||
|
``LyrebirdScratchModel/runSelection()``; disabled when nothing is selected.
|
||||||
|
|
||||||
|
The engine status pill at the top-left is also a **Start/Stop** button
|
||||||
|
(``LyrebirdScratchModel/toggleEngine()``): green "engine running" when live,
|
||||||
|
red "▶ start engine" when stopped. A snippet is only audible while the engine
|
||||||
|
is running; the host normally starts it at launch, but this lets the user
|
||||||
|
recover from a failed start (e.g. no output device) without relaunching.
|
||||||
|
|
||||||
|
## Engine panel (scope + status)
|
||||||
|
|
||||||
|
The panel at the bottom of the window is a small always-on view of the running
|
||||||
|
engine:
|
||||||
|
|
||||||
|
- A live dual-channel **oscilloscope** of the output (``ScratchScopeView``),
|
||||||
|
fed by a ``ScopeCapture`` that ``LiveSession`` attaches to the first one or two
|
||||||
|
output buses at init (it must be installed before `start()`). Pass
|
||||||
|
`attachScope: false` to `LiveSession.init` to opt out.
|
||||||
|
- **CPU average / peak** meter bars and the **synth / group / snippet** counts,
|
||||||
|
so overrun and node growth are visible at a glance.
|
||||||
|
|
||||||
## Snippet API surface
|
## Snippet API surface
|
||||||
|
|
||||||
@@ -55,32 +93,448 @@ A snippet has one local in scope:
|
|||||||
context: SnippetContext
|
context: SnippetContext
|
||||||
```
|
```
|
||||||
|
|
||||||
`SnippetContext` is intentionally minimal in v1:
|
`SnippetContext`:
|
||||||
|
|
||||||
- `context.engine` — the host `SynthesisEngine`.
|
- `context.engine` — the host `SynthesisEngine`.
|
||||||
- `context.play(_:)` — add a `Synthesizer` to the engine and register it for
|
- `context.play(_:)` — add a `Synthesizer` to the engine and register it for
|
||||||
cleanup on the next non-additive run.
|
cleanup on the next non-additive run.
|
||||||
- `context.reportMessage(_:)` — write back to the host (used by tests; handy for
|
- `context.play { <graph> }` — play a bare generator graph, no `SynthesizerBase`
|
||||||
`print`-style probes during development).
|
subclass needed (wraps it in a `ClosureSynthesizer`).
|
||||||
|
- `context.play(slot:_:)` / `context.play(slot:) { <graph> }` — play into a
|
||||||
|
**named slot** (see below).
|
||||||
|
- `context.reportMessage(_:)` — print a line to the **Console** panel (see
|
||||||
|
below); the live-coding equivalent of `print`.
|
||||||
|
|
||||||
|
## Console
|
||||||
|
|
||||||
|
An always-open panel down the right side of the window is the log:
|
||||||
|
|
||||||
|
- **Report messages** — every `context.reportMessage(_:)` line (and host notices
|
||||||
|
like a failed `engine.add` or a dropped slot swap).
|
||||||
|
- **Errors** — compile and Graph DSL diagnostics, with their `line:col`, shown
|
||||||
|
here rather than in a transient bottom strip so they stay visible while you
|
||||||
|
fix them.
|
||||||
|
- **Run notices** — a one-line result for each run.
|
||||||
|
|
||||||
|
Oldest first, auto-scrolled to the newest, capped at
|
||||||
|
``LyrebirdScratchModel/maxConsoleEntries`` lines. **Clear** empties it; a
|
||||||
|
**Reset Session** clears it too. The model exposes the log as
|
||||||
|
``LyrebirdScratchModel/consoleEntries``.
|
||||||
|
|
||||||
|
## Functional snippets & scheduling
|
||||||
|
|
||||||
|
A Swift-mode snippet is **real Swift**, not just a graph expression — loops,
|
||||||
|
`let` bindings, functions, arrays all work. The harness preamble imports
|
||||||
|
**Foundation**, `LyrebirdSynth`, and `LyrebirdLiveCompile`, so `pow`, `sin`,
|
||||||
|
`sqrt`, `Date`, and the whole generator library are in scope without any
|
||||||
|
`import` — which is good, because a snippet **can't** declare one (its body is
|
||||||
|
wrapped inside the entry function, and `import` is only legal at file scope). The
|
||||||
|
one rule for anything time-based: **schedule** events, don't `Thread.sleep`. The snippet body runs
|
||||||
|
once, synchronously, on the main thread; sleeping in a loop would freeze the UI
|
||||||
|
(the audio thread is separate, but the editor isn't). Use
|
||||||
|
`engine.schedule(_:after:)` for sample-accurate timing instead.
|
||||||
|
|
||||||
|
For example, a `for` loop that plays ten short sine tones a third of a second
|
||||||
|
apart — a C-major run — each a decaying `Line` envelope times a sine that frees
|
||||||
|
itself when done (`doneAction: .freeNode`), so the voices never pile up:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0,
|
||||||
|
440.0, 493.88, 523.25, 587.33, 659.25]
|
||||||
|
for i in 0..<10 {
|
||||||
|
let freq: Double = scale[i]
|
||||||
|
let tone = ClosureSynthesizer {
|
||||||
|
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
|
||||||
|
* OscSin.Audio(freq: freq)
|
||||||
|
}
|
||||||
|
do { try context.engine.schedule(tone, after: Double(i) * 0.35) }
|
||||||
|
catch { context.reportMessage("schedule \(i) failed: \(error)") }
|
||||||
|
}
|
||||||
|
context.reportMessage("scheduled 10 tones")
|
||||||
|
```
|
||||||
|
|
||||||
|
The loop returns immediately after scheduling all ten adds; the engine fires
|
||||||
|
each at its time (`0, 0.35, 0.70 … s`). A 0.2 s tone with 0.35 s spacing leaves a
|
||||||
|
short gap between each. This is *fire-and-forget* scheduling for a fixed sequence.
|
||||||
|
|
||||||
|
### The one rule: retention
|
||||||
|
|
||||||
|
The snippet body runs **once, synchronously, then returns**. Anything that fires
|
||||||
|
*later* must be held by something that outlives the snippet — the snippet itself
|
||||||
|
is transient. Three things self-sustain, and everything below builds on them:
|
||||||
|
|
||||||
|
- **`engine.schedule(…)`** — the engine holds the pending event.
|
||||||
|
- **`LyrebirdRoutine` / `LyrebirdTask`** — the routine runs on a dedicated
|
||||||
|
background thread that retains it until the body finishes or `stop()` is called.
|
||||||
|
- **`context.play(…)` synths** — the session tracks them (and named slots).
|
||||||
|
|
||||||
|
A `Thread.sleep` or busy `while` loop in the snippet *body* is the anti-pattern:
|
||||||
|
it runs on the **main thread**, so it freezes the editor UI (the RT audio thread
|
||||||
|
keeps going, but you can't type). Anything that *waits* belongs on a routine's
|
||||||
|
background thread, not in the body.
|
||||||
|
|
||||||
|
### Mechanisms
|
||||||
|
|
||||||
|
| Mechanism | Use for | Timing API |
|
||||||
|
|---|---|---|
|
||||||
|
| `context.engine.schedule(_:after:)` / `schedule(_:at:)` | One-shot "play this at time T" | Seconds, or a `SampleTime` |
|
||||||
|
| `LyrebirdRoutine` | A sequence with pauses; open-ended loops | `ctx.wait(seconds:)` / `wait(beats:)` / `waitUntil(sampleTime:)` |
|
||||||
|
| `LyrebirdTask` | Same as a routine but **pausable** (`pause()` / `resume()`) | same as routine |
|
||||||
|
| `LyrebirdClock` | Beat → sample-time reference | `clock.sampleTime(beat:)`, `nextBeat(after:)` → feed `schedule(_:at:)` or `ctx.waitUntil(sampleTime:)` |
|
||||||
|
| Trigger generators (`Impulse` → `Demand` / `TriggeredRandom` / gate) | Timing *inside* the audio graph — arps, gated LFOs, step patterns | Sample-accurate, in the running synth |
|
||||||
|
| `LyrebirdProcess` / `LyrebirdEventList`, `Score` / `ScorePlayer` | Structured / pre-composed timelines | Event lists |
|
||||||
|
|
||||||
|
All of these are reachable from a snippet through `context.engine` and the public
|
||||||
|
`LyrebirdSynth` types — nothing extra is injected.
|
||||||
|
|
||||||
|
### Waiting: `LyrebirdRoutine`
|
||||||
|
|
||||||
|
For "play N things with a pause between each" — the reactive counterpart to the
|
||||||
|
fire-and-forget loop above — use a routine. Its body runs on a background thread
|
||||||
|
(so `wait` never freezes the UI), and `routine.start(engine:)` keeps it alive
|
||||||
|
after the snippet returns:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0]
|
||||||
|
let routine = LyrebirdRoutine { ctx in
|
||||||
|
for freq in scale {
|
||||||
|
ctx.add(ClosureSynthesizer {
|
||||||
|
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
|
||||||
|
* OscSin.Audio(freq: freq)
|
||||||
|
})
|
||||||
|
try ctx.wait(seconds: 0.3) // background-thread wait — UI stays live
|
||||||
|
}
|
||||||
|
}
|
||||||
|
routine.start(engine: context.engine) // self-sustaining; survives the snippet
|
||||||
|
```
|
||||||
|
|
||||||
|
`ctx.add(_:)` hops to the main-actor `engine.add` for you. `ctx.wait(beats:)`
|
||||||
|
waits at `ctx.tempo` (default 120 BPM; set `ctx.tempo = …` in the body to change
|
||||||
|
it); `ctx.waitUntil(sampleTime:)` waits to an absolute engine time, which is where
|
||||||
|
`LyrebirdClock.sampleTime(beat:)` comes in for on-grid spacing. Call
|
||||||
|
`routine.stop()` (e.g. from a later ⌘E) to cancel — the body exits at its next
|
||||||
|
`wait`.
|
||||||
|
|
||||||
|
### Caveats
|
||||||
|
|
||||||
|
- **Never block the main thread** — no `Thread.sleep` / busy loops in the snippet
|
||||||
|
body. Wait on a routine instead.
|
||||||
|
- `Task { }` / `DispatchQueue.main.asyncAfter` *technically* work (they fire later
|
||||||
|
on main and the session keeps `context` alive), but prefer `engine.schedule`
|
||||||
|
(sample-accurate) or a routine (proper timed waits) over ad-hoc dispatch.
|
||||||
|
- A `LyrebirdClock` used only to compute schedule times is fine to let go; if
|
||||||
|
you need it *driving* something over time, a routine's thread keeps it alive.
|
||||||
|
|
||||||
|
### NRT: sample-clock timing only
|
||||||
|
|
||||||
|
**Render to File (⌥⌘R) is offline.** The `NRTDriver` renders faster than real
|
||||||
|
time in a tight **synchronous burst** — 10 s of audio in a fraction of a second —
|
||||||
|
and it does **not** wait for anything on the wall clock. So only timing expressed
|
||||||
|
in **engine / sample time** survives a render; wall-clock timing silently drops out.
|
||||||
|
|
||||||
|
| Mechanism | Live | Render to File |
|
||||||
|
|---|---|---|
|
||||||
|
| `engine.schedule(_:after:/at:)` | ✅ | ✅ — fires at its sample time as blocks render |
|
||||||
|
| In-graph triggers (`Impulse` → `Demand` / gates) | ✅ | ✅ — per-sample, driven by the render itself (best for NRT) |
|
||||||
|
| `LyrebirdClock.sampleTime(beat:)` → `schedule(_:at:)` | ✅ | ✅ — pure beat→sample math |
|
||||||
|
| `LyrebirdRoutine` / `LyrebirdTask` (`wait(seconds:/beats:)`) | ✅ | ❌ — **wall-clock sleeps on a background thread; the render finishes before they fire, so their `ctx.add`s never make the file** |
|
||||||
|
| Real-time playback (`playTimeline`, live `ScorePlayer`) | ✅ | ❌ — the sample-accurate scheduling underneath is fine; the wall-clock playback driver isn't |
|
||||||
|
|
||||||
|
Rule of thumb: if the timing is a routine's `wait`, it's for **live** play; to make
|
||||||
|
the same idea render, re-express it as `engine.schedule(_:after:)` (fixed
|
||||||
|
sequence) or an `Impulse`-driven graph (periodic / patterned). This is a real
|
||||||
|
footgun — routine timing works when you play it and silently produces an empty or
|
||||||
|
truncated bounce when you render it.
|
||||||
|
|
||||||
|
> Note: **Graph DSL mode** evaluates only generator-graph expressions — no loops
|
||||||
|
> or scheduling. Functional code like the above needs **Swift mode**.
|
||||||
|
|
||||||
|
## Named slots (hot-swap)
|
||||||
|
|
||||||
|
`context.play(slot: "name") { … }` installs a voice under a name. Re-running a
|
||||||
|
slot definition **replaces just that voice in place** — the new voice starts
|
||||||
|
before the old one is removed (a brief overlap, no gap), while everything else
|
||||||
|
keeps playing:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
context.play(slot: "bass") { OscSaw.Audio(freq: 55, mul: 0.2) }
|
||||||
|
context.play(slot: "lead") { Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0) }
|
||||||
|
```
|
||||||
|
|
||||||
|
Unlike anonymous `context.play`, a slotted voice is **not** torn down by the
|
||||||
|
next non-additive (⌘↩) run — that is what lets you edit and re-evaluate one
|
||||||
|
voice at a time while the rest of the patch keeps going (the `Pdef` idiom).
|
||||||
|
|
||||||
|
| API | Lifetime |
|
||||||
|
|-----|----------|
|
||||||
|
| `context.play(_:)` / `context.play { }` | Removed on the next non-additive run. |
|
||||||
|
| `context.play(slot:) { }` | Persists; a same-name re-run replaces it in place. |
|
||||||
|
|
||||||
|
### Start a voice, release it later
|
||||||
|
|
||||||
|
The slot **name is the handle** — the persistent reference you keep across
|
||||||
|
evaluations. (Swift `let`/`var` bindings do not carry from one snippet to the
|
||||||
|
next: each ⌘↩ / ⌘E is a separately-compiled unit, so a variable declared in one
|
||||||
|
run is invisible to the next.) So the "start something, let go of it later"
|
||||||
|
gesture is: name a slot in one evaluation, then release it by name from another —
|
||||||
|
a natural pairing with **Run Selection** (⌘E):
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// Select this line, ⌘E — starts a persistent, gated voice named "pad":
|
||||||
|
context.play(slot: "pad") { EnvGen(gate: 1, /* … release-on-done */) * OscSaw.Audio(freq: 110) }
|
||||||
|
|
||||||
|
// …later, select this line, ⌘E — graceful release: the envelope tails out,
|
||||||
|
// then the voice frees itself:
|
||||||
|
context.release(slot: "pad")
|
||||||
|
```
|
||||||
|
|
||||||
|
- `context.release(slot:)` triggers the voice's envelope **release** phase and
|
||||||
|
drops the handle; the voice must free itself (an `EnvGen`/gate with a
|
||||||
|
free-on-done action) to leave the engine.
|
||||||
|
- `context.free(slot:)` is the **immediate** hard stop (no tail) — the
|
||||||
|
counterpart to `release`.
|
||||||
|
|
||||||
|
Clear a slot with `context.free(slot: "bass")` (or `context.session.clearSlot`),
|
||||||
|
all slots with `context.session.clearSlots()`. The toolbar **Clear Synths**
|
||||||
|
button is a full reset — anonymous synths *and* every slot. A slot definition you
|
||||||
|
delete from the buffer and stop re-running is *not* auto-removed (a `Pdef`-style
|
||||||
|
gotcha) — release/free it explicitly or hit Clear Synths.
|
||||||
|
|
||||||
## Threading
|
## Threading
|
||||||
|
|
||||||
All UI is `@MainActor`-isolated. `LiveSession.compileAndRun` is invoked
|
All UI is `@MainActor`-isolated. The Run / Run Additive actions dispatch a
|
||||||
synchronously inside the button action, so the editor freezes for the duration
|
`Task` that awaits ``LyrebirdScratchModel/run(additive:)``, which awaits
|
||||||
of the `swiftc` invocation (≈ 1 second cold, much faster on warm cache). v1
|
`LiveSession.compileAndRunAsync` — the `swiftc` subprocess runs on a background
|
||||||
accepts that trade-off; an off-main compile path is on the polish list.
|
`Task.detached`, so the editor stays responsive while a compile is in flight.
|
||||||
|
The snippet entry then resumes on the main actor to touch engine + UI state.
|
||||||
|
`LyrebirdScratchMenuController` disables the Run / Run Additive commands
|
||||||
|
whenever ``ReevalState/canEvaluate`` is `false` (a compile is in flight or the
|
||||||
|
buffer is empty); `run(additive:)` additionally guards re-entrancy on
|
||||||
|
``LyrebirdScratchModel/isCompiling``.
|
||||||
|
|
||||||
|
## Re-evaluation readiness
|
||||||
|
|
||||||
|
``LyrebirdScratchModel/reevalState`` publishes a ``ReevalState`` — a structured
|
||||||
|
signal for *when* a re-evaluation is available and whether it would change
|
||||||
|
anything:
|
||||||
|
|
||||||
|
| State | Meaning |
|
||||||
|
|-------|---------|
|
||||||
|
| `.empty` | Buffer is blank. Nothing to run. |
|
||||||
|
| `.dirty` | Edited since the last run (or never run). An eval is available. |
|
||||||
|
| `.compiling` | A compile + run is in flight. |
|
||||||
|
| `.queued(untilBeat:)` | Compiled; a quantized slot swap is scheduled but not yet audible (see below). |
|
||||||
|
| `.clean` | Buffer matches what is currently playing. |
|
||||||
|
| `.failed(diagnosticCount:)` | The last run failed to compile. |
|
||||||
|
|
||||||
|
The editor renders this as a colored dot + label in the status bar.
|
||||||
|
``ReevalState/canEvaluate`` is `true` whenever a run can be triggered right now
|
||||||
|
(non-blank buffer, no compile already running) — hosts can gate their own Run
|
||||||
|
controls on it.
|
||||||
|
|
||||||
|
## Quantized swaps (on-beat latency masking)
|
||||||
|
|
||||||
|
A `swiftc` build finishes a few hundred milliseconds after ⌘↩ — long enough to
|
||||||
|
feel loose against a running groove. Point the session at a `LyrebirdClock` and
|
||||||
|
choose a `SwapQuantize` mode, and named-slot swaps land on the next musical
|
||||||
|
boundary instead of whenever the compile happens to finish:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
let clock = LyrebirdClock(engine: engine, bpm: 120)
|
||||||
|
let session = LiveSession(engine: engine)
|
||||||
|
session.swapClock = clock
|
||||||
|
session.swapQuantize = .nextBar(beatsPerBar: 4) // .immediate | .nextBeat | .nextBar
|
||||||
|
```
|
||||||
|
|
||||||
|
Now `context.play(slot: "bass") { … }` **schedules** the new voice's add and the
|
||||||
|
old voice's removal at the same upcoming boundary sample time (`engine.schedule` /
|
||||||
|
`engine.remove(_:at:)`), so the swap is glitch-free and on-grid. Because the
|
||||||
|
change is quantized to a boundary that is comfortably past the compile, the
|
||||||
|
compile latency is hidden: you edit, hit ⌘↩, and the change drops exactly on the
|
||||||
|
downbeat.
|
||||||
|
|
||||||
|
While the swap is pending, ``LyrebirdScratchModel/reevalState`` reads
|
||||||
|
`.queued(untilBeat:)` (a purple badge); it settles to `.clean` once the clock
|
||||||
|
passes the boundary (or `.dirty` if you edit again first). ``LiveSession/pendingSwapBeat``
|
||||||
|
exposes the target beat. `.immediate` (or no `swapClock`) makes swaps take effect
|
||||||
|
at once. Anonymous `context.play` is unaffected; quantization applies to named
|
||||||
|
slots only.
|
||||||
|
|
||||||
|
Re-running a slot while its previous quantized swap is still pending is safe: the
|
||||||
|
previous voice's removal is always scheduled no earlier than its own add, so a
|
||||||
|
just-scheduled voice is never left orphaned.
|
||||||
|
|
||||||
|
## First-run latency (module-cache prewarm)
|
||||||
|
|
||||||
|
A snippet compiles in ~0.1 s once the Swift/Clang module cache is warm — but the
|
||||||
|
*first* compile of a session pays ~2–3 s to build the precompiled module for the
|
||||||
|
large `LyrebirdSynth` interface. Left alone, that cost lands on the user's first
|
||||||
|
⌘↩ (the "time to first sound").
|
||||||
|
|
||||||
|
``LiveSession/prewarm()`` moves it into the background: it type-checks a trivial
|
||||||
|
import-only snippet on a detached `.utility` task, warming swiftc's default
|
||||||
|
module cache so the first real compile is already fast. `LyrebirdScratchView`
|
||||||
|
calls it from `onAppear` (idempotent — safe to call again). It is *not* wired
|
||||||
|
into `LyrebirdScratchModel.init`, so constructing a model never shells out to
|
||||||
|
swiftc; a headless host should call `session.prewarm()` at launch itself.
|
||||||
|
|
||||||
|
A prewarm never throws: a failure (e.g. a missing toolchain) leaves
|
||||||
|
``LiveSession/isPrewarmed`` `false` — so a later call retries, and the first
|
||||||
|
real compile simply pays the cold build itself and surfaces any real error
|
||||||
|
through its own diagnostics.
|
||||||
|
|
||||||
|
> Note: the prewarm deliberately uses swiftc's default module cache rather than a
|
||||||
|
> pinned `-module-cache-path`. A freshly-built dedicated cache produces module
|
||||||
|
> metadata that diverges from the already-loaded `libLyrebirdLiveCompileDynamic`,
|
||||||
|
> which turns a benign ObjC class-duplication warning into a hard cast crash when
|
||||||
|
> a snippet is `dlopen`'d.
|
||||||
|
|
||||||
|
## Compile artifacts & Application Support
|
||||||
|
|
||||||
|
Swift-mode compilation points `swiftc` at the Lyrebird module artifacts: the
|
||||||
|
swiftmodules, the Lyrebird dylibs, and the C-shim (`LyrebirdC`) Clang module map.
|
||||||
|
In a dev checkout those live in the SPM build dir under `~/Documents`, so a
|
||||||
|
non-sandboxed host — and the `swiftc` subprocess it spawns — trips the macOS
|
||||||
|
"wants to access your Documents folder" permission gate. (The scratch/compile
|
||||||
|
temp dirs use `/var/folders/…` and are never the cause.)
|
||||||
|
|
||||||
|
``LiveSession/stageArtifacts(from:to:)`` copies the minimal set into
|
||||||
|
`~/Library/Application Support/LyrebirdScratch/LiveCompile/` — an ungated
|
||||||
|
location — and **rewrites the C module map's absolute umbrella-header path** to a
|
||||||
|
staged copy of the header, so the staged directory is a fully self-contained
|
||||||
|
compile root. ``LiveSession/defaultImportPaths()`` / `defaultLibrarySearchPaths()`
|
||||||
|
/ `defaultRpaths()` then prefer the staged dir when it is populated. Staging is
|
||||||
|
idempotent (a receipt file skips an unchanged source) and best-effort (falls back
|
||||||
|
to the build dir on any failure). A host calls it once before constructing the
|
||||||
|
session:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
LiveSession.stageArtifacts() // stage into App Support
|
||||||
|
let session = LiveSession(engine: engine) // defaults resolve to the staged dir
|
||||||
|
```
|
||||||
|
|
||||||
|
For a **standalone** app, ship the artifacts inside the bundle at
|
||||||
|
`Contents/Resources/LyrebirdArtifacts` (name = ``LiveSession/bundledArtifactsDirName``);
|
||||||
|
``LiveSession/artifactSourceDir()`` prefers that over the build dir, so a shipped
|
||||||
|
`LyrebirdScratch.app` in `/Applications` stages without ever reading a
|
||||||
|
permission-gated folder. In a dev checkout the one-time stage copy still reads
|
||||||
|
the build dir under `~/Documents`; every later launch reuses the staged copy.
|
||||||
|
|
||||||
|
## Code completion
|
||||||
|
|
||||||
|
Swift code completion is provided by the toolchain's `sourcekit-lsp`, driven over
|
||||||
|
stdio by ``SourceKitLSPClient`` and bridged to the editor by
|
||||||
|
``SnippetCompletionService``. Press **Esc** (or **F5** — the standard macOS
|
||||||
|
completion keys) to complete at the caret; the candidates are the real symbols the snippet would
|
||||||
|
see at compile time — `LyrebirdSynth` generators (`OscSin.` → `Audio`, `Control`,
|
||||||
|
…), the injected `context` (`context.` → `play`, `engine`, …), and the Swift
|
||||||
|
standard library. Completion is **manual, never auto-triggered on `.`** — an
|
||||||
|
unrequested popup ambushes typing and the built-in completion window is awkward
|
||||||
|
to dismiss mid-edit.
|
||||||
|
|
||||||
|
How it resolves those symbols for an otherwise free-standing file: the service
|
||||||
|
maintains a small temp workspace holding the snippet **wrapped** in the same
|
||||||
|
`SnippetHarness` preamble the compiler uses, next to a `compile_commands.json`
|
||||||
|
carrying the host `LiveSession`'s `-I` / module-map / link flags. sourcekit-lsp's
|
||||||
|
compilation-database build system reads that file. The caret is mapped through
|
||||||
|
the harness line offset, so a completion request at the user's row hits the right
|
||||||
|
row in the wrapped document. Completion is Swift-mode only — graph-DSL mode is
|
||||||
|
interpreted and needs no compiler — and best-effort: any LSP failure yields no
|
||||||
|
candidates rather than an error.
|
||||||
|
|
||||||
## Limitations
|
## Limitations
|
||||||
|
|
||||||
- macOS only.
|
- macOS only.
|
||||||
- No syntax highlighting, code completion, or line-number gutter (deferred).
|
- Syntax highlighting is a lightweight built-in lexer (`ScratchSwiftTokenizer`) —
|
||||||
- Compiled dylibs are leaked by design — types in a loaded snippet may still be
|
approximate by design, not a full parser. Completion (above) uses the real
|
||||||
referenced by tracked synths; unloading is unsafe.
|
compiler via sourcekit-lsp; the two are independent.
|
||||||
|
- Completion is invoked manually with **Esc** (or **F5**); there is no
|
||||||
|
auto-trigger on `.`.
|
||||||
- The host `.app` must not be sandboxed and must allow library validation to be
|
- The host `.app` must not be sandboxed and must allow library validation to be
|
||||||
disabled, since `swiftc` is invoked via `Process` and the resulting unsigned
|
disabled, since `swiftc` is invoked via `Process` and the resulting unsigned
|
||||||
dylib is `dlopen`'d.
|
dylib is `dlopen`'d.
|
||||||
|
|
||||||
|
## Snippet memory (the dylib leak)
|
||||||
|
|
||||||
|
Every ⌘↩ compiles a fresh dylib and `dlopen`s it; those dylibs are **never
|
||||||
|
unloaded**, so a session's mapped memory grows one dylib per successful
|
||||||
|
evaluation. ``LiveSession/loadedSnippetCount`` reports how many are mapped — a
|
||||||
|
host can nudge the user to restart after a very long session.
|
||||||
|
|
||||||
|
This is a hard limit of the compiled approach, not an oversight. Reclaiming the
|
||||||
|
memory would require `dlclose`, which is **unsafe** for these dylibs: `dlopen`
|
||||||
|
registers a Swift dylib's type metadata and protocol-conformance records into
|
||||||
|
process-global runtime caches, and `dlclose` unmaps the dylib without
|
||||||
|
deregistering them — leaving those caches pointing into freed memory, so a later
|
||||||
|
type operation can crash. That holds even after every synth a snippet produced
|
||||||
|
has been removed. A refcount-gated `dlclose` was therefore considered and
|
||||||
|
rejected rather than shipped as a crash-prone flag.
|
||||||
|
|
||||||
|
``LiveSession/resetAll()`` (the toolbar **Clear Synths**) is the pressure-relief
|
||||||
|
valve: it stops all snippet audio — removing every anonymous and slotted synth —
|
||||||
|
and gives a clean slate without tearing down the engine, but it does not reclaim
|
||||||
|
the mapped dylibs. Only restarting the process does. The **Graph DSL mode**
|
||||||
|
below sidesteps dylibs entirely and is the structural fix.
|
||||||
|
|
||||||
|
The editor makes this visible rather than silent: the engine bar shows a
|
||||||
|
**"snippets: N"** count (`LyrebirdScratchModel.loadedSnippetCount`), and once it
|
||||||
|
crosses ``LyrebirdScratchModel/snippetRestartThreshold`` (50) the count turns
|
||||||
|
orange and a warning banner appears — nudging the user to restart to reclaim the
|
||||||
|
memory, or to switch to Graph DSL mode (which maps no dylibs). It is a nudge, not
|
||||||
|
a hard stop: the choice stays with the user.
|
||||||
|
|
||||||
|
Two Run-menu commands act on this:
|
||||||
|
|
||||||
|
- **Reset Session** (``LyrebirdScratchModel/resetSession()``) — an *in-process*
|
||||||
|
reset: stops all snippet audio, shuts down the code-completion server (freeing
|
||||||
|
its subprocess and temp workspace), and clears diagnostics and the run
|
||||||
|
baseline. **Non-destructive** — your buffer is left untouched, so it needs no
|
||||||
|
confirmation. It does **not** unload the mapped snippet dylibs.
|
||||||
|
- **Restart to Reclaim Memory…** — relaunches the app (after a confirmation,
|
||||||
|
since unsaved buffer edits are lost), the only way to actually free the mapped
|
||||||
|
dylibs. The fresh process starts at zero.
|
||||||
|
|
||||||
|
## Graph DSL mode (instant, no compile)
|
||||||
|
|
||||||
|
The status-bar toggle switches the editor between two evaluators:
|
||||||
|
|
||||||
|
- **Swift** — the full snippet path above: swiftc compiles a dylib, which is
|
||||||
|
`dlopen`'d and run. The whole language, `SynthesizerBase` subclasses, arbitrary
|
||||||
|
code — at the cost of a compile and a permanently mapped dylib.
|
||||||
|
- **Graph DSL** — the interpreted graph-DSL. The buffer is lexed, parsed, and
|
||||||
|
built into a generator graph **in-process**: no swiftc, no dylib, microseconds
|
||||||
|
instead of a compile round-trip, and nothing leaks. The trade is scope — only
|
||||||
|
generator-graph *expressions*, not arbitrary Swift.
|
||||||
|
|
||||||
|
A DSL buffer is one statement per line:
|
||||||
|
|
||||||
|
```
|
||||||
|
bass = OscSawtooth.Audio(freq: 55, mul: 0.15)
|
||||||
|
Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
- A **bare** line plays anonymously and is tracked, so a non-additive re-run
|
||||||
|
(⌘↩) replaces it — exactly like `context.play { … }`.
|
||||||
|
- A **named** line (`name = …`) installs a persistent, hot-swappable named slot
|
||||||
|
(like `context.play(slot:)`): it survives a non-additive re-run and is swapped
|
||||||
|
in place on the next evaluation, so you can mutate one voice while others keep
|
||||||
|
playing. Quantized swaps apply here too.
|
||||||
|
|
||||||
|
Generators are spelled **exactly** as in a Lyrebird `build()` —
|
||||||
|
`OscSin.Audio(freq:)`, `.Control` for the control-rate variant — so a graph you
|
||||||
|
like in the editor pastes into a project unchanged (only the wrapping differs;
|
||||||
|
see the `LyrebirdGraphDSL` design notes). The bare `OscSin(…)` no-rate form is a
|
||||||
|
DSL shorthand for the audio variant.
|
||||||
|
|
||||||
|
The whole program is built **before** any engine mutation, so a syntax or build
|
||||||
|
error leaves the currently-playing graph untouched — a bad edit never drops
|
||||||
|
audio. Errors surface in the same gutter as swiftc diagnostics: a parse error
|
||||||
|
points at its line/column; a build error (unknown generator, bad argument)
|
||||||
|
reports at file scope. See ``LyrebirdScratchModel/switchMode(to:)`` and
|
||||||
|
``LiveSession/runGraphDSL(_:additive:resources:)``.
|
||||||
|
|
||||||
## Topics
|
## Topics
|
||||||
|
|
||||||
- ``LyrebirdScratchView``
|
- ``LyrebirdScratchView``
|
||||||
- ``LyrebirdScratchModel``
|
- ``LyrebirdScratchModel``
|
||||||
|
- ``ScratchEvalMode``
|
||||||
|
|||||||
@@ -13,8 +13,12 @@ import LyrebirdLiveCompile
|
|||||||
/// Builds and installs the macOS application menu bar for a live-coding host
|
/// Builds and installs the macOS application menu bar for a live-coding host
|
||||||
/// driven by a `LyrebirdScratchModel`. Owns the action targets so menu items
|
/// driven by a `LyrebirdScratchModel`. Owns the action targets so menu items
|
||||||
/// stay wired for the lifetime of the controller.
|
/// stay wired for the lifetime of the controller.
|
||||||
|
///
|
||||||
|
/// Conforms to `NSMenuItemValidation` so the Run / Run Additive commands
|
||||||
|
/// disable when the buffer cannot be evaluated — i.e. while a compile is in
|
||||||
|
/// flight or the buffer is empty (``ReevalState/canEvaluate``).
|
||||||
@MainActor
|
@MainActor
|
||||||
public final class LyrebirdScratchMenuController: NSObject {
|
public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation {
|
||||||
|
|
||||||
public let model: LyrebirdScratchModel
|
public let model: LyrebirdScratchModel
|
||||||
|
|
||||||
@@ -24,7 +28,7 @@ public final class LyrebirdScratchMenuController: NSObject {
|
|||||||
|
|
||||||
/// Construct the full menu bar (App / File / Edit / Run / View / Window /
|
/// Construct the full menu bar (App / File / Edit / Run / View / Window /
|
||||||
/// Help) and assign it to `NSApplication.shared.mainMenu`.
|
/// Help) and assign it to `NSApplication.shared.mainMenu`.
|
||||||
public func installMainMenu(appName: String = "LyrebirdScratchDemo") {
|
public func installMainMenu(appName: String = "LyrebirdScratch") {
|
||||||
let mainMenu: NSMenu = NSMenu()
|
let mainMenu: NSMenu = NSMenu()
|
||||||
|
|
||||||
mainMenu.addItem(appMenuItem(appName: appName))
|
mainMenu.addItem(appMenuItem(appName: appName))
|
||||||
@@ -35,6 +39,11 @@ public final class LyrebirdScratchMenuController: NSObject {
|
|||||||
mainMenu.addItem(windowMenuItem())
|
mainMenu.addItem(windowMenuItem())
|
||||||
|
|
||||||
NSApplication.shared.mainMenu = mainMenu
|
NSApplication.shared.mainMenu = mainMenu
|
||||||
|
|
||||||
|
// Launch check: if the Swift toolchain is missing, warn with install guidance
|
||||||
|
// (the Swift scratchpad needs swiftc). Fires once per launch — the probe runs
|
||||||
|
// off-main and the alert (if any) is dispatched back to the main thread.
|
||||||
|
warnIfSwiftToolchainMissing()
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: App menu
|
// MARK: App menu
|
||||||
@@ -131,6 +140,12 @@ public final class LyrebirdScratchMenuController: NSObject {
|
|||||||
keyEquivalent: "f")
|
keyEquivalent: "f")
|
||||||
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
|
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
|
||||||
menu.addItem(find)
|
menu.addItem(find)
|
||||||
|
menu.addItem(NSMenuItem.separator())
|
||||||
|
let format: NSMenuItem = target(NSMenuItem(title: "Format Code",
|
||||||
|
action: #selector(formatCode(_:)),
|
||||||
|
keyEquivalent: "f"))
|
||||||
|
format.keyEquivalentModifierMask = [.command, .option]
|
||||||
|
menu.addItem(format)
|
||||||
item.submenu = menu
|
item.submenu = menu
|
||||||
return item
|
return item
|
||||||
}
|
}
|
||||||
@@ -148,10 +163,26 @@ public final class LyrebirdScratchMenuController: NSObject {
|
|||||||
keyEquivalent: "\r")
|
keyEquivalent: "\r")
|
||||||
runAdd.keyEquivalentModifierMask = [.command, .shift]
|
runAdd.keyEquivalentModifierMask = [.command, .shift]
|
||||||
menu.addItem(target(runAdd))
|
menu.addItem(target(runAdd))
|
||||||
|
menu.addItem(target(NSMenuItem(title: "Run Selection",
|
||||||
|
action: #selector(runSelection(_:)),
|
||||||
|
keyEquivalent: "e")))
|
||||||
|
menu.addItem(NSMenuItem.separator())
|
||||||
|
let render: NSMenuItem = target(NSMenuItem(title: "Render to File…",
|
||||||
|
action: #selector(renderToFile(_:)),
|
||||||
|
keyEquivalent: "r"))
|
||||||
|
render.keyEquivalentModifierMask = [.command, .option]
|
||||||
|
menu.addItem(render)
|
||||||
menu.addItem(NSMenuItem.separator())
|
menu.addItem(NSMenuItem.separator())
|
||||||
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
|
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
|
||||||
action: #selector(clearSynths(_:)),
|
action: #selector(clearSynths(_:)),
|
||||||
keyEquivalent: "k")))
|
keyEquivalent: "k")))
|
||||||
|
menu.addItem(NSMenuItem.separator())
|
||||||
|
menu.addItem(target(NSMenuItem(title: "Reset Session",
|
||||||
|
action: #selector(resetSession(_:)),
|
||||||
|
keyEquivalent: "")))
|
||||||
|
menu.addItem(target(NSMenuItem(title: "Restart to Reclaim Memory…",
|
||||||
|
action: #selector(restartApp(_:)),
|
||||||
|
keyEquivalent: "")))
|
||||||
item.submenu = menu
|
item.submenu = menu
|
||||||
return item
|
return item
|
||||||
}
|
}
|
||||||
@@ -201,6 +232,33 @@ public final class LyrebirdScratchMenuController: NSObject {
|
|||||||
return item
|
return item
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Menu validation
|
||||||
|
|
||||||
|
/// Disable the Run / Run Additive commands whenever the buffer cannot be
|
||||||
|
/// evaluated (a compile is in flight, or the buffer is empty). All other
|
||||||
|
/// items stay enabled. AppKit calls this automatically for items whose
|
||||||
|
/// target is this controller.
|
||||||
|
public func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
|
||||||
|
switch menuItem.action {
|
||||||
|
case #selector(runSnippet(_:)), #selector(runSnippetAdditive(_:)):
|
||||||
|
return model.reevalState.canEvaluate
|
||||||
|
case #selector(runSelection(_:)):
|
||||||
|
// Needs a selection to run and an evaluator that isn't mid-compile.
|
||||||
|
return model.hasSelection && model.reevalState.canEvaluate
|
||||||
|
case #selector(resetSession(_:)):
|
||||||
|
// Don't tear the session down mid-compile.
|
||||||
|
return !model.isCompiling
|
||||||
|
case #selector(formatCode(_:)):
|
||||||
|
// Not mid-compile; the model's formatter no-ops on a blank buffer.
|
||||||
|
return !model.isCompiling
|
||||||
|
case #selector(renderToFile(_:)):
|
||||||
|
// Needs an evaluatable buffer and no compile/render in flight.
|
||||||
|
return model.reevalState.canEvaluate
|
||||||
|
default:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Action targets
|
// MARK: - Action targets
|
||||||
|
|
||||||
private func target(_ item: NSMenuItem) -> NSMenuItem {
|
private func target(_ item: NSMenuItem) -> NSMenuItem {
|
||||||
@@ -261,6 +319,90 @@ public final class LyrebirdScratchMenuController: NSObject {
|
|||||||
Task { @MainActor in _ = await model.run(additive: true) }
|
Task { @MainActor in _ = await model.run(additive: true) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@objc private func runSelection(_ sender: Any?) {
|
||||||
|
Task { @MainActor in _ = await model.runSelection() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func formatCode(_ sender: Any?) {
|
||||||
|
Task { @MainActor in await model.formatBuffer() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func renderToFile(_ sender: Any?) {
|
||||||
|
// Single save dialog: an accessory view carries the format popup + duration,
|
||||||
|
// and keeps the filename extension in sync with the chosen container.
|
||||||
|
let defaultRenderDuration: Double = 5.0
|
||||||
|
let panel: NSSavePanel = NSSavePanel()
|
||||||
|
panel.message = "Render the snippet (or selection) to an audio file"
|
||||||
|
let accessory: RenderOptionsAccessory = RenderOptionsAccessory(
|
||||||
|
baseName: "render", initialDuration: defaultRenderDuration, savePanel: panel
|
||||||
|
)
|
||||||
|
panel.accessoryView = accessory
|
||||||
|
|
||||||
|
guard panel.runModal() == .OK, let chosenURL: URL = panel.url else { return }
|
||||||
|
|
||||||
|
guard let duration: Double = accessory.durationSeconds else {
|
||||||
|
let invalid: NSAlert = NSAlert()
|
||||||
|
invalid.messageText = "Invalid duration"
|
||||||
|
invalid.informativeText = "Enter a positive number of seconds (e.g. 5.0)."
|
||||||
|
invalid.runModal()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let format: AudioFileFormat = accessory.selectedFormat
|
||||||
|
// This is the source of truth for the final extension: force it to match the
|
||||||
|
// chosen format so a hand-typed name with the wrong (or no) extension still
|
||||||
|
// produces a correctly-named file. (The accessory's own panel-name sync is a
|
||||||
|
// live-preview convenience; enforcement happens here.)
|
||||||
|
let url: URL = chosenURL.deletingPathExtension().appendingPathExtension(format.fileExtension)
|
||||||
|
|
||||||
|
Task { @MainActor in
|
||||||
|
let ok: Bool = await model.renderToFile(url: url, format: format, duration: duration)
|
||||||
|
if ok { NSWorkspace.shared.activateFileViewerSelecting([url]) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func resetSession(_ sender: Any?) {
|
||||||
|
model.resetSession()
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func restartApp(_ sender: Any?) {
|
||||||
|
let alert: NSAlert = NSAlert()
|
||||||
|
alert.messageText = "Restart to reclaim memory?"
|
||||||
|
alert.informativeText =
|
||||||
|
"Relaunches the app to free the \(model.loadedSnippetCount) mapped snippet "
|
||||||
|
+ "dylibs (compiled snippets can't be unloaded any other way). Unsaved changes "
|
||||||
|
+ "in the buffer will be lost."
|
||||||
|
alert.addButton(withTitle: "Restart")
|
||||||
|
alert.addButton(withTitle: "Cancel")
|
||||||
|
guard alert.runModal() == .alertFirstButtonReturn else { return }
|
||||||
|
LyrebirdScratchMenuController.relaunchApp()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Relaunch the host `.app`: open a fresh instance, then terminate this one
|
||||||
|
/// once it is confirmed on its way. The new process starts with zero mapped
|
||||||
|
/// snippet dylibs — the only way to reclaim that memory. On a launch failure
|
||||||
|
/// the current process is **kept** (and the user informed) rather than
|
||||||
|
/// terminated into oblivion.
|
||||||
|
private static func relaunchApp() {
|
||||||
|
let url: URL = Bundle.main.bundleURL
|
||||||
|
let config: NSWorkspace.OpenConfiguration = NSWorkspace.OpenConfiguration()
|
||||||
|
config.createsNewApplicationInstance = true
|
||||||
|
NSWorkspace.shared.openApplication(at: url, configuration: config) { app, error in
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
if let error: Error = error {
|
||||||
|
let alert: NSAlert = NSAlert()
|
||||||
|
alert.messageText = "Restart failed"
|
||||||
|
alert.informativeText =
|
||||||
|
"Could not relaunch the app (\(error.localizedDescription)). "
|
||||||
|
+ "The current session is unchanged."
|
||||||
|
alert.runModal()
|
||||||
|
} else if app != nil {
|
||||||
|
NSApp.terminate(nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@objc private func clearSynths(_ sender: Any?) {
|
@objc private func clearSynths(_ sender: Any?) {
|
||||||
model.clearTracked()
|
model.clearTracked()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import Foundation
|
|||||||
import CoreGraphics
|
import CoreGraphics
|
||||||
import LyrebirdSynth
|
import LyrebirdSynth
|
||||||
// Re-exported so consumers that link only the `LyrebirdLiveCompileUI` product
|
// Re-exported so consumers that link only the `LyrebirdLiveCompileUI` product
|
||||||
// (e.g. the LyrebirdScratchDemo app) get the `LyrebirdLiveCompile` API
|
// (e.g. the LyrebirdScratch app) get the `LyrebirdLiveCompile` API
|
||||||
// (`LiveSession`, …) without separately linking the `LyrebirdLiveCompile`
|
// (`LiveSession`, …) without separately linking the `LyrebirdLiveCompile`
|
||||||
// dynamic product — which clashes in Xcode with the static target embed.
|
// dynamic product — which clashes in Xcode with the static target embed.
|
||||||
@_exported import LyrebirdLiveCompile
|
@_exported import LyrebirdLiveCompile
|
||||||
@@ -42,27 +42,54 @@ public final class LyrebirdScratchModel: ObservableObject {
|
|||||||
// ⌘⇧↩ — additive run (keep previously played synths around).
|
// ⌘⇧↩ — additive run (keep previously played synths around).
|
||||||
//
|
//
|
||||||
// The snippet body has `context: SnippetContext` in scope.
|
// The snippet body has `context: SnippetContext` in scope.
|
||||||
// `context.engine` → the host `SynthesisEngine`.
|
// `context.play { <graph> }` → play a bare generator graph, no subclass needed.
|
||||||
// `context.play(synth)` → adds a `Synthesizer` and tracks it for cleanup.
|
// `context.play(synth)` → add a `Synthesizer` you declared.
|
||||||
// `context.reportMessage(_)`→ writes back to the host (useful for `print`-style probes).
|
// `context.engine` → the host `SynthesisEngine`.
|
||||||
|
// `context.reportMessage(_)` → write back to the host (`print`-style probes).
|
||||||
|
|
||||||
class SineSynth: SynthesizerBase {
|
context.play { Pan2(input: OscSin.Audio(freq: 440, mul: 0.15), pan: 0) }
|
||||||
override func build() {
|
|
||||||
let sine = OscSin.Audio(freq: 440, mul: 0.15)
|
|
||||||
let stereo = Pan2(input: sine, pan: 0)
|
|
||||||
output(bus: 0, source: stereo)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let synth = SineSynth()
|
|
||||||
_ = context.play(synth)
|
|
||||||
context.reportMessage("playing 440 Hz sine — stereo, centered")
|
context.reportMessage("playing 440 Hz sine — stereo, centered")
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
/// Placeholder for the interpreted graph-DSL mode. Shows the instant path:
|
||||||
|
/// no `context`, no subclass — just generator-graph expressions, one per
|
||||||
|
/// line, spelled exactly as they would be in a Lyrebird `build()`.
|
||||||
|
public nonisolated static let graphDSLPlaceholder: String = """
|
||||||
|
# Graph DSL — instant, no compile. One graph expression per line.
|
||||||
|
# A bare line plays anonymously; `name = …` plays a named, hot-swappable slot.
|
||||||
|
# Generators are spelled exactly as in Swift: OscSin.Audio(freq: 440) * 0.1
|
||||||
|
|
||||||
|
bass = OscSawtooth.Audio(freq: 55, mul: 0.15)
|
||||||
|
Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0)
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
/// The seed text for a given evaluation mode.
|
||||||
|
public nonisolated static func defaultPlaceholder(for mode: ScratchEvalMode) -> String {
|
||||||
|
switch mode {
|
||||||
|
case .swift: return defaultPlaceholder
|
||||||
|
case .graphDSL: return graphDSLPlaceholder
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Current editor text. View binds to this; user edits flow back here via
|
/// Current editor text. View binds to this; user edits flow back here via
|
||||||
/// the `NSTextView` delegate inside `LyrebirdScratchView`.
|
/// the `NSTextView` delegate inside `LyrebirdScratchView`.
|
||||||
@Published public var text: String
|
///
|
||||||
|
/// Edits recompute ``reevalState`` (unless a compile is in flight, which
|
||||||
|
/// owns the state until it resolves).
|
||||||
|
@Published public var text: String {
|
||||||
|
didSet { recomputeReevalStateAfterEdit() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Structured re-evaluation readiness signal. See ``ReevalState``. The view
|
||||||
|
/// binds a status badge to this and gates the Run controls on
|
||||||
|
/// ``ReevalState/canEvaluate``.
|
||||||
|
@Published public private(set) var reevalState: ReevalState
|
||||||
|
|
||||||
|
/// Text of the most recent *successful* run. `nil` before the first
|
||||||
|
/// successful run. Compared against ``text`` to decide `.clean` vs `.dirty`.
|
||||||
|
private var lastEvaluatedText: String?
|
||||||
|
|
||||||
/// Parsed swiftc diagnostics from the last `run(additive:)` invocation.
|
/// Parsed swiftc diagnostics from the last `run(additive:)` invocation.
|
||||||
/// Empty when the last run compiled cleanly or has not yet been attempted.
|
/// Empty when the last run compiled cleanly or has not yet been attempted.
|
||||||
@@ -72,10 +99,83 @@ public final class LyrebirdScratchModel: ObservableObject {
|
|||||||
/// Updated by `run(additive:)` and `clearTracked()`.
|
/// Updated by `run(additive:)` and `clearTracked()`.
|
||||||
@Published public private(set) var statusMessage: String = ""
|
@Published public private(set) var statusMessage: String = ""
|
||||||
|
|
||||||
|
/// Accumulated console log shown in the always-open right panel: snippet
|
||||||
|
/// `context.reportMessage(_:)` output, compile/DSL errors, and run notices,
|
||||||
|
/// oldest first. Capped at ``maxConsoleEntries``.
|
||||||
|
@Published public private(set) var consoleEntries: [ScratchConsoleEntry] = []
|
||||||
|
|
||||||
|
/// Upper bound on retained console lines; the oldest are dropped past it.
|
||||||
|
public nonisolated static let maxConsoleEntries: Int = 500
|
||||||
|
|
||||||
|
private var _consoleSeq: Int = 0
|
||||||
|
|
||||||
|
/// Append one console line, trimming the log to ``maxConsoleEntries``.
|
||||||
|
private func appendConsole(_ kind: ScratchConsoleEntry.Kind, _ text: String, location: String? = nil) {
|
||||||
|
_consoleSeq += 1
|
||||||
|
consoleEntries.append(ScratchConsoleEntry(id: _consoleSeq, kind: kind, text: text, location: location))
|
||||||
|
let overflow: Int = consoleEntries.count - LyrebirdScratchModel.maxConsoleEntries
|
||||||
|
if overflow > 0 { consoleEntries.removeFirst(overflow) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Empty the console.
|
||||||
|
public func clearConsole() {
|
||||||
|
consoleEntries.removeAll()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After a run resolves, move the snippet's report messages into the console
|
||||||
|
/// (they arrive in order during the run), then the run outcome: on failure,
|
||||||
|
/// each diagnostic as an error line; on success, a one-line notice.
|
||||||
|
private func recordRunConsole(succeeded: Bool) {
|
||||||
|
for message: String in session.drainMessages() {
|
||||||
|
appendConsole(.message, message)
|
||||||
|
}
|
||||||
|
if succeeded {
|
||||||
|
appendConsole(.info, statusMessage)
|
||||||
|
} else if diagnostics.isEmpty {
|
||||||
|
appendConsole(.error, statusMessage)
|
||||||
|
} else {
|
||||||
|
for diagnostic: Diagnostic in diagnostics {
|
||||||
|
let location: String? = diagnostic.line.map { "\($0):\(diagnostic.column)" }
|
||||||
|
appendConsole(.error, diagnostic.message, location: location)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Mirror of `session.trackedSynthCount`, refreshed after every `run` /
|
/// Mirror of `session.trackedSynthCount`, refreshed after every `run` /
|
||||||
/// `clearTracked` call so the toolbar can show the count without polling.
|
/// `clearTracked` call so the toolbar can show the count without polling.
|
||||||
@Published public private(set) var trackedSynthCount: Int
|
@Published public private(set) var trackedSynthCount: Int
|
||||||
|
|
||||||
|
/// Mirror of `session.loadedSnippetCount` — compiled snippet dylibs mapped
|
||||||
|
/// into the process this session. Each successful **Swift-mode** run maps
|
||||||
|
/// one; they are never unloaded (`dlclose` is unsafe for Swift dylibs — see
|
||||||
|
/// ``LiveSession/resetAll()``), so this only grows until a process restart.
|
||||||
|
/// Graph-DSL runs add nothing. Refreshed alongside ``trackedSynthCount``.
|
||||||
|
@Published public private(set) var loadedSnippetCount: Int
|
||||||
|
|
||||||
|
/// Count of mapped snippet dylibs past which the editor nudges the user to
|
||||||
|
/// restart (or switch to the leak-free Graph DSL mode).
|
||||||
|
public nonisolated static let snippetRestartThreshold: Int = 50
|
||||||
|
|
||||||
|
/// A restart suggestion once ``loadedSnippetCount`` reaches
|
||||||
|
/// ``snippetRestartThreshold``, else `nil`. The mapped dylibs cannot be
|
||||||
|
/// reclaimed without a process restart (by design), so this is the
|
||||||
|
/// user-facing safety valve over that leak.
|
||||||
|
public var snippetMemoryHint: String? {
|
||||||
|
LyrebirdScratchModel.snippetMemoryHint(count: loadedSnippetCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pure form of ``snippetMemoryHint`` — the message for `count` mapped
|
||||||
|
/// snippets, or `nil` below `threshold`. Factored out so the boundary is
|
||||||
|
/// unit-testable without running dozens of real compiles.
|
||||||
|
nonisolated static func snippetMemoryHint(
|
||||||
|
count: Int,
|
||||||
|
threshold: Int = LyrebirdScratchModel.snippetRestartThreshold
|
||||||
|
) -> String? {
|
||||||
|
guard count >= threshold else { return nil }
|
||||||
|
return "\(count) compiled snippets are mapped and can't be freed without "
|
||||||
|
+ "restarting. Restart to reclaim memory, or use Graph DSL mode (no compile, no leak)."
|
||||||
|
}
|
||||||
|
|
||||||
/// `true` while a `run(additive:)` invocation is awaiting the background
|
/// `true` while a `run(additive:)` invocation is awaiting the background
|
||||||
/// swiftc compile. View code disables Run / Run Additive buttons against
|
/// swiftc compile. View code disables Run / Run Additive buttons against
|
||||||
/// this so a second compile cannot stack on top of a still-running one.
|
/// this so a second compile cannot stack on top of a still-running one.
|
||||||
@@ -93,8 +193,56 @@ public final class LyrebirdScratchModel: ObservableObject {
|
|||||||
/// horizontally.
|
/// horizontally.
|
||||||
@Published public var wrapsLines: Bool = true
|
@Published public var wrapsLines: Bool = true
|
||||||
|
|
||||||
|
/// The current editor selection text (empty when nothing is selected).
|
||||||
|
/// Pushed by the editor on selection change; drives ``hasSelection`` and
|
||||||
|
/// ``runSelection()``.
|
||||||
|
@Published public private(set) var selectionText: String = ""
|
||||||
|
|
||||||
|
/// `true` when the editor has a non-whitespace selection available to run.
|
||||||
|
public var hasSelection: Bool {
|
||||||
|
!selectionText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record the editor's current selection. Called by the editor's
|
||||||
|
/// selection-change delegate; empty string clears it.
|
||||||
|
public func updateSelection(_ text: String) {
|
||||||
|
guard text != selectionText else { return } // avoid redundant republish
|
||||||
|
selectionText = text
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which evaluator ``run(additive:)`` sends the buffer through. `.swift`
|
||||||
|
/// compiles a snippet dylib; `.graphDSL` interprets a generator graph
|
||||||
|
/// instantly. Toggle via ``switchMode(to:)`` so the seed placeholder swaps
|
||||||
|
/// with the mode. See ``ScratchEvalMode``.
|
||||||
|
@Published public private(set) var evalMode: ScratchEvalMode = .swift
|
||||||
|
|
||||||
public let session: LiveSession
|
public let session: LiveSession
|
||||||
|
|
||||||
|
/// Lazily-created code-completion service (Swift mode only). Spun up on the
|
||||||
|
/// first completion request so a session that never triggers completion
|
||||||
|
/// never launches `sourcekit-lsp`.
|
||||||
|
private var _completion: SnippetCompletionService?
|
||||||
|
|
||||||
|
/// Fetch Swift code-completion candidates for the current buffer at a
|
||||||
|
/// zero-based user-space `line` / `character` (UTF-16). Returns `[]` in
|
||||||
|
/// graph-DSL mode (the interpreter needs no LSP) or on any LSP failure —
|
||||||
|
/// completion is best-effort and never surfaces an error to the editor.
|
||||||
|
public func completionItems(line: Int, character: Int) async -> [LSPCompletionItem] {
|
||||||
|
guard evalMode == .swift else { return [] }
|
||||||
|
let service: SnippetCompletionService
|
||||||
|
if let existing: SnippetCompletionService = _completion {
|
||||||
|
service = existing
|
||||||
|
} else {
|
||||||
|
service = SnippetCompletionService(session: session)
|
||||||
|
_completion = service
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
return try await service.completions(userBody: text, line: line, character: character)
|
||||||
|
} catch {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public nonisolated static let minFontSize: CGFloat = 9
|
public nonisolated static let minFontSize: CGFloat = 9
|
||||||
public nonisolated static let maxFontSize: CGFloat = 32
|
public nonisolated static let maxFontSize: CGFloat = 32
|
||||||
public nonisolated static let defaultFontSize: CGFloat = 13
|
public nonisolated static let defaultFontSize: CGFloat = 13
|
||||||
@@ -124,6 +272,48 @@ public final class LyrebirdScratchModel: ObservableObject {
|
|||||||
self.session = session
|
self.session = session
|
||||||
self.text = initialText
|
self.text = initialText
|
||||||
self.trackedSynthCount = session.trackedSynthCount
|
self.trackedSynthCount = session.trackedSynthCount
|
||||||
|
self.loadedSnippetCount = session.loadedSnippetCount
|
||||||
|
// No run yet: blank buffer is `.empty`, otherwise `.dirty` (runnable,
|
||||||
|
// never evaluated). `lastEvaluatedText` stays nil until a run succeeds.
|
||||||
|
self.reevalState = LyrebirdScratchModel.isBlank(initialText) ? .empty : .dirty
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `text` is empty once whitespace and newlines are stripped.
|
||||||
|
private nonisolated static func isBlank(_ text: String) -> Bool {
|
||||||
|
text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recompute ``reevalState`` from the current buffer after a user edit.
|
||||||
|
/// A no-op while a compile is in flight — the run owns the state until it
|
||||||
|
/// resolves (edits made mid-compile are re-evaluated once it finishes).
|
||||||
|
private func recomputeReevalStateAfterEdit() {
|
||||||
|
guard !isCompiling else { return }
|
||||||
|
// Assign only on a real change: after the first edit dirties the buffer,
|
||||||
|
// every later keystroke re-derives `.dirty` — republishing an unchanged
|
||||||
|
// value would re-render the whole view for nothing.
|
||||||
|
let next: ReevalState = derivedIdleState()
|
||||||
|
if next != reevalState { reevalState = next }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Settle a `.queued` state once its scheduled swap has become audible.
|
||||||
|
/// Called on the editor's heartbeat (the view's refresh timer): when the
|
||||||
|
/// session no longer reports a pending swap, drop back to the idle state
|
||||||
|
/// (`.clean`, or `.dirty` if the buffer was edited while queued). No-op
|
||||||
|
/// unless the current state is `.queued`.
|
||||||
|
public func refreshQueuedState() {
|
||||||
|
guard case .queued = reevalState else { return }
|
||||||
|
if session.pendingSwapBeat == nil {
|
||||||
|
reevalState = derivedIdleState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The readiness state implied by the current buffer when no compile is in
|
||||||
|
/// flight: `.empty` for a blank buffer, `.clean` when it matches the last
|
||||||
|
/// successful run, `.dirty` otherwise.
|
||||||
|
private func derivedIdleState() -> ReevalState {
|
||||||
|
if LyrebirdScratchModel.isBlank(text) { return .empty }
|
||||||
|
if let last: String = lastEvaluatedText, last == text { return .clean }
|
||||||
|
return .dirty
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Compile and execute the current `text`. Updates `diagnostics`,
|
/// Compile and execute the current `text`. Updates `diagnostics`,
|
||||||
@@ -140,19 +330,49 @@ public final class LyrebirdScratchModel: ObservableObject {
|
|||||||
/// without throwing; `false` otherwise.
|
/// without throwing; `false` otherwise.
|
||||||
@discardableResult
|
@discardableResult
|
||||||
public func run(additive: Bool) async -> Bool {
|
public func run(additive: Bool) async -> Bool {
|
||||||
|
switch evalMode {
|
||||||
|
case .swift: return await runSwiftSnippet(body: text, additive: additive, recordBaseline: true)
|
||||||
|
case .graphDSL: return runGraphDSLBuffer(body: text, additive: additive, recordBaseline: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluate just the current editor selection as an **additive** run: the
|
||||||
|
/// selected text is compiled/interpreted and added to whatever is already
|
||||||
|
/// playing (never a non-additive replace), and it does not disturb the
|
||||||
|
/// whole-buffer re-evaluation baseline — the buffer's `.clean`/`.dirty`
|
||||||
|
/// status still reflects the last *whole* run. No-op when nothing is
|
||||||
|
/// selected. Works in both Swift and Graph DSL modes.
|
||||||
|
@discardableResult
|
||||||
|
public func runSelection() async -> Bool {
|
||||||
|
guard hasSelection else { return false }
|
||||||
|
let body: String = selectionText
|
||||||
|
switch evalMode {
|
||||||
|
case .swift: return await runSwiftSnippet(body: body, additive: true, recordBaseline: false)
|
||||||
|
case .graphDSL: return runGraphDSLBuffer(body: body, additive: true, recordBaseline: false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Swift path: compile `body` to a dylib off-main and run it.
|
||||||
|
/// `recordBaseline` distinguishes a whole-buffer run (updates the `.clean`
|
||||||
|
/// baseline) from a selection run (leaves it untouched).
|
||||||
|
private func runSwiftSnippet(body: String, additive: Bool, recordBaseline: Bool) async -> Bool {
|
||||||
guard !isCompiling else { return false }
|
guard !isCompiling else { return false }
|
||||||
let body: String = text
|
|
||||||
diagnostics = []
|
diagnostics = []
|
||||||
statusMessage = "Compiling…"
|
statusMessage = "Compiling…"
|
||||||
isCompiling = true
|
isCompiling = true
|
||||||
|
reevalState = .compiling
|
||||||
|
var runSucceeded: Bool = false
|
||||||
defer {
|
defer {
|
||||||
isCompiling = false
|
isCompiling = false
|
||||||
trackedSynthCount = session.trackedSynthCount
|
trackedSynthCount = session.trackedSynthCount
|
||||||
|
loadedSnippetCount = session.loadedSnippetCount
|
||||||
|
recordRunConsole(succeeded: runSucceeded)
|
||||||
}
|
}
|
||||||
do {
|
do {
|
||||||
try await session.compileAndRunAsync(body, additive: additive)
|
try await session.compileAndRunAsync(body, additive: additive)
|
||||||
let mode: String = additive ? "additive" : "replaced"
|
statusMessage = "Ran \(runDescription(additive: additive, recordBaseline: recordBaseline))."
|
||||||
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
settleReeval(body: body, recordBaseline: recordBaseline)
|
||||||
|
runSucceeded = true
|
||||||
return true
|
return true
|
||||||
} catch let sessionError as LiveSessionError {
|
} catch let sessionError as LiveSessionError {
|
||||||
switch sessionError {
|
switch sessionError {
|
||||||
@@ -165,7 +385,7 @@ public final class LyrebirdScratchModel: ObservableObject {
|
|||||||
message: "\(underlying)",
|
message: "\(underlying)",
|
||||||
rawLine: 0
|
rawLine: 0
|
||||||
)]
|
)]
|
||||||
statusMessage = "Compile failed — see diagnostics below."
|
statusMessage = "Compile failed — see console."
|
||||||
} else {
|
} else {
|
||||||
diagnostics = diags
|
diagnostics = diags
|
||||||
let plural: String = diags.count == 1 ? "" : "s"
|
let plural: String = diags.count == 1 ? "" : "s"
|
||||||
@@ -173,19 +393,287 @@ public final class LyrebirdScratchModel: ObservableObject {
|
|||||||
}
|
}
|
||||||
case .compilerError(let underlying):
|
case .compilerError(let underlying):
|
||||||
statusMessage = "Compiler error: \(underlying)"
|
statusMessage = "Compiler error: \(underlying)"
|
||||||
|
case .graphDSLFailed(let diags, _):
|
||||||
|
// Not expected on the Swift path, but map it faithfully.
|
||||||
|
diagnostics = diags
|
||||||
|
statusMessage = "DSL error — \(diags.count) diagnostic(s)."
|
||||||
}
|
}
|
||||||
|
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||||
return false
|
return false
|
||||||
} catch {
|
} catch {
|
||||||
statusMessage = "Error: \(error)"
|
statusMessage = "Error: \(error)"
|
||||||
|
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Forward to `LiveSession.clearTracked()` and refresh `trackedSynthCount`.
|
/// Graph-DSL path: interpret `body` in-process — instant, no swiftc, so no
|
||||||
public func clearTracked() {
|
/// `isCompiling` spinner and no `await`. A parse/build failure leaves the
|
||||||
session.clearTracked()
|
/// currently-playing graph untouched (the session builds before it mutates).
|
||||||
|
private func runGraphDSLBuffer(body: String, additive: Bool, recordBaseline: Bool) -> Bool {
|
||||||
|
guard !isCompiling else { return false }
|
||||||
|
diagnostics = []
|
||||||
|
var runSucceeded: Bool = false
|
||||||
|
defer {
|
||||||
|
trackedSynthCount = session.trackedSynthCount
|
||||||
|
loadedSnippetCount = session.loadedSnippetCount
|
||||||
|
recordRunConsole(succeeded: runSucceeded)
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
try session.runGraphDSL(body, additive: additive)
|
||||||
|
statusMessage = "Ran DSL \(runDescription(additive: additive, recordBaseline: recordBaseline))."
|
||||||
|
settleReeval(body: body, recordBaseline: recordBaseline)
|
||||||
|
runSucceeded = true
|
||||||
|
return true
|
||||||
|
} catch let sessionError as LiveSessionError {
|
||||||
|
if case .graphDSLFailed(let diags, _) = sessionError {
|
||||||
|
diagnostics = diags
|
||||||
|
let plural: String = diags.count == 1 ? "" : "s"
|
||||||
|
statusMessage = "DSL error — \(diags.count) diagnostic\(plural)."
|
||||||
|
} else {
|
||||||
|
statusMessage = "Error: \(sessionError)"
|
||||||
|
}
|
||||||
|
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||||
|
return false
|
||||||
|
} catch {
|
||||||
|
statusMessage = "Error: \(error)"
|
||||||
|
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Settle the readiness state after a successful run. For a whole-buffer run
|
||||||
|
/// (`recordBaseline`), record the run text as the `.clean` baseline; for a
|
||||||
|
/// selection run, leave the baseline untouched (the buffer's status still
|
||||||
|
/// reflects the last whole run). Either way resolve to `.queued` when the
|
||||||
|
/// buffer is unchanged and a quantized swap is pending, else the derived
|
||||||
|
/// idle state.
|
||||||
|
private func settleReeval(body: String, recordBaseline: Bool) {
|
||||||
|
if recordBaseline { lastEvaluatedText = body }
|
||||||
|
let idle: ReevalState = derivedIdleState()
|
||||||
|
if idle == .clean, let beat: Double = session.pendingSwapBeat {
|
||||||
|
reevalState = .queued(untilBeat: beat)
|
||||||
|
} else {
|
||||||
|
reevalState = idle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Settle the readiness state after a *failed* run. A whole-buffer failure
|
||||||
|
/// sets `.failed` (the badge should reflect that the buffer doesn't run). A
|
||||||
|
/// selection failure must NOT touch the whole-buffer badge — the buffer and
|
||||||
|
/// its last whole-run baseline are unaffected — so it recomputes the derived
|
||||||
|
/// idle state and marks the status line as a selection failure. Diagnostics
|
||||||
|
/// (already set by the caller) still surface the error either way.
|
||||||
|
private func settleReevalAfterFailure(recordBaseline: Bool) {
|
||||||
|
if recordBaseline {
|
||||||
|
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||||
|
} else {
|
||||||
|
statusMessage = "Selection — " + statusMessage
|
||||||
|
reevalState = derivedIdleState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Status-line phrase for a run: distinguishes a whole-buffer replace/add
|
||||||
|
/// from a selection add, and includes the live tracked-synth count.
|
||||||
|
private func runDescription(additive: Bool, recordBaseline: Bool) -> String {
|
||||||
|
let what: String
|
||||||
|
if !recordBaseline {
|
||||||
|
what = "selection (added)"
|
||||||
|
} else {
|
||||||
|
what = additive ? "additive" : "replaced"
|
||||||
|
}
|
||||||
|
return "(\(what)). Tracked synths: \(session.trackedSynthCount)"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Switch evaluation mode. When the buffer still holds the *current* mode's
|
||||||
|
/// untouched placeholder, swap in the target mode's placeholder so the seed
|
||||||
|
/// example matches the mode; any edited buffer is left as-is.
|
||||||
|
///
|
||||||
|
/// The new mode's evaluator has not run whatever is on screen, so the last-run
|
||||||
|
/// baseline is dropped (the buffer reads as `.dirty`) and any diagnostics from
|
||||||
|
/// a prior run in the old mode are cleared — leaving them would show gutter
|
||||||
|
/// markers against a buffer the current mode never evaluated.
|
||||||
|
public func switchMode(to mode: ScratchEvalMode) {
|
||||||
|
guard mode != evalMode else { return }
|
||||||
|
if text == LyrebirdScratchModel.defaultPlaceholder(for: evalMode) {
|
||||||
|
text = LyrebirdScratchModel.defaultPlaceholder(for: mode)
|
||||||
|
}
|
||||||
|
lastEvaluatedText = nil
|
||||||
|
diagnostics = []
|
||||||
|
evalMode = mode
|
||||||
|
reevalState = derivedIdleState()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// In-process session reset: stop all snippet audio, shut down the code-
|
||||||
|
/// completion server (freeing its subprocess + temp workspace), and clear
|
||||||
|
/// diagnostics and the run baseline. **Non-destructive** — the editor buffer
|
||||||
|
/// (the user's code) is left untouched, so this needs no confirmation.
|
||||||
|
///
|
||||||
|
/// It reclaims everything it *can* in-process — but **not** the compiled
|
||||||
|
/// snippet dylibs (`loadedSnippetCount`), which cannot be unloaded safely
|
||||||
|
/// (`dlclose` is unsafe for Swift dylibs). Only relaunching the process frees
|
||||||
|
/// those; the status line says so, and the "Restart" command does it.
|
||||||
|
///
|
||||||
|
/// No-op while a compile is in flight (matching the run methods' guard) — a
|
||||||
|
/// reset must not tear the session down under an active `compileAndRunAsync`.
|
||||||
|
/// Pretty-print the buffer with `swift-format` (off the main thread),
|
||||||
|
/// replacing the text on success. Logs the outcome to the console; on a
|
||||||
|
/// parse error or missing toolchain the buffer is left untouched.
|
||||||
|
public func formatBuffer() async {
|
||||||
|
guard !isCompiling else { return }
|
||||||
|
let source: String = text
|
||||||
|
guard !LyrebirdScratchModel.isBlank(source) else { return }
|
||||||
|
// Hold the busy flag across the subprocess round-trip so a second Format
|
||||||
|
// (or a Run) can't overlap, and re-check the buffer before applying: the
|
||||||
|
// user may keep typing while `swift-format` runs, and a result computed
|
||||||
|
// from the now-stale `source` must not clobber those edits. `reevalState`
|
||||||
|
// goes `.compiling` too so the Run/Render menu items (validated on
|
||||||
|
// `reevalState.canEvaluate`) actually disable during the format.
|
||||||
|
isCompiling = true
|
||||||
|
reevalState = .compiling
|
||||||
|
defer {
|
||||||
|
isCompiling = false
|
||||||
|
reevalState = derivedIdleState()
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
let formatted: String = try await Task.detached(priority: .userInitiated) {
|
||||||
|
try SwiftFormatter.format(source: source)
|
||||||
|
}.value
|
||||||
|
guard text == source else {
|
||||||
|
appendConsole(.error, "Buffer changed during formatting — result discarded.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if formatted != source {
|
||||||
|
text = formatted
|
||||||
|
}
|
||||||
|
appendConsole(.info, "Formatted.")
|
||||||
|
} catch {
|
||||||
|
appendConsole(.error, "Format failed: \(error)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Render the current selection (or the whole buffer when nothing is
|
||||||
|
/// selected) to an audio file, offline. Builds the snippet graph on a
|
||||||
|
/// throwaway engine driven by an `NRTDriver` — matching the live engine's
|
||||||
|
/// sample rate / channel count / bus layout — then renders `duration`
|
||||||
|
/// seconds off the main thread (`NRTDriver.start()` blocks). Logs the
|
||||||
|
/// outcome to the console.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - url: Destination file. Its extension should match `format`.
|
||||||
|
/// - format: Container and PCM encoding (``AudioFileFormat``). Defaults to
|
||||||
|
/// `.cafFloat32`. RF64/CAF are uncapped; plain WAV/AIFF throw past 4 GB.
|
||||||
|
/// - duration: Render length in seconds. Must be finite and > 0.
|
||||||
|
/// - Returns: `true` when the file was rendered (so the caller can reveal it).
|
||||||
|
@discardableResult
|
||||||
|
public func renderToFile(
|
||||||
|
url: URL,
|
||||||
|
format: AudioFileFormat = .cafFloat32,
|
||||||
|
duration: Double
|
||||||
|
) async -> Bool {
|
||||||
|
guard !isCompiling else { return false }
|
||||||
|
guard duration > 0, duration.isFinite else {
|
||||||
|
appendConsole(.error, "Render duration must be a positive number of seconds.")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
let code: String = hasSelection ? selectionText : text
|
||||||
|
guard !LyrebirdScratchModel.isBlank(code) else {
|
||||||
|
appendConsole(.error, "Nothing to render.")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// Gate the Run/Render menu items (validated on `reevalState.canEvaluate`)
|
||||||
|
// and any re-entrancy for the render's duration.
|
||||||
|
isCompiling = true
|
||||||
|
reevalState = .compiling
|
||||||
|
defer {
|
||||||
|
isCompiling = false
|
||||||
|
reevalState = derivedIdleState()
|
||||||
|
}
|
||||||
|
|
||||||
|
let live: SynthesisEngine = session.engine
|
||||||
|
let offline: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: live.blockSize,
|
||||||
|
controlBlockSize: live.controlBlockSize,
|
||||||
|
sampleRate: live.sampleRate,
|
||||||
|
numOutputChannels: live.numOutputChannels,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: live.numAudioBuses,
|
||||||
|
numControlBuses: live.numControlBuses,
|
||||||
|
driver: NRTDriver(outputURL: url, duration: duration, format: format)
|
||||||
|
)
|
||||||
|
let offlineSession: LiveSession = LiveSession(engine: offline, attachScope: false)
|
||||||
|
do {
|
||||||
|
// Build the graph on the offline engine (compile off-main, add on main).
|
||||||
|
try await offlineSession.compileAndRunAsync(code, additive: true)
|
||||||
|
// Render synchronously, off the main thread; NRTDriver writes the CAF.
|
||||||
|
// `stop()` runs inside the detached task (where `offline` lives): the
|
||||||
|
// driver returns with the engine still `isRunning`, and only `stop()`
|
||||||
|
// drains the node tree — without it every rendered graph leaks
|
||||||
|
// (matches EngineHost's NRT job teardown). Keeping it here also avoids
|
||||||
|
// a cross-actor use of the non-Sendable engine after the detached run.
|
||||||
|
try await Task.detached(priority: .userInitiated) {
|
||||||
|
defer { offline.stop() }
|
||||||
|
try offline.start()
|
||||||
|
}.value
|
||||||
|
appendConsole(.info, "Rendered \(String(format: "%.2f", duration)) s → \(url.lastPathComponent)")
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
appendConsole(.error, "Render failed: \(error)")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public func resetSession() {
|
||||||
|
guard !isCompiling else { return }
|
||||||
|
session.resetAll()
|
||||||
|
_completion?.shutdownSynchronously()
|
||||||
|
_completion = nil // recreated lazily on next completion
|
||||||
|
diagnostics = []
|
||||||
|
consoleEntries.removeAll()
|
||||||
|
lastEvaluatedText = nil
|
||||||
trackedSynthCount = session.trackedSynthCount
|
trackedSynthCount = session.trackedSynthCount
|
||||||
statusMessage = "Cleared tracked synths."
|
loadedSnippetCount = session.loadedSnippetCount
|
||||||
|
reevalState = derivedIdleState()
|
||||||
|
statusMessage = loadedSnippetCount > 0
|
||||||
|
? "Session reset. \(loadedSnippetCount) snippet dylibs still mapped — Restart to reclaim that memory."
|
||||||
|
: "Session reset."
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the audio engine if stopped, or stop it if running. Surfaces the
|
||||||
|
/// outcome (including a start failure — e.g. no audio device) on the status
|
||||||
|
/// line. The host normally starts the engine at launch; this lets the user
|
||||||
|
/// see the state and recover from a failed start without relaunching.
|
||||||
|
public func toggleEngine() {
|
||||||
|
let engine: SynthesisEngine = session.engine
|
||||||
|
if engine.isRunning {
|
||||||
|
engine.stop()
|
||||||
|
statusMessage = "Engine stopped."
|
||||||
|
} else {
|
||||||
|
do {
|
||||||
|
try engine.start()
|
||||||
|
statusMessage = "Engine started."
|
||||||
|
} catch {
|
||||||
|
statusMessage = "Engine failed to start: \(error)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Full reset: remove both the anonymous tracked synths *and* every named
|
||||||
|
/// slot from the engine, then refresh `trackedSynthCount`.
|
||||||
|
///
|
||||||
|
/// Clearing the engine means nothing the buffer produced is still playing,
|
||||||
|
/// so the "last run" baseline is dropped and the buffer reads as `.dirty`
|
||||||
|
/// (or `.empty`) — a re-evaluation is again meaningful.
|
||||||
|
public func clearTracked() {
|
||||||
|
session.resetAll()
|
||||||
|
trackedSynthCount = session.trackedSynthCount
|
||||||
|
// `resetAll` stops audio but does NOT unload the compiled snippet dylibs
|
||||||
|
// (unsafe), so the mapped-snippet count is unchanged — refresh the mirror
|
||||||
|
// so the UI stays truthful about it.
|
||||||
|
loadedSnippetCount = session.loadedSnippetCount
|
||||||
|
statusMessage = "Cleared all synths (tracked + slots)."
|
||||||
|
lastEvaluatedText = nil
|
||||||
|
reevalState = derivedIdleState()
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Snippet save / load
|
// MARK: - Snippet save / load
|
||||||
@@ -197,10 +685,14 @@ public final class LyrebirdScratchModel: ObservableObject {
|
|||||||
/// `NSOpenPanel` UI; this method does the IO.
|
/// `NSOpenPanel` UI; this method does the IO.
|
||||||
public func load(from url: URL) throws {
|
public func load(from url: URL) throws {
|
||||||
let loaded: String = try String(contentsOf: url, encoding: .utf8)
|
let loaded: String = try String(contentsOf: url, encoding: .utf8)
|
||||||
|
// Drop the run baseline first so the `text` didSet — and the explicit
|
||||||
|
// recompute below — treat freshly loaded content as unrun (`.dirty`).
|
||||||
|
lastEvaluatedText = nil
|
||||||
text = loaded
|
text = loaded
|
||||||
documentURL = url
|
documentURL = url
|
||||||
diagnostics = []
|
diagnostics = []
|
||||||
statusMessage = "Loaded \(url.lastPathComponent)."
|
statusMessage = "Loaded \(url.lastPathComponent)."
|
||||||
|
reevalState = derivedIdleState()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Write `text` to `url` as UTF-8, set ``documentURL``, refresh status.
|
/// Write `text` to `url` as UTF-8, set ``documentURL``, refresh status.
|
||||||
|
|||||||
@@ -45,19 +45,48 @@ import LyrebirdLiveCompile
|
|||||||
///
|
///
|
||||||
/// ## Threading
|
/// ## Threading
|
||||||
///
|
///
|
||||||
/// All UI work is `@MainActor`-isolated. The Run / Run Additive buttons
|
/// All UI work is `@MainActor`-isolated. The Run / Run Additive commands (in the
|
||||||
/// dispatch a `Task` that awaits `LyrebirdScratchModel.run(additive:)`, which
|
/// menu bar built by ``LyrebirdScratchMenuController``) dispatch a `Task` that
|
||||||
/// itself awaits `LiveSession.compileAndRunAsync`. The swiftc subprocess runs
|
/// awaits `LyrebirdScratchModel.run(additive:)`, which itself awaits
|
||||||
/// on a background `Task.detached`; the snippet entry then resumes on the
|
/// `LiveSession.compileAndRunAsync`. The swiftc subprocess runs on a background
|
||||||
/// main actor so it can touch UI-side state. Both Run buttons disable while
|
/// `Task.detached`; the snippet entry then resumes on the main actor so it can
|
||||||
/// ``LyrebirdScratchModel/isCompiling`` is `true`.
|
/// touch UI-side state. The menu controller gates the Run commands on
|
||||||
|
/// ``ReevalState/canEvaluate`` (disabled while a compile is in flight or the
|
||||||
|
/// buffer is empty); `run(additive:)` additionally guards re-entrancy on
|
||||||
|
/// ``LyrebirdScratchModel/isCompiling``.
|
||||||
@MainActor
|
@MainActor
|
||||||
public struct LyrebirdScratchView: View {
|
public struct LyrebirdScratchView: View {
|
||||||
|
|
||||||
@StateObject private var model: LyrebirdScratchModel
|
@StateObject private var model: LyrebirdScratchModel
|
||||||
@State private var engineTick: Int = 0
|
/// Snapshot of the engine's non-`@Published` live stats, refreshed on the
|
||||||
|
/// heartbeat. Bound in place by the status rows — deliberately NOT via
|
||||||
|
/// `.id(tick)`, which forces a subview teardown/rebuild every tick and churns
|
||||||
|
/// the surrounding layout, nudging the editor's scroll position ("screen
|
||||||
|
/// jumping" while scrolled down). Updating an `@State` value re-renders the
|
||||||
|
/// labels in place with stable identity, so the layout stays put.
|
||||||
|
@State private var stats: EngineStats = EngineStats()
|
||||||
private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
|
private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
|
||||||
|
|
||||||
|
/// Non-`@Published` engine values polled on the heartbeat.
|
||||||
|
private struct EngineStats: Equatable {
|
||||||
|
var isRunning: Bool = false
|
||||||
|
var averageCPU: Double = 0
|
||||||
|
var peakCPU: Double = 0
|
||||||
|
var synthesizerCount: Int = 0
|
||||||
|
var groupCount: Int = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
private func snapshotStats() -> EngineStats {
|
||||||
|
let e: SynthesisEngine = model.session.engine
|
||||||
|
return EngineStats(
|
||||||
|
isRunning: e.isRunning,
|
||||||
|
averageCPU: e.averageCPU,
|
||||||
|
peakCPU: e.peakCPU,
|
||||||
|
synthesizerCount: e.synthesizerCount,
|
||||||
|
groupCount: e.groupCount
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// Construct with a fresh `LyrebirdScratchModel` wrapping `session`.
|
/// Construct with a fresh `LyrebirdScratchModel` wrapping `session`.
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
@@ -82,8 +111,35 @@ public struct LyrebirdScratchView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public var body: some View {
|
public var body: some View {
|
||||||
|
HStack(spacing: 0) {
|
||||||
|
mainColumn
|
||||||
|
Divider()
|
||||||
|
consolePanel
|
||||||
|
.frame(width: consoleWidth)
|
||||||
|
}
|
||||||
|
.frame(minWidth: scratchMinWidth + consoleWidth, minHeight: scratchMinHeight)
|
||||||
|
.onAppear {
|
||||||
|
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
|
||||||
|
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
|
||||||
|
// Idempotent — safe if `onAppear` fires again.
|
||||||
|
model.session.prewarm()
|
||||||
|
}
|
||||||
|
.onReceive(engineRefresh) { _ in
|
||||||
|
let next: EngineStats = snapshotStats()
|
||||||
|
if next != stats { stats = next }
|
||||||
|
// Settle a `.queued` readiness badge once its swap has fired.
|
||||||
|
model.refreshQueuedState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The editor column: engine controls, editor, status, engine panel.
|
||||||
|
private var mainColumn: some View {
|
||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
engineBar
|
engineBar
|
||||||
|
if let hint: String = model.snippetMemoryHint {
|
||||||
|
Divider()
|
||||||
|
snippetMemoryBanner(hint)
|
||||||
|
}
|
||||||
Divider()
|
Divider()
|
||||||
ScratchEditor(
|
ScratchEditor(
|
||||||
text: Binding(
|
text: Binding(
|
||||||
@@ -91,41 +147,172 @@ public struct LyrebirdScratchView: View {
|
|||||||
set: { model.text = $0 }
|
set: { model.text = $0 }
|
||||||
),
|
),
|
||||||
fontSize: model.fontSize,
|
fontSize: model.fontSize,
|
||||||
wrapsLines: model.wrapsLines
|
wrapsLines: model.wrapsLines,
|
||||||
|
requestCompletions: { line, character in
|
||||||
|
await model.completionItems(line: line, character: character)
|
||||||
|
},
|
||||||
|
onSelectionChanged: { selected in model.updateSelection(selected) }
|
||||||
)
|
)
|
||||||
.frame(minHeight: editorMinHeight)
|
.frame(minHeight: editorMinHeight)
|
||||||
Divider()
|
Divider()
|
||||||
statusBar
|
statusBar
|
||||||
if !model.diagnostics.isEmpty {
|
Divider()
|
||||||
Divider()
|
enginePanel
|
||||||
diagnosticsList
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Always-open right-side console: report messages, errors, and run notices,
|
||||||
|
/// oldest first, auto-scrolled to the newest.
|
||||||
|
private var consolePanel: some View {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
HStack {
|
||||||
|
Text("Console")
|
||||||
|
.font(.system(.caption, design: .monospaced))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
Spacer()
|
||||||
|
Button("Clear") { model.clearConsole() }
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.font(.system(.caption2, design: .monospaced))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.disabled(model.consoleEntries.isEmpty)
|
||||||
|
}
|
||||||
|
.padding(.horizontal, statusHPad)
|
||||||
|
.padding(.vertical, statusVPad)
|
||||||
|
Divider()
|
||||||
|
ScrollViewReader { proxy in
|
||||||
|
ScrollView {
|
||||||
|
LazyVStack(alignment: .leading, spacing: 2) {
|
||||||
|
ForEach(model.consoleEntries) { entry in
|
||||||
|
ConsoleRow(entry: entry)
|
||||||
|
}
|
||||||
|
Color.clear.frame(height: 1).id(consoleBottomID)
|
||||||
|
}
|
||||||
|
.padding(diagnosticListPadding)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
}
|
||||||
|
.onChange(of: model.consoleEntries.count) { _, _ in
|
||||||
|
proxy.scrollTo(consoleBottomID, anchor: .bottom)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
|
|
||||||
.onReceive(engineRefresh) { _ in engineTick &+= 1 }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private var engineBar: some View {
|
private var engineBar: some View {
|
||||||
let engine: SynthesisEngine = model.session.engine
|
let engine: SynthesisEngine = model.session.engine
|
||||||
return HStack(spacing: toolbarSpacing) {
|
return HStack(spacing: toolbarSpacing) {
|
||||||
Circle()
|
Button {
|
||||||
.fill(engine.isRunning ? Color.green : Color.red)
|
model.toggleEngine()
|
||||||
.frame(width: engineDotSize, height: engineDotSize)
|
stats = snapshotStats()
|
||||||
Text(engine.isRunning ? "engine running" : "engine stopped")
|
} label: {
|
||||||
.font(.system(.caption, design: .monospaced))
|
HStack(spacing: reevalBadgeSpacing) {
|
||||||
.foregroundStyle(.secondary)
|
Circle()
|
||||||
|
.fill(stats.isRunning ? Color.green : Color.red)
|
||||||
|
.frame(width: engineDotSize, height: engineDotSize)
|
||||||
|
Text(stats.isRunning ? "engine running" : "▶ start engine")
|
||||||
|
.font(.system(.caption, design: .monospaced))
|
||||||
|
.foregroundStyle(stats.isRunning ? Color.secondary : Color.primary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.help(stats.isRunning ? "Stop the audio engine" : "Start the audio engine")
|
||||||
Spacer()
|
Spacer()
|
||||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
|
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(stats.averageCPU))")
|
||||||
.font(.system(.caption, design: .monospaced))
|
.font(.system(.caption, design: .monospaced))
|
||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
Spacer().frame(width: 8)
|
Spacer().frame(width: 8)
|
||||||
Text("synths: \(model.trackedSynthCount)")
|
Text("synths: \(model.trackedSynthCount)")
|
||||||
.font(.system(.caption, design: .monospaced))
|
.font(.system(.caption, design: .monospaced))
|
||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
|
Spacer().frame(width: 8)
|
||||||
|
Text("snippets: \(model.loadedSnippetCount)")
|
||||||
|
.font(.system(.caption, design: .monospaced))
|
||||||
|
.foregroundStyle(model.snippetMemoryHint == nil ? Color.secondary : Color.orange)
|
||||||
|
.help("Compiled snippet dylibs mapped this session. They can't be "
|
||||||
|
+ "unloaded without restarting (Graph DSL mode maps none).")
|
||||||
}
|
}
|
||||||
.padding(.horizontal, toolbarPadding)
|
.padding(.horizontal, toolbarPadding)
|
||||||
.padding(.vertical, 6)
|
.padding(.vertical, 6)
|
||||||
.id(engineTick)
|
}
|
||||||
|
|
||||||
|
/// Warning strip shown once mapped snippet dylibs cross the restart
|
||||||
|
/// threshold — the user-facing safety valve over the by-design leak.
|
||||||
|
private func snippetMemoryBanner(_ hint: String) -> some View {
|
||||||
|
HStack(spacing: reevalBadgeSpacing) {
|
||||||
|
Image(systemName: "exclamationmark.triangle.fill")
|
||||||
|
.foregroundStyle(.orange)
|
||||||
|
Text(hint)
|
||||||
|
.font(.system(.caption, design: .monospaced))
|
||||||
|
.foregroundStyle(.primary)
|
||||||
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
}
|
||||||
|
.padding(.horizontal, toolbarPadding)
|
||||||
|
.padding(.vertical, 6)
|
||||||
|
.background(Color.orange.opacity(0.12))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bottom engine panel: a live output oscilloscope plus a compact status
|
||||||
|
/// readout (sample rate, CPU average/peak meters, node counts). The status
|
||||||
|
/// text refreshes in place off the ``stats`` snapshot — no `.id(tick)`
|
||||||
|
/// teardown, so the surrounding layout (and the editor's scroll) stays put.
|
||||||
|
private var enginePanel: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 6) {
|
||||||
|
if let scope: ScopeCapture = model.session.scope {
|
||||||
|
ScratchScopeView(capture: scope)
|
||||||
|
.frame(height: scopeHeight)
|
||||||
|
}
|
||||||
|
engineStatusRow
|
||||||
|
}
|
||||||
|
.padding(.horizontal, toolbarPadding)
|
||||||
|
.padding(.vertical, 6)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Heartbeat-refreshed engine readout: rate/channels, CPU meters, node counts.
|
||||||
|
private var engineStatusRow: some View {
|
||||||
|
let engine: SynthesisEngine = model.session.engine
|
||||||
|
return VStack(alignment: .leading, spacing: 6) {
|
||||||
|
HStack {
|
||||||
|
Text("Engine")
|
||||||
|
.font(.system(.caption, design: .monospaced))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
Spacer()
|
||||||
|
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch")
|
||||||
|
.font(.system(.caption2, design: .monospaced))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
cpuMeter(label: "CPU avg", value: stats.averageCPU)
|
||||||
|
cpuMeter(label: "CPU peak", value: stats.peakCPU)
|
||||||
|
Text("synths \(stats.synthesizerCount) · groups \(stats.groupCount) · snippets \(model.loadedSnippetCount)")
|
||||||
|
.font(.system(.caption2, design: .monospaced))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One labelled CPU meter bar. `value` is a fraction of one block period
|
||||||
|
/// (`[0, 1]`); the fill greens/oranges/reds as it approaches overrun.
|
||||||
|
private func cpuMeter(label: String, value: Double) -> some View {
|
||||||
|
let clamped: CGFloat = CGFloat(min(max(value, 0), 1))
|
||||||
|
let fill: Color = value > cpuMeterCriticalThreshold
|
||||||
|
? .red
|
||||||
|
: (value > cpuMeterWarningThreshold ? .orange : .green)
|
||||||
|
return HStack(spacing: 6) {
|
||||||
|
Text(label)
|
||||||
|
.font(.system(.caption2, design: .monospaced))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.frame(width: cpuLabelWidth, alignment: .leading)
|
||||||
|
GeometryReader { geo in
|
||||||
|
ZStack(alignment: .leading) {
|
||||||
|
RoundedRectangle(cornerRadius: 2).fill(Color.secondary.opacity(0.15))
|
||||||
|
RoundedRectangle(cornerRadius: 2).fill(fill)
|
||||||
|
.frame(width: geo.size.width * clamped)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(height: meterHeight)
|
||||||
|
Text(formatCPU(value))
|
||||||
|
.font(.system(.caption2, design: .monospaced))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
.frame(width: cpuValueWidth, alignment: .trailing)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func formatCPU(_ value: Double) -> String {
|
private func formatCPU(_ value: Double) -> String {
|
||||||
@@ -138,6 +325,14 @@ public struct LyrebirdScratchView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Evaluate just the current selection, additively. No-op when nothing is
|
||||||
|
/// selected.
|
||||||
|
public func runSelection() {
|
||||||
|
Task { @MainActor in
|
||||||
|
_ = await model.runSelection()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public func presentOpenPanel() {
|
public func presentOpenPanel() {
|
||||||
let panel: NSOpenPanel = NSOpenPanel()
|
let panel: NSOpenPanel = NSOpenPanel()
|
||||||
panel.allowedContentTypes = [.swiftSource]
|
panel.allowedContentTypes = [.swiftSource]
|
||||||
@@ -180,28 +375,94 @@ public struct LyrebirdScratchView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private var statusBar: some View {
|
private var statusBar: some View {
|
||||||
HStack {
|
HStack(spacing: toolbarSpacing) {
|
||||||
|
reevalBadge
|
||||||
Text(model.statusMessage.isEmpty ? "Ready." : model.statusMessage)
|
Text(model.statusMessage.isEmpty ? "Ready." : model.statusMessage)
|
||||||
.font(.system(.caption, design: .monospaced))
|
.font(.system(.caption, design: .monospaced))
|
||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
.lineLimit(1)
|
.lineLimit(1)
|
||||||
.truncationMode(.middle)
|
.truncationMode(.middle)
|
||||||
Spacer()
|
Spacer()
|
||||||
|
modePicker
|
||||||
}
|
}
|
||||||
.padding(.horizontal, statusHPad)
|
.padding(.horizontal, statusHPad)
|
||||||
.padding(.vertical, statusVPad)
|
.padding(.vertical, statusVPad)
|
||||||
}
|
}
|
||||||
|
|
||||||
private var diagnosticsList: some View {
|
/// Segmented toggle between the Swift-compile and instant graph-DSL
|
||||||
ScrollView {
|
/// evaluators. Routes through ``LyrebirdScratchModel/switchMode(to:)`` so the
|
||||||
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
|
/// seed placeholder follows the mode.
|
||||||
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diag in
|
private var modePicker: some View {
|
||||||
DiagnosticRow(diagnostic: diag)
|
Picker("Mode", selection: Binding(
|
||||||
}
|
get: { model.evalMode },
|
||||||
|
// Defer to the next main-actor tick: the Picker's `set` runs inside
|
||||||
|
// SwiftUI's view-update pass, and `switchMode` mutates @Published
|
||||||
|
// state ("Publishing changes from within view updates is not
|
||||||
|
// allowed"). Scheduling it off the current pass avoids that.
|
||||||
|
set: { newMode in Task { @MainActor in model.switchMode(to: newMode) } }
|
||||||
|
)) {
|
||||||
|
ForEach(ScratchEvalMode.allCases, id: \.self) { mode in
|
||||||
|
Text(mode.title).tag(mode)
|
||||||
}
|
}
|
||||||
.padding(diagnosticListPadding)
|
|
||||||
}
|
}
|
||||||
.frame(minHeight: diagnosticsMinHeight, maxHeight: diagnosticsMaxHeight)
|
.pickerStyle(.segmented)
|
||||||
|
.labelsHidden()
|
||||||
|
.fixedSize()
|
||||||
|
.help("Swift compiles a snippet dylib; Graph DSL interprets a generator graph instantly, no compile.")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-evaluation readiness indicator: a colored dot + short label bound to
|
||||||
|
/// ``LyrebirdScratchModel/reevalState``. Tells the user at a glance whether
|
||||||
|
/// an eval is available (dirty), in flight (compiling), matches what is
|
||||||
|
/// playing (clean), or failed.
|
||||||
|
private var reevalBadge: some View {
|
||||||
|
HStack(spacing: reevalBadgeSpacing) {
|
||||||
|
Circle()
|
||||||
|
.fill(reevalColor)
|
||||||
|
.frame(width: engineDotSize, height: engineDotSize)
|
||||||
|
Text(reevalLabel)
|
||||||
|
.font(.system(.caption, design: .monospaced))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
.help(reevalHelp)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var reevalColor: Color {
|
||||||
|
switch model.reevalState {
|
||||||
|
case .empty: return .secondary
|
||||||
|
case .clean: return .green
|
||||||
|
case .dirty: return .yellow
|
||||||
|
case .compiling: return .blue
|
||||||
|
case .queued: return .purple
|
||||||
|
case .failed: return .red
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var reevalLabel: String {
|
||||||
|
switch model.reevalState {
|
||||||
|
case .empty: return "empty"
|
||||||
|
case .clean: return "clean"
|
||||||
|
case .dirty: return "dirty"
|
||||||
|
case .compiling: return "compiling"
|
||||||
|
case .queued: return "queued"
|
||||||
|
case .failed: return "failed"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var reevalHelp: String {
|
||||||
|
switch model.reevalState {
|
||||||
|
case .empty: return "Nothing to evaluate."
|
||||||
|
case .clean: return "Buffer matches what is playing. ⌘↩ re-runs it."
|
||||||
|
case .dirty: return "Edited since the last run — ⌘↩ to re-evaluate."
|
||||||
|
case .compiling: return "Compiling…"
|
||||||
|
case .queued(let beat):
|
||||||
|
return String(format: "Compiled — swap lands on beat %.0f.", beat)
|
||||||
|
case .failed(let count):
|
||||||
|
let plural: String = count == 1 ? "" : "s"
|
||||||
|
return count == 0
|
||||||
|
? "Last run failed to compile."
|
||||||
|
: "Last run failed — \(count) diagnostic\(plural)."
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Layout constants — all in points. Kept private; tuned to match
|
// Layout constants — all in points. Kept private; tuned to match
|
||||||
@@ -219,26 +480,39 @@ public struct LyrebirdScratchView: View {
|
|||||||
private let diagnosticsMinHeight: CGFloat = 80
|
private let diagnosticsMinHeight: CGFloat = 80
|
||||||
private let diagnosticsMaxHeight: CGFloat = 200
|
private let diagnosticsMaxHeight: CGFloat = 200
|
||||||
private let engineDotSize: CGFloat = 8
|
private let engineDotSize: CGFloat = 8
|
||||||
|
private let reevalBadgeSpacing: CGFloat = 4
|
||||||
|
private let scopeHeight: CGFloat = 88
|
||||||
|
private let meterHeight: CGFloat = 6
|
||||||
|
private let consoleWidth: CGFloat = 300
|
||||||
|
private let consoleBottomID: String = "scratch.console.bottom"
|
||||||
|
private let cpuLabelWidth: CGFloat = 58
|
||||||
|
private let cpuValueWidth: CGFloat = 40
|
||||||
|
/// CPU-meter fill turns orange above this fraction of one block period, red
|
||||||
|
/// above ``cpuMeterCriticalThreshold``.
|
||||||
|
private let cpuMeterWarningThreshold: Double = 0.5
|
||||||
|
private let cpuMeterCriticalThreshold: Double = 0.8
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
|
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
|
||||||
/// message in a compact monospaced row.
|
/// message in a compact monospaced row.
|
||||||
private struct DiagnosticRow: View {
|
private struct ConsoleRow: View {
|
||||||
|
|
||||||
let diagnostic: Diagnostic
|
let entry: ScratchConsoleEntry
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
HStack(alignment: .firstTextBaseline, spacing: rowGutter) {
|
HStack(alignment: .firstTextBaseline, spacing: 6) {
|
||||||
Text(locationString)
|
Text(glyph)
|
||||||
.font(.system(.caption, design: .monospaced))
|
.font(.system(.caption2, design: .monospaced))
|
||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(color)
|
||||||
.frame(minWidth: locationColumnWidth, alignment: .leading)
|
.frame(width: 14, alignment: .leading)
|
||||||
Text(diagnostic.severity.rawValue)
|
if let location: String = entry.location {
|
||||||
.font(.system(.caption, design: .monospaced))
|
Text(location)
|
||||||
.foregroundStyle(color(for: diagnostic.severity))
|
.font(.system(.caption2, design: .monospaced))
|
||||||
.frame(minWidth: severityColumnWidth, alignment: .leading)
|
.foregroundStyle(.secondary)
|
||||||
Text(diagnostic.message)
|
}
|
||||||
|
Text(entry.text)
|
||||||
.font(.system(.caption, design: .monospaced))
|
.font(.system(.caption, design: .monospaced))
|
||||||
|
.foregroundStyle(entry.kind == .error ? Color.primary : color)
|
||||||
.textSelection(.enabled)
|
.textSelection(.enabled)
|
||||||
.multilineTextAlignment(.leading)
|
.multilineTextAlignment(.leading)
|
||||||
.fixedSize(horizontal: false, vertical: true)
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
@@ -246,27 +520,97 @@ private struct DiagnosticRow: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var locationString: String {
|
/// Leading glyph per kind: an X for errors, an arrow for messages, a dot for
|
||||||
if let line: Int = diagnostic.line {
|
/// info notices.
|
||||||
return "\(line):\(diagnostic.column)"
|
private var glyph: String {
|
||||||
|
switch entry.kind {
|
||||||
|
case .error: return "✗"
|
||||||
|
case .message: return "›"
|
||||||
|
case .info: return "·"
|
||||||
}
|
}
|
||||||
return "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private func color(for severity: DiagnosticSeverity) -> Color {
|
private var color: Color {
|
||||||
switch severity {
|
switch entry.kind {
|
||||||
case .error: return .red
|
case .error: return .red
|
||||||
case .warning: return .orange
|
case .message: return .cyan
|
||||||
case .note: return .secondary
|
case .info: return .secondary
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private let rowGutter: CGFloat = 8
|
|
||||||
private let locationColumnWidth: CGFloat = 80
|
|
||||||
private let severityColumnWidth: CGFloat = 56
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `NSViewRepresentable` wrapping a vanilla `NSTextView` inside an
|
/// `NSTextView` subclass that fixes member-completion behavior.
|
||||||
|
///
|
||||||
|
/// The default `rangeForUserCompletion` scans back over the whole dotted
|
||||||
|
/// expression, so a candidate would *replace* the receiver rather than the
|
||||||
|
/// partial word being typed. Completing a member after `context.` → `engine`
|
||||||
|
/// would replace `context`; accepting an argument label after `OscSin.Audio(`
|
||||||
|
/// → `freq:` would replace `OscSin.Audio`. The correct replace range is just
|
||||||
|
/// the run of identifier characters immediately before the caret (empty after
|
||||||
|
/// any boundary — `.`, `(`, `,`, whitespace), so the candidate inserts there.
|
||||||
|
|
||||||
|
/// Whether `c` (a UTF-16 code unit) is a Swift identifier character —
|
||||||
|
/// ASCII letter, digit, or underscore. Sufficient for completion-range
|
||||||
|
/// scanning; identifiers with non-ASCII scalars are not a concern here.
|
||||||
|
private func isIdentifierCodeUnit(_ c: unichar) -> Bool {
|
||||||
|
let underscore: unichar = 95
|
||||||
|
let zero: unichar = 48, nine: unichar = 57
|
||||||
|
let upperA: unichar = 65, upperZ: unichar = 90
|
||||||
|
let lowerA: unichar = 97, lowerZ: unichar = 122
|
||||||
|
return c == underscore
|
||||||
|
|| (c >= zero && c <= nine)
|
||||||
|
|| (c >= upperA && c <= upperZ)
|
||||||
|
|| (c >= lowerA && c <= lowerZ)
|
||||||
|
}
|
||||||
|
|
||||||
|
final class ScratchTextView: NSTextView {
|
||||||
|
/// Invoked when the user asks for completion (the standard completion key —
|
||||||
|
/// Esc / F5). Set by `makeNSView`, right after `configure`; runs the async fetch and then
|
||||||
|
/// shows the completion window. Completion is manual only.
|
||||||
|
var onManualComplete: (() -> Void)?
|
||||||
|
|
||||||
|
override var rangeForUserCompletion: NSRange {
|
||||||
|
let sel: NSRange = selectedRange()
|
||||||
|
// Never replace across an actual selection — defer to the default.
|
||||||
|
guard sel.length == 0, sel.location <= (string as NSString).length else {
|
||||||
|
return super.rangeForUserCompletion
|
||||||
|
}
|
||||||
|
let ns: NSString = string as NSString
|
||||||
|
var start: Int = sel.location
|
||||||
|
while start > 0 && isIdentifierCodeUnit(ns.character(at: start - 1)) {
|
||||||
|
start -= 1
|
||||||
|
}
|
||||||
|
return NSRange(location: start, length: sel.location - start)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Intercept the built-in `complete:` command (bound to Esc / F5) so the
|
||||||
|
/// candidates are fetched asynchronously first, then shown. Without this,
|
||||||
|
/// pressing Esc would call the delegate with an empty (never-fetched) list.
|
||||||
|
/// Everything else falls through to the normal editor commands.
|
||||||
|
override func doCommand(by selector: Selector) {
|
||||||
|
if selector == #selector(NSStandardKeyBindingResponding.complete(_:)) {
|
||||||
|
onManualComplete?()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
super.doCommand(by: selector)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Esc is delivered as `cancelOperation:` (not `complete:`) by the default
|
||||||
|
/// key bindings, so it never reaches `doCommand(by:)`'s `complete:` arm —
|
||||||
|
/// only F5 does. Route it here too so Esc invokes completion as documented.
|
||||||
|
/// The completion window, once open, consumes Esc itself to dismiss, so this
|
||||||
|
/// only fires when the window is closed.
|
||||||
|
override func cancelOperation(_ sender: Any?) {
|
||||||
|
onManualComplete?()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Width of the line-number gutter drawn by ``ScratchLineNumberGutter``.
|
||||||
|
/// `ScratchEditor.configure` reserves this as the text view's left inset so
|
||||||
|
/// the gutter overlay doesn't cover the text.
|
||||||
|
static let lineNumberGutterWidth: CGFloat = 40
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `NSViewRepresentable` wrapping a ``ScratchTextView`` inside an
|
||||||
/// `NSScrollView`. Monospaced 13 pt, plain text, no smart-quote / dash /
|
/// `NSScrollView`. Monospaced 13 pt, plain text, no smart-quote / dash /
|
||||||
/// auto-correct interference — matches the editor expectations of someone
|
/// auto-correct interference — matches the editor expectations of someone
|
||||||
/// typing Swift code.
|
/// typing Swift code.
|
||||||
@@ -275,24 +619,157 @@ private struct ScratchEditor: NSViewRepresentable {
|
|||||||
@Binding var text: String
|
@Binding var text: String
|
||||||
let fontSize: CGFloat
|
let fontSize: CGFloat
|
||||||
let wrapsLines: Bool
|
let wrapsLines: Bool
|
||||||
|
/// Async source of code-completion candidates for a zero-based user-space
|
||||||
|
/// (line, UTF-16 character). Supplied by the view from the model.
|
||||||
|
let requestCompletions: @MainActor (_ line: Int, _ character: Int) async -> [LSPCompletionItem]
|
||||||
|
/// Called with the current selected substring whenever the selection
|
||||||
|
/// changes (empty when nothing is selected). Drives "Run Selection".
|
||||||
|
let onSelectionChanged: @MainActor (String) -> Void
|
||||||
|
|
||||||
|
@MainActor
|
||||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||||
var parent: ScratchEditor
|
var parent: ScratchEditor
|
||||||
|
/// Candidate insert-texts from the most recent completion fetch; served
|
||||||
|
/// synchronously to the text view's completion window via the delegate.
|
||||||
|
private var _completionStrings: [String] = []
|
||||||
|
/// Monotonic id of the latest completion request; a resolving fetch only
|
||||||
|
/// applies its results if it is still the newest (so a slow older request
|
||||||
|
/// can't clobber a fresher one that landed first).
|
||||||
|
private var _completionGeneration: Int = 0
|
||||||
|
/// Pending debounced re-highlight; cancelled and rescheduled on each edit
|
||||||
|
/// so a burst of keystrokes re-tokenizes the buffer once, not per key.
|
||||||
|
private var _highlightWork: DispatchWorkItem?
|
||||||
|
/// Last selection substring pushed to the model, so an unchanged selection
|
||||||
|
/// (the common case while typing — caret moves, selection stays empty)
|
||||||
|
/// doesn't republish `@Published` state and re-render the whole view.
|
||||||
|
private var _lastSelectionPushed: String = ""
|
||||||
|
/// Last `wrapsLines` value applied, so `updateNSView` can skip re-applying
|
||||||
|
/// wrap/paragraph settings on a pure text republish (every keystroke).
|
||||||
|
var lastWraps: Bool?
|
||||||
|
|
||||||
|
/// Idle delay before re-highlighting after an edit. Short enough to feel
|
||||||
|
/// instant once typing pauses; long enough to coalesce a fast burst.
|
||||||
|
private static let highlightDebounce: TimeInterval = 0.045
|
||||||
|
|
||||||
init(_ parent: ScratchEditor) { self.parent = parent }
|
init(_ parent: ScratchEditor) { self.parent = parent }
|
||||||
|
|
||||||
func textDidChange(_ notification: Notification) {
|
func textDidChange(_ notification: Notification) {
|
||||||
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
||||||
parent.text = tv.string
|
parent.text = tv.string
|
||||||
|
scheduleHighlight(tv)
|
||||||
|
// Completion is manual (Esc), never auto-triggered on `.`: an
|
||||||
|
// unrequested popup ambushes typing and the built-in completion
|
||||||
|
// window is awkward to dismiss mid-edit.
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Coalesce full-buffer re-highlighting: cancel any pending pass and run
|
||||||
|
/// one shortly after the edits stop. Newly typed characters render in the
|
||||||
|
/// base color immediately (via `typingAttributes`); syntax colors catch
|
||||||
|
/// up a beat later, avoiding an O(n) tokenize on every keystroke.
|
||||||
|
private func scheduleHighlight(_ tv: NSTextView) {
|
||||||
|
_highlightWork?.cancel()
|
||||||
|
let work: DispatchWorkItem = DispatchWorkItem { [weak self, weak tv] in
|
||||||
|
guard let self: Coordinator = self, let tv: NSTextView = tv else { return }
|
||||||
|
self.parent.applyHighlight(to: tv)
|
||||||
|
}
|
||||||
|
_highlightWork = work
|
||||||
|
DispatchQueue.main.asyncAfter(deadline: .now() + Coordinator.highlightDebounce, execute: work)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Push the current selected substring up to the model so "Run Selection"
|
||||||
|
/// knows what (if anything) is selected — but only when it actually
|
||||||
|
/// changed, to avoid a per-caret-move `@Published` republish.
|
||||||
|
func textViewDidChangeSelection(_ notification: Notification) {
|
||||||
|
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
||||||
|
let sel: NSRange = tv.selectedRange()
|
||||||
|
let selected: String
|
||||||
|
if sel.length > 0, sel.location + sel.length <= (tv.string as NSString).length {
|
||||||
|
selected = (tv.string as NSString).substring(with: sel)
|
||||||
|
} else {
|
||||||
|
selected = ""
|
||||||
|
}
|
||||||
|
guard selected != _lastSelectionPushed else { return }
|
||||||
|
_lastSelectionPushed = selected
|
||||||
|
// Defer the @Published mutation: a programmatic text change (via
|
||||||
|
// `updateNSView` → `replaceText`) can clamp the selection and re-post
|
||||||
|
// this notification from inside a SwiftUI update pass. Scheduling on
|
||||||
|
// the next main-actor tick keeps that off the render pass ("Publishing
|
||||||
|
// changes from within view updates is not allowed").
|
||||||
|
let notify: @MainActor (String) -> Void = parent.onSelectionChanged
|
||||||
|
Task { @MainActor in notify(selected) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The text view calls this synchronously from `complete(_:)`; return the
|
||||||
|
/// candidates fetched asynchronously just before. Replaces the default
|
||||||
|
/// dictionary-word completions entirely.
|
||||||
|
func textView(_ textView: NSTextView,
|
||||||
|
completions words: [String],
|
||||||
|
forPartialWordRange charRange: NSRange,
|
||||||
|
indexOfSelectedItem index: UnsafeMutablePointer<Int>?) -> [String] {
|
||||||
|
_completionStrings
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch completions for the current caret position, then show the text
|
||||||
|
/// view's completion window. No-op when the selection is non-empty (a
|
||||||
|
/// range is selected, not an insertion point) or the fetch is empty.
|
||||||
|
func triggerCompletion(_ tv: NSTextView) {
|
||||||
|
let sel: NSRange = tv.selectedRange()
|
||||||
|
guard sel.length == 0 else { return }
|
||||||
|
let (line, character): (Int, Int) = editorLineAndUTF16Char(
|
||||||
|
in: tv.string, utf16Offset: sel.location)
|
||||||
|
let request: @MainActor (Int, Int) async -> [LSPCompletionItem] = parent.requestCompletions
|
||||||
|
_completionGeneration += 1
|
||||||
|
let generation: Int = _completionGeneration
|
||||||
|
Task { @MainActor [weak self, weak tv] in
|
||||||
|
let items: [LSPCompletionItem] = await request(line, character)
|
||||||
|
guard let self: Coordinator = self, let tv: NSTextView = tv,
|
||||||
|
!items.isEmpty else { return }
|
||||||
|
// Ignore a superseded request (a newer trigger fired meanwhile)
|
||||||
|
// and one whose caret has since moved.
|
||||||
|
guard generation == self._completionGeneration,
|
||||||
|
tv.selectedRange() == sel else { return }
|
||||||
|
self._completionStrings = items.map { $0.insertText }
|
||||||
|
tv.complete(nil)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||||
|
|
||||||
func makeNSView(context: Context) -> NSScrollView {
|
func makeNSView(context: Context) -> NSScrollView {
|
||||||
let scroll: NSScrollView = NSTextView.scrollableTextView()
|
// Build the scroll view around a `ScratchTextView` subclass so its
|
||||||
if let tv: NSTextView = scroll.documentView as? NSTextView {
|
// `rangeForUserCompletion` override can keep member completion from
|
||||||
configure(tv, in: scroll, with: context.coordinator)
|
// eating the receiver expression (see the class doc).
|
||||||
|
let scroll: NSScrollView = NSScrollView()
|
||||||
|
scroll.borderType = .noBorder
|
||||||
|
scroll.hasVerticalScroller = true
|
||||||
|
scroll.autoresizingMask = [.width, .height]
|
||||||
|
|
||||||
|
let tv: ScratchTextView = ScratchTextView(frame: .zero)
|
||||||
|
// Opt into TextKit 1: accessing `layoutManager` permanently switches the
|
||||||
|
// text view off TextKit 2, where `self.layoutManager` is nil — the gutter
|
||||||
|
// drawing needs it to place numbers against laid-out line rects.
|
||||||
|
_ = tv.layoutManager
|
||||||
|
tv.autoresizingMask = [.width]
|
||||||
|
tv.isVerticallyResizable = true
|
||||||
|
tv.isHorizontallyResizable = false
|
||||||
|
tv.minSize = NSSize(width: 0, height: 0)
|
||||||
|
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
||||||
|
height: CGFloat.greatestFiniteMagnitude)
|
||||||
|
tv.textContainer?.widthTracksTextView = true
|
||||||
|
scroll.documentView = tv
|
||||||
|
|
||||||
|
configure(tv, in: scroll, with: context.coordinator)
|
||||||
|
// Manual completion (Esc): fetch candidates, then show the window.
|
||||||
|
let coordinator: Coordinator = context.coordinator
|
||||||
|
tv.onManualComplete = { [weak coordinator, weak tv] in
|
||||||
|
guard let coordinator: Coordinator = coordinator, let tv: ScratchTextView = tv else { return }
|
||||||
|
coordinator.triggerCompletion(tv)
|
||||||
}
|
}
|
||||||
|
// Line-number gutter: a floating overlay pinned to the left of the visible
|
||||||
|
// area (see `ScratchLineNumberGutter` for why not an `NSRulerView`).
|
||||||
|
let gutter: ScratchLineNumberGutter = ScratchLineNumberGutter(scrollView: scroll, textView: tv)
|
||||||
|
scroll.addFloatingSubview(gutter, for: .vertical)
|
||||||
return scroll
|
return scroll
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -301,17 +778,26 @@ private struct ScratchEditor: NSViewRepresentable {
|
|||||||
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
|
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
|
||||||
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||||
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
|
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
|
||||||
if fontChanged {
|
let wrapChanged: Bool = context.coordinator.lastWraps != wrapsLines
|
||||||
tv.font = font
|
context.coordinator.lastWraps = wrapsLines
|
||||||
}
|
let textChanged: Bool = tv.string != text
|
||||||
|
|
||||||
|
// Fast path: a pure text republish (the per-keystroke case) needs no work
|
||||||
|
// here — the `NSTextView` already holds the text (it's the editor of
|
||||||
|
// record), highlighting is debounced in the Coordinator, and font/wrap
|
||||||
|
// are unchanged. Skip the paragraph-style measure + attribute churn.
|
||||||
|
guard textChanged || fontChanged || wrapChanged else { return }
|
||||||
|
|
||||||
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
|
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
|
||||||
|
if fontChanged { tv.font = font }
|
||||||
tv.defaultParagraphStyle = paragraphStyle
|
tv.defaultParagraphStyle = paragraphStyle
|
||||||
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
|
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
|
||||||
applyWrap(to: tv, in: scroll)
|
applyWrap(to: tv, in: scroll)
|
||||||
if tv.string != text {
|
if textChanged {
|
||||||
|
// External change (load, reset, mode switch) — replace + re-highlight.
|
||||||
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
|
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
|
||||||
} else if fontChanged {
|
} else if fontChanged {
|
||||||
reapplyAttrs(to: tv, font: font, paragraph: paragraphStyle)
|
applyHighlight(to: tv, font: font, paragraph: paragraphStyle)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -340,16 +826,37 @@ private struct ScratchEditor: NSViewRepresentable {
|
|||||||
let attributed: NSAttributedString = NSAttributedString(string: newText, attributes: attrs)
|
let attributed: NSAttributedString = NSAttributedString(string: newText, attributes: attrs)
|
||||||
tv.textStorage?.setAttributedString(attributed)
|
tv.textStorage?.setAttributedString(attributed)
|
||||||
tv.typingAttributes = attrs
|
tv.typingAttributes = attrs
|
||||||
|
applyHighlight(to: tv, font: font, paragraph: paragraph)
|
||||||
|
// A direct `setAttributedString` bypasses `NSTextView`'s edit path, so the
|
||||||
|
// gutter (which redraws on `NSText.didChangeNotification`) isn't told to
|
||||||
|
// refresh. Nudge it explicitly after a programmatic replace (format /
|
||||||
|
// load / reset) so the line count doesn't go stale.
|
||||||
|
if let scroll: NSScrollView = tv.enclosingScrollView {
|
||||||
|
for sub: NSView in scroll.subviews {
|
||||||
|
(sub as? ScratchLineNumberGutter)?.refresh()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func reapplyAttrs(to tv: NSTextView,
|
// MARK: - Syntax highlighting
|
||||||
font: NSFont,
|
|
||||||
paragraph: NSParagraphStyle) {
|
/// Re-tokenize the buffer and paint token colors via
|
||||||
|
/// ``ScratchSyntaxHighlighter``. Attribute-only — the string and the
|
||||||
|
/// selection are untouched.
|
||||||
|
private func applyHighlight(to tv: NSTextView,
|
||||||
|
font: NSFont,
|
||||||
|
paragraph: NSParagraphStyle) {
|
||||||
guard let storage: NSTextStorage = tv.textStorage else { return }
|
guard let storage: NSTextStorage = tv.textStorage else { return }
|
||||||
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
|
let base: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
|
||||||
let range: NSRange = NSRange(location: 0, length: storage.length)
|
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
|
||||||
storage.setAttributes(attrs, range: range)
|
tv.typingAttributes = base
|
||||||
tv.typingAttributes = attrs
|
}
|
||||||
|
|
||||||
|
/// Convenience for the delegate path, which has only the text view: rebuilds
|
||||||
|
/// the font/paragraph from the current `fontSize`.
|
||||||
|
func applyHighlight(to tv: NSTextView) {
|
||||||
|
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||||
|
applyHighlight(to: tv, font: font, paragraph: makeParagraphStyle(for: font))
|
||||||
}
|
}
|
||||||
|
|
||||||
private func applyWrap(to tv: NSTextView, in scroll: NSScrollView) {
|
private func applyWrap(to tv: NSTextView, in scroll: NSScrollView) {
|
||||||
@@ -378,7 +885,15 @@ private struct ScratchEditor: NSViewRepresentable {
|
|||||||
tv.delegate = coordinator
|
tv.delegate = coordinator
|
||||||
let editorFont: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
let editorFont: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||||
tv.font = editorFont
|
tv.font = editorFont
|
||||||
tv.isRichText = false
|
// Rich text so per-token foreground colors render. User styling can't
|
||||||
|
// creep in: every edit re-runs `applyHighlight`, which normalizes the
|
||||||
|
// font/paragraph over the whole buffer before recoloring, and the smart
|
||||||
|
// substitutions below stay disabled.
|
||||||
|
tv.isRichText = true
|
||||||
|
// Rich text would otherwise allow dragged/pasted images to inject
|
||||||
|
// NSTextAttachment glyphs into the buffer; keep it plain-text-only so the
|
||||||
|
// content is always compilable Swift source.
|
||||||
|
tv.importsGraphics = false
|
||||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||||
tv.isAutomaticDashSubstitutionEnabled = false
|
tv.isAutomaticDashSubstitutionEnabled = false
|
||||||
tv.isAutomaticTextReplacementEnabled = false
|
tv.isAutomaticTextReplacementEnabled = false
|
||||||
@@ -386,7 +901,11 @@ private struct ScratchEditor: NSViewRepresentable {
|
|||||||
tv.smartInsertDeleteEnabled = false
|
tv.smartInsertDeleteEnabled = false
|
||||||
tv.allowsUndo = true
|
tv.allowsUndo = true
|
||||||
tv.usesFindBar = true
|
tv.usesFindBar = true
|
||||||
tv.textContainerInset = NSSize(width: editorInset, height: editorInset)
|
// Left inset reserves the column the `ScratchLineNumberGutter` overlay
|
||||||
|
// draws line numbers into (see `ScratchLineNumberGutter.draw(_:)`).
|
||||||
|
// `textContainerInset` is symmetric, so the right margin matches —
|
||||||
|
// harmless whitespace.
|
||||||
|
tv.textContainerInset = NSSize(width: ScratchTextView.lineNumberGutterWidth, height: editorInset)
|
||||||
tv.drawsBackground = true
|
tv.drawsBackground = true
|
||||||
tv.backgroundColor = .textBackgroundColor
|
tv.backgroundColor = .textBackgroundColor
|
||||||
tv.textColor = .labelColor
|
tv.textColor = .labelColor
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
// ReevalState.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdUI/LiveCompile
|
||||||
|
//
|
||||||
|
// `ReevalState` is the structured re-evaluation readiness signal published by
|
||||||
|
// `LyrebirdScratchModel`. It answers "can I re-evaluate, and would it change
|
||||||
|
// anything?" for the editor UI — distinct from the free-text `statusMessage`.
|
||||||
|
// A snippet's buffer becomes `.dirty` when edited away from the last
|
||||||
|
// successfully-run text, flips to `.compiling` while a run is in flight, and
|
||||||
|
// settles to `.clean` (buffer matches what is playing) or `.failed` afterward.
|
||||||
|
//
|
||||||
|
// macOS only — the whole LiveCompile UI surface is macOS-only.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
|
||||||
|
/// Re-evaluation readiness of a live-coding buffer.
|
||||||
|
///
|
||||||
|
/// Published by ``LyrebirdScratchModel/reevalState`` so the editor can show a
|
||||||
|
/// status badge and enable/disable the Run controls without inspecting the
|
||||||
|
/// free-text status line.
|
||||||
|
///
|
||||||
|
/// State machine:
|
||||||
|
///
|
||||||
|
/// - ``empty`` → editing non-blank text → ``dirty``
|
||||||
|
/// - ``dirty`` → run starts → ``compiling``
|
||||||
|
/// - ``compiling`` → success → ``clean`` (or ``dirty`` if the buffer was edited
|
||||||
|
/// mid-compile; or ``queued(untilBeat:)`` if the run scheduled a quantized
|
||||||
|
/// slot swap that has not yet fired) / failure → ``failed(diagnosticCount:)``
|
||||||
|
/// - ``queued(untilBeat:)`` → the scheduled swap fires → ``clean`` (or
|
||||||
|
/// ``dirty`` if the buffer was edited while queued)
|
||||||
|
/// - ``clean`` / ``queued(untilBeat:)`` / ``failed(diagnosticCount:)`` →
|
||||||
|
/// editing → ``dirty`` (or ``empty`` if the buffer is cleared to whitespace)
|
||||||
|
public enum ReevalState: Equatable, Sendable {
|
||||||
|
|
||||||
|
/// Buffer is empty or whitespace-only. Nothing to evaluate.
|
||||||
|
case empty
|
||||||
|
|
||||||
|
/// Buffer matches the text of the last successful run — re-evaluating would
|
||||||
|
/// re-run the same source. Re-evaluation is still permitted (e.g. additive).
|
||||||
|
case clean
|
||||||
|
|
||||||
|
/// Buffer has been edited since the last successful run (or has never been
|
||||||
|
/// run) and holds non-blank content. A re-evaluation is available and would
|
||||||
|
/// change what is playing.
|
||||||
|
case dirty
|
||||||
|
|
||||||
|
/// A compile + run is in flight. Run controls should be disabled.
|
||||||
|
case compiling
|
||||||
|
|
||||||
|
/// The run compiled and its slot swap is scheduled but has not yet fired —
|
||||||
|
/// the change becomes audible on `untilBeat` (a `LyrebirdClock` beat). Only
|
||||||
|
/// reached when swaps are quantized (see `SwapQuantize`); the state settles
|
||||||
|
/// to ``clean`` once the clock passes the boundary.
|
||||||
|
case queued(untilBeat: Double)
|
||||||
|
|
||||||
|
/// The last run failed to compile. `diagnosticCount` is the number of
|
||||||
|
/// parsed diagnostics (0 when the failure produced no line-mapped
|
||||||
|
/// diagnostics, e.g. a toolchain error).
|
||||||
|
case failed(diagnosticCount: Int)
|
||||||
|
|
||||||
|
/// `true` when a re-evaluation can be triggered right now — i.e. the buffer
|
||||||
|
/// holds runnable content and no compile is already in flight. A pending
|
||||||
|
/// quantized swap (``queued``) does not block a further edit + re-run.
|
||||||
|
public var canEvaluate: Bool {
|
||||||
|
switch self {
|
||||||
|
case .empty, .compiling:
|
||||||
|
return false
|
||||||
|
case .clean, .dirty, .queued, .failed:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
// RenderOptionsAccessory.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import AppKit
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
|
/// Accessory view embedded in the "Render to File" `NSSavePanel`: a container/encoding
|
||||||
|
/// popup and a duration field. Selecting a format rewrites the panel's filename
|
||||||
|
/// extension and remembers the choice (`UserDefaults`) so the next render defaults to it.
|
||||||
|
///
|
||||||
|
/// The sample rate and channel count are intentionally **not** exposed here — the
|
||||||
|
/// offline render mirrors the live engine (WYSIWYG with what was just heard).
|
||||||
|
@MainActor
|
||||||
|
final class RenderOptionsAccessory: NSView {
|
||||||
|
|
||||||
|
// MARK: - Format catalogue
|
||||||
|
|
||||||
|
/// One selectable output format. `token` is the persistence key (stable across
|
||||||
|
/// reordering / re-titling of the list, unlike a raw index or the display title).
|
||||||
|
private struct Option {
|
||||||
|
let title: String
|
||||||
|
let format: AudioFileFormat
|
||||||
|
let token: String
|
||||||
|
}
|
||||||
|
|
||||||
|
private static let options: [Option] = [
|
||||||
|
Option(title: "WAV — 32-bit float", format: .wavFloat32, token: "wavF32"),
|
||||||
|
Option(title: "WAV — 16-bit integer", format: .wavInt16, token: "wavI16"),
|
||||||
|
Option(title: "WAV — 24-bit integer", format: .wavInt24, token: "wavI24"),
|
||||||
|
Option(title: "AIFF — 32-bit float", format: .aiffFloat32, token: "aiffF32"),
|
||||||
|
Option(title: "CAF — 32-bit float (uncapped)", format: .cafFloat32, token: "cafF32"),
|
||||||
|
Option(title: "RF64 WAV — 32-bit float (>4 GB)", format: .rf64Float32, token: "rf64F32"),
|
||||||
|
Option(title: "RF64 WAV — 24-bit integer (>4 GB)", format: .rf64Int24, token: "rf64I24"),
|
||||||
|
Option(title: "AAC — 256 kbps (M4A)", format: .aacHigh, token: "aacHigh"),
|
||||||
|
Option(title: "AAC — 128 kbps (M4A)", format: .aacMedium, token: "aacMedium"),
|
||||||
|
Option(title: "Apple Lossless (M4A)", format: .alac, token: "alac"),
|
||||||
|
]
|
||||||
|
|
||||||
|
/// Persisted last-used format token. Defaults to CAF (the pre-accessory behaviour).
|
||||||
|
private static let defaultsKey: String = "com.lyrebird.scratch.renderFormatToken"
|
||||||
|
private static let fallbackToken: String = "cafF32"
|
||||||
|
|
||||||
|
// MARK: - Layout metrics
|
||||||
|
|
||||||
|
private static let accessoryWidth: CGFloat = 380
|
||||||
|
private static let accessoryHeight: CGFloat = 96
|
||||||
|
private static let contentMargin: CGFloat = 16
|
||||||
|
private static let gridSpacing: CGFloat = 8
|
||||||
|
private static let minDurationFieldWidth: CGFloat = 80
|
||||||
|
|
||||||
|
// MARK: - Subviews
|
||||||
|
|
||||||
|
private let formatPopup: NSPopUpButton = NSPopUpButton(frame: .zero, pullsDown: false)
|
||||||
|
private let durationField: NSTextField = NSTextField(frame: .zero)
|
||||||
|
|
||||||
|
private let baseName: String
|
||||||
|
private weak var savePanel: NSSavePanel?
|
||||||
|
|
||||||
|
// MARK: - Public read-out
|
||||||
|
|
||||||
|
/// The format for the currently selected popup item.
|
||||||
|
var selectedFormat: AudioFileFormat {
|
||||||
|
let index: Int = formatPopup.indexOfSelectedItem
|
||||||
|
guard index >= 0 && index < RenderOptionsAccessory.options.count else {
|
||||||
|
return .cafFloat32
|
||||||
|
}
|
||||||
|
return RenderOptionsAccessory.options[index].format
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parsed duration in seconds, or `nil` when the field is not a positive number.
|
||||||
|
var durationSeconds: Double? { RenderOptionsAccessory.parseDuration(durationField.stringValue) }
|
||||||
|
|
||||||
|
/// Parse a duration string to a positive, finite seconds value (or `nil`). Pure —
|
||||||
|
/// extracted so it can be unit-tested without the modal panel.
|
||||||
|
static func parseDuration(_ raw: String) -> Double? {
|
||||||
|
let trimmed: String = raw.trimmingCharacters(in: .whitespaces)
|
||||||
|
guard let value: Double = Double(trimmed), value > 0, value.isFinite else { return nil }
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// - Parameters:
|
||||||
|
/// - baseName: Filename stem (no extension); the format's extension is appended.
|
||||||
|
/// - initialDuration: Seconds pre-filled in the duration field.
|
||||||
|
/// - savePanel: The panel to keep the filename extension in sync with.
|
||||||
|
init(baseName: String, initialDuration: Double, savePanel: NSSavePanel) {
|
||||||
|
self.baseName = baseName
|
||||||
|
self.savePanel = savePanel
|
||||||
|
super.init(frame: NSRect(x: 0, y: 0,
|
||||||
|
width: RenderOptionsAccessory.accessoryWidth,
|
||||||
|
height: RenderOptionsAccessory.accessoryHeight))
|
||||||
|
|
||||||
|
let startIndex: Int = RenderOptionsAccessory.persistedIndex()
|
||||||
|
|
||||||
|
formatPopup.addItems(withTitles: RenderOptionsAccessory.options.map(\.title))
|
||||||
|
formatPopup.selectItem(at: startIndex)
|
||||||
|
formatPopup.target = self
|
||||||
|
formatPopup.action = #selector(formatChanged)
|
||||||
|
formatPopup.translatesAutoresizingMaskIntoConstraints = false
|
||||||
|
|
||||||
|
durationField.stringValue = String(format: "%.2f", initialDuration)
|
||||||
|
durationField.translatesAutoresizingMaskIntoConstraints = false
|
||||||
|
|
||||||
|
let formatLabel: NSTextField = RenderOptionsAccessory.makeLabel("Format:")
|
||||||
|
let durationLabel: NSTextField = RenderOptionsAccessory.makeLabel("Duration (s):")
|
||||||
|
|
||||||
|
let grid: NSGridView = NSGridView(views: [
|
||||||
|
[formatLabel, formatPopup],
|
||||||
|
[durationLabel, durationField],
|
||||||
|
])
|
||||||
|
grid.translatesAutoresizingMaskIntoConstraints = false
|
||||||
|
grid.rowSpacing = RenderOptionsAccessory.gridSpacing
|
||||||
|
grid.columnSpacing = RenderOptionsAccessory.gridSpacing
|
||||||
|
grid.column(at: 0).xPlacement = .trailing
|
||||||
|
addSubview(grid)
|
||||||
|
|
||||||
|
let margin: CGFloat = RenderOptionsAccessory.contentMargin
|
||||||
|
NSLayoutConstraint.activate([
|
||||||
|
grid.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin),
|
||||||
|
grid.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -margin),
|
||||||
|
grid.topAnchor.constraint(equalTo: topAnchor, constant: margin),
|
||||||
|
grid.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -margin),
|
||||||
|
durationField.widthAnchor.constraint(
|
||||||
|
greaterThanOrEqualToConstant: RenderOptionsAccessory.minDurationFieldWidth),
|
||||||
|
])
|
||||||
|
|
||||||
|
// Seed the panel filename once from baseName + the initial format's extension.
|
||||||
|
savePanel.nameFieldStringValue = baseName + "." + selectedFormat.fileExtension
|
||||||
|
}
|
||||||
|
|
||||||
|
@available(*, unavailable)
|
||||||
|
required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
|
||||||
|
|
||||||
|
// MARK: - Actions
|
||||||
|
|
||||||
|
@objc private func formatChanged() {
|
||||||
|
syncPanelExtension()
|
||||||
|
let index: Int = formatPopup.indexOfSelectedItem
|
||||||
|
if index >= 0 && index < RenderOptionsAccessory.options.count {
|
||||||
|
UserDefaults.standard.set(RenderOptionsAccessory.options[index].token,
|
||||||
|
forKey: RenderOptionsAccessory.defaultsKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-extension the panel's current filename to match the selected format,
|
||||||
|
/// **preserving any stem the user typed** — only the extension is replaced.
|
||||||
|
private func syncPanelExtension() {
|
||||||
|
guard let panel: NSSavePanel = savePanel else { return }
|
||||||
|
let currentStem: String = (panel.nameFieldStringValue as NSString).deletingPathExtension
|
||||||
|
let stem: String = currentStem.isEmpty ? baseName : currentStem
|
||||||
|
panel.nameFieldStringValue = stem + "." + selectedFormat.fileExtension
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Test seam: select a format by index as if the user picked it from the popup
|
||||||
|
/// (fires the same `formatChanged` side effects — panel re-extension + persistence).
|
||||||
|
func selectFormatForTesting(at index: Int) {
|
||||||
|
formatPopup.selectItem(at: index)
|
||||||
|
formatChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Test seam: clear the persisted last-format so a test can start from the
|
||||||
|
/// default and not leak state into other tests or the real app.
|
||||||
|
static func clearPersistedFormatForTesting() {
|
||||||
|
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Helpers
|
||||||
|
|
||||||
|
private static func persistedIndex() -> Int {
|
||||||
|
let token: String = UserDefaults.standard.string(forKey: defaultsKey) ?? fallbackToken
|
||||||
|
if let index: Int = options.firstIndex(where: { $0.token == token }) { return index }
|
||||||
|
return options.firstIndex(where: { $0.token == fallbackToken }) ?? 0
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func makeLabel(_ text: String) -> NSTextField {
|
||||||
|
let label: NSTextField = NSTextField(labelWithString: text)
|
||||||
|
label.translatesAutoresizingMaskIntoConstraints = false
|
||||||
|
return label
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// ScratchConsoleEntry.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdUI/LiveCompile
|
||||||
|
//
|
||||||
|
// One line in the scratch editor's console panel — a report message, an error,
|
||||||
|
// or a run notice.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
|
||||||
|
/// A single entry in the always-open console.
|
||||||
|
public struct ScratchConsoleEntry: Identifiable, Equatable {
|
||||||
|
|
||||||
|
/// What kind of line this is, for coloring.
|
||||||
|
public enum Kind: Equatable {
|
||||||
|
/// `context.reportMessage(_:)` output (and host notices).
|
||||||
|
case message
|
||||||
|
/// A compile / DSL error.
|
||||||
|
case error
|
||||||
|
/// A run outcome / informational notice.
|
||||||
|
case info
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Monotonic id (also the display order).
|
||||||
|
public let id: Int
|
||||||
|
public let kind: Kind
|
||||||
|
public let text: String
|
||||||
|
/// `"line:col"` for an error with a known source position, else `nil`.
|
||||||
|
public let location: String?
|
||||||
|
|
||||||
|
public init(id: Int, kind: Kind, text: String, location: String? = nil) {
|
||||||
|
self.id = id
|
||||||
|
self.kind = kind
|
||||||
|
self.text = text
|
||||||
|
self.location = location
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
// ScratchEvalMode.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdUI/LiveCompile
|
||||||
|
//
|
||||||
|
// Which evaluator the scratch editor runs the buffer through.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
|
||||||
|
/// The evaluation path for a `LyrebirdScratchModel`'s buffer.
|
||||||
|
public enum ScratchEvalMode: String, CaseIterable, Sendable {
|
||||||
|
/// Full Swift snippet compiled with swiftc into a dylib and run — the whole
|
||||||
|
/// language, `SynthesizerBase` subclasses, arbitrary code. Costs a compile.
|
||||||
|
case swift
|
||||||
|
/// Interpreted graph-DSL — instant, no swiftc, but only generator-graph
|
||||||
|
/// expressions (`OscSin.Audio(freq: 440) * 0.1`, `bass = …`).
|
||||||
|
case graphDSL
|
||||||
|
|
||||||
|
/// Human-readable label for a mode toggle.
|
||||||
|
public var title: String {
|
||||||
|
switch self {
|
||||||
|
case .swift: return "Swift"
|
||||||
|
case .graphDSL: return "Graph DSL"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
// ScratchLineNumberGutter.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// Line-number gutter for `ScratchEditor`'s text view, implemented as a plain
|
||||||
|
// floating overlay `NSView` rather than an `NSRulerView`. Enabling
|
||||||
|
// `NSScrollView.rulersVisible` in this SwiftUI `NSViewRepresentable` mis-tiles
|
||||||
|
// the document view (text goes invisible and stops taking input), and drawing
|
||||||
|
// inside a layer-backed `NSTextView` never reaches `draw(_:)`. A floating
|
||||||
|
// subview draws normally and leaves the text view untouched. It reads the text
|
||||||
|
// view's layout manager and the clip view's scroll offset to place one
|
||||||
|
// right-aligned number per source line in the visible region.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import AppKit
|
||||||
|
|
||||||
|
final class ScratchLineNumberGutter: NSView {
|
||||||
|
|
||||||
|
private weak var textView: NSTextView?
|
||||||
|
private weak var scrollView: NSScrollView?
|
||||||
|
|
||||||
|
init(scrollView: NSScrollView, textView: NSTextView) {
|
||||||
|
self.scrollView = scrollView
|
||||||
|
self.textView = textView
|
||||||
|
let height: CGFloat = scrollView.contentView.bounds.height
|
||||||
|
super.init(frame: NSRect(x: 0, y: 0, width: ScratchTextView.lineNumberGutterWidth, height: height))
|
||||||
|
self.autoresizingMask = [.height]
|
||||||
|
|
||||||
|
let clip: NSClipView = scrollView.contentView
|
||||||
|
clip.postsBoundsChangedNotifications = true
|
||||||
|
let center: NotificationCenter = NotificationCenter.default
|
||||||
|
center.addObserver(self, selector: #selector(refresh),
|
||||||
|
name: NSView.boundsDidChangeNotification, object: clip)
|
||||||
|
center.addObserver(self, selector: #selector(refresh),
|
||||||
|
name: NSText.didChangeNotification, object: textView)
|
||||||
|
center.addObserver(self, selector: #selector(refresh),
|
||||||
|
name: NSView.frameDidChangeNotification, object: textView)
|
||||||
|
}
|
||||||
|
|
||||||
|
required init?(coder: NSCoder) {
|
||||||
|
fatalError("ScratchLineNumberGutter does not support NSCoder init")
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
NotificationCenter.default.removeObserver(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
override var isFlipped: Bool { true }
|
||||||
|
|
||||||
|
/// Redraw the whole gutter after an edit / scroll / relayout. A programmatic
|
||||||
|
/// text replace (format / load / reset) can happen without an
|
||||||
|
/// `NSText.didChangeNotification`, so the host also nudges this directly.
|
||||||
|
@objc func refresh() { needsDisplay = true }
|
||||||
|
|
||||||
|
override func draw(_ dirtyRect: NSRect) {
|
||||||
|
gutterFillColor.setFill()
|
||||||
|
bounds.fill()
|
||||||
|
gutterDividerColor.setStroke()
|
||||||
|
let divider: NSBezierPath = NSBezierPath()
|
||||||
|
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
||||||
|
divider.move(to: NSPoint(x: dividerX, y: bounds.minY))
|
||||||
|
divider.line(to: NSPoint(x: dividerX, y: bounds.maxY))
|
||||||
|
divider.lineWidth = 1
|
||||||
|
divider.stroke()
|
||||||
|
|
||||||
|
guard let textView: NSTextView = textView,
|
||||||
|
let layoutManager: NSLayoutManager = textView.layoutManager,
|
||||||
|
let container: NSTextContainer = textView.textContainer,
|
||||||
|
let clip: NSClipView = scrollView?.contentView else { return }
|
||||||
|
|
||||||
|
let visibleRect: NSRect = clip.documentVisibleRect
|
||||||
|
let inset: CGFloat = textView.textContainerInset.height
|
||||||
|
let ns: NSString = textView.string as NSString
|
||||||
|
let total: Int = ns.length
|
||||||
|
let attrs: [NSAttributedString.Key: Any] = [
|
||||||
|
.font: gutterFont,
|
||||||
|
.foregroundColor: gutterTextColor,
|
||||||
|
]
|
||||||
|
|
||||||
|
// Glyphs visible in the clip, then the source-line walk over that range.
|
||||||
|
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: container)
|
||||||
|
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
||||||
|
|
||||||
|
// Snap to the START of the first visible source line before counting: when
|
||||||
|
// word-wrap puts a wrapped continuation fragment at the top of the visible
|
||||||
|
// area, `charRange.location` lands mid-line, and `lineNumber(at:)` would
|
||||||
|
// over-count by one (throwing off every number below it).
|
||||||
|
let firstLineStart: Int = ns.lineRange(for: NSRange(location: min(charRange.location, total), length: 0)).location
|
||||||
|
var lineIndex: Int = lineNumber(at: firstLineStart, in: ns)
|
||||||
|
var cursor: Int = firstLineStart
|
||||||
|
let visibleEnd: Int = NSMaxRange(charRange)
|
||||||
|
while cursor < visibleEnd && cursor < total {
|
||||||
|
let lineRange: NSRange = ns.lineRange(for: NSRange(location: cursor, length: 0))
|
||||||
|
// Position from the line *fragment* rect (the row's box), not the glyph
|
||||||
|
// bounding rect. `boundingRect` is inconsistent across a trailing
|
||||||
|
// newline and blank lines — it's what left the last number cramped
|
||||||
|
// against the trailing empty line. The fragment rect is one clean,
|
||||||
|
// uniform-height box per row.
|
||||||
|
let firstGlyph: Int = layoutManager.glyphIndexForCharacter(at: lineRange.location)
|
||||||
|
let fragment: NSRect = layoutManager.lineFragmentRect(
|
||||||
|
forGlyphAt: firstGlyph,
|
||||||
|
effectiveRange: nil,
|
||||||
|
withoutAdditionalLayout: true
|
||||||
|
)
|
||||||
|
drawNumber(lineIndex, docY: fragment.minY + inset, lineHeight: fragment.height,
|
||||||
|
visibleMinY: visibleRect.minY, attrs: attrs)
|
||||||
|
let advance: Int = NSMaxRange(lineRange)
|
||||||
|
if advance <= cursor { break }
|
||||||
|
cursor = advance
|
||||||
|
lineIndex += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trailing empty line (empty doc, or one ending in a newline): drawn from
|
||||||
|
// the layout manager's extra fragment, which `boundingRect` on a
|
||||||
|
// zero-length range does not cover.
|
||||||
|
let endsWithNewline: Bool = total > 0 && CharacterSet.newlines.contains(
|
||||||
|
Unicode.Scalar(ns.character(at: total - 1)) ?? Unicode.Scalar(0)
|
||||||
|
)
|
||||||
|
if total == 0 || endsWithNewline {
|
||||||
|
let extra: NSRect = layoutManager.extraLineFragmentRect
|
||||||
|
if extra.height > 0 {
|
||||||
|
drawNumber(lineIndex, docY: extra.minY + inset, lineHeight: extra.height,
|
||||||
|
visibleMinY: visibleRect.minY, attrs: attrs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func drawNumber(_ n: Int, docY: CGFloat, lineHeight: CGFloat, visibleMinY: CGFloat,
|
||||||
|
attrs: [NSAttributedString.Key: Any]) {
|
||||||
|
// Document Y → gutter-local Y (the gutter floats over the visible area).
|
||||||
|
let y: CGFloat = docY - visibleMinY
|
||||||
|
let label: NSString = "\(n)" as NSString
|
||||||
|
let size: CGSize = label.size(withAttributes: attrs)
|
||||||
|
let point: NSPoint = NSPoint(
|
||||||
|
x: bounds.maxX - size.width - rightInset,
|
||||||
|
y: y + (lineHeight - size.height) * verticalCenterFraction
|
||||||
|
)
|
||||||
|
label.draw(at: point, withAttributes: attrs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 1-based source line number of the character at `loc`. Counts CR/LF/CRLF.
|
||||||
|
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
||||||
|
if loc <= 0 { return 1 }
|
||||||
|
var line: Int = 1
|
||||||
|
text.enumerateSubstrings(in: NSRange(location: 0, length: loc),
|
||||||
|
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
||||||
|
line += 1
|
||||||
|
}
|
||||||
|
return line
|
||||||
|
}
|
||||||
|
|
||||||
|
private let rightInset: CGFloat = 6
|
||||||
|
private let dividerHalfPixel: CGFloat = 0.5
|
||||||
|
private let gutterFontSize: CGFloat = 11
|
||||||
|
private let verticalCenterFraction: CGFloat = 0.5
|
||||||
|
private let gutterFillColor: NSColor = .controlBackgroundColor
|
||||||
|
private let gutterDividerColor: NSColor = .separatorColor
|
||||||
|
private let gutterTextColor: NSColor = .tertiaryLabelColor
|
||||||
|
private var gutterFont: NSFont { NSFont.monospacedSystemFont(ofSize: gutterFontSize, weight: .regular) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
// ScratchLineNumberRuler.swift
|
|
||||||
// Lyrebird
|
|
||||||
//
|
|
||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
||||||
// SPDX-License-Identifier: MIT
|
|
||||||
|
|
||||||
// LyrebirdUI/LiveCompile
|
|
||||||
//
|
|
||||||
// Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as
|
|
||||||
// the scroll view's `verticalRulerView` so it tracks scroll position for free.
|
|
||||||
// Reads laid-out glyph rects from the text view's layout manager and writes one
|
|
||||||
// 1-based line label per visible line into the ruler's bounds.
|
|
||||||
|
|
||||||
#if os(macOS)
|
|
||||||
import AppKit
|
|
||||||
|
|
||||||
/// `NSRulerView` subclass rendering one right-aligned line number per laid-out
|
|
||||||
/// line of the host `NSTextView`. Tracks the text view's scroll origin via the
|
|
||||||
/// `boundsDidChangeNotification` posted by the enclosing `NSClipView` and
|
|
||||||
/// invalidates itself on every text edit and frame change.
|
|
||||||
final class ScratchLineNumberRuler: NSRulerView {
|
|
||||||
|
|
||||||
/// Re-resolved on every `draw` so the ruler picks up font / layout-manager
|
|
||||||
/// swaps the text view performs after attachment.
|
|
||||||
private weak var textView: NSTextView?
|
|
||||||
|
|
||||||
init(scrollView: NSScrollView, textView: NSTextView) {
|
|
||||||
self.textView = textView
|
|
||||||
super.init(scrollView: scrollView, orientation: .verticalRuler)
|
|
||||||
self.clientView = textView
|
|
||||||
self.ruleThickness = gutterWidth
|
|
||||||
let center: NotificationCenter = NotificationCenter.default
|
|
||||||
center.addObserver(self,
|
|
||||||
selector: #selector(invalidateForChange(_:)),
|
|
||||||
name: NSText.didChangeNotification,
|
|
||||||
object: textView)
|
|
||||||
center.addObserver(self,
|
|
||||||
selector: #selector(invalidateForChange(_:)),
|
|
||||||
name: NSView.frameDidChangeNotification,
|
|
||||||
object: textView)
|
|
||||||
let clipView: NSClipView = scrollView.contentView
|
|
||||||
clipView.postsBoundsChangedNotifications = true
|
|
||||||
center.addObserver(self,
|
|
||||||
selector: #selector(invalidateForChange(_:)),
|
|
||||||
name: NSView.boundsDidChangeNotification,
|
|
||||||
object: clipView)
|
|
||||||
}
|
|
||||||
|
|
||||||
required init(coder: NSCoder) {
|
|
||||||
fatalError("ScratchLineNumberRuler does not support NSCoder init")
|
|
||||||
}
|
|
||||||
|
|
||||||
deinit {
|
|
||||||
NotificationCenter.default.removeObserver(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func invalidateForChange(_ note: Notification) {
|
|
||||||
needsDisplay = true
|
|
||||||
}
|
|
||||||
|
|
||||||
override func drawHashMarksAndLabels(in rect: NSRect) {
|
|
||||||
guard let textView: NSTextView,
|
|
||||||
let layoutManager: NSLayoutManager = textView.layoutManager,
|
|
||||||
let textContainer: NSTextContainer = textView.textContainer else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
gutterFillColor.setFill()
|
|
||||||
rect.fill()
|
|
||||||
gutterDividerColor.setStroke()
|
|
||||||
let dividerPath: NSBezierPath = NSBezierPath()
|
|
||||||
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
|
||||||
dividerPath.move(to: NSPoint(x: dividerX, y: rect.minY))
|
|
||||||
dividerPath.line(to: NSPoint(x: dividerX, y: rect.maxY))
|
|
||||||
dividerPath.lineWidth = 1
|
|
||||||
dividerPath.stroke()
|
|
||||||
|
|
||||||
let nsText: NSString = textView.string as NSString
|
|
||||||
let totalLength: Int = nsText.length
|
|
||||||
let visibleRect: NSRect = scrollView?.contentView.bounds ?? .zero
|
|
||||||
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: textContainer)
|
|
||||||
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
|
||||||
let inset: CGFloat = textView.textContainerInset.height
|
|
||||||
let attrs: [NSAttributedString.Key: Any] = [
|
|
||||||
.font: rulerFont,
|
|
||||||
.foregroundColor: gutterTextColor,
|
|
||||||
]
|
|
||||||
|
|
||||||
var lineIndex: Int = lineNumber(at: charRange.location, in: nsText)
|
|
||||||
var cursor: Int = charRange.location
|
|
||||||
let visibleEnd: Int = NSMaxRange(charRange)
|
|
||||||
while cursor < visibleEnd && cursor <= totalLength {
|
|
||||||
// `lineRange(for:)` advances cursor by the full line including its
|
|
||||||
// terminator, so `\r`, `\n`, and `\r\n` line endings are all
|
|
||||||
// handled by Foundation.
|
|
||||||
let probeLength: Int = (cursor == totalLength) ? 0 : 0
|
|
||||||
let lineRange: NSRange = nsText.lineRange(for: NSRange(location: cursor, length: probeLength))
|
|
||||||
let lineGlyphRange: NSRange = layoutManager.glyphRange(forCharacterRange: lineRange,
|
|
||||||
actualCharacterRange: nil)
|
|
||||||
let usedRect: NSRect = layoutManager.boundingRect(forGlyphRange: lineGlyphRange,
|
|
||||||
in: textContainer)
|
|
||||||
let yInView: CGFloat = usedRect.minY + inset - visibleRect.minY
|
|
||||||
let label: NSString = "\(lineIndex)" as NSString
|
|
||||||
let size: CGSize = label.size(withAttributes: attrs)
|
|
||||||
let drawPoint: NSPoint = NSPoint(
|
|
||||||
x: bounds.maxX - size.width - rightInset,
|
|
||||||
y: yInView + ((usedRect.height - size.height) * 0.5)
|
|
||||||
)
|
|
||||||
label.draw(at: drawPoint, withAttributes: attrs)
|
|
||||||
|
|
||||||
let advance: Int = NSMaxRange(lineRange)
|
|
||||||
if advance <= cursor { break } // defensive — empty trailing line
|
|
||||||
cursor = advance
|
|
||||||
lineIndex += 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1-based line number of the character at `loc`. Delegates to
|
|
||||||
// `NSString.enumerateSubstrings(.byLines)` so CR, LF, and CRLF endings are
|
|
||||||
// all counted correctly. Linear in `loc`, runs once per draw on the prefix
|
|
||||||
// that precedes the first visible line.
|
|
||||||
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
|
||||||
if loc <= 0 { return 1 }
|
|
||||||
var line: Int = 1
|
|
||||||
let prefixRange: NSRange = NSRange(location: 0, length: loc)
|
|
||||||
text.enumerateSubstrings(in: prefixRange,
|
|
||||||
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
|
||||||
line += 1
|
|
||||||
}
|
|
||||||
return line
|
|
||||||
}
|
|
||||||
|
|
||||||
private let gutterWidth: CGFloat = 40
|
|
||||||
private let rightInset: CGFloat = 6
|
|
||||||
private let dividerHalfPixel: CGFloat = 0.5 // crisp 1px divider on Retina
|
|
||||||
private let rulerFontSize: CGFloat = 11
|
|
||||||
private let gutterFillColor: NSColor = NSColor.controlBackgroundColor
|
|
||||||
private let gutterDividerColor: NSColor = NSColor.separatorColor
|
|
||||||
private let gutterTextColor: NSColor = NSColor.tertiaryLabelColor
|
|
||||||
private var rulerFont: NSFont {
|
|
||||||
NSFont.monospacedSystemFont(ofSize: rulerFontSize, weight: .regular)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
// ScratchScopeView.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdUI/LiveCompile
|
||||||
|
//
|
||||||
|
// A compact real-time oscilloscope for the scratch editor's engine panel.
|
||||||
|
// Reimplemented here (rather than reusing `LyrebirdUI.LyrebirdScopeView`) because
|
||||||
|
// the LiveCompile stack must not link `LyrebirdUI` — that would static-fold a
|
||||||
|
// second copy of `LyrebirdSynth`'s ObjC classes. It reads the same core
|
||||||
|
// `ScopeCapture` the engine writes to.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import SwiftUI
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
|
/// Polls a ``ScopeCapture`` at ~30 Hz and draws each captured channel's waveform
|
||||||
|
/// with `Canvas`. Channels stack vertically; channel 0 cyan, channel 1 orange.
|
||||||
|
struct ScratchScopeView: View {
|
||||||
|
|
||||||
|
let capture: ScopeCapture
|
||||||
|
|
||||||
|
@State private var channels: [[Float]] = []
|
||||||
|
|
||||||
|
private static let pollIntervalNs: UInt64 = 33_333_333 // ~30 Hz
|
||||||
|
private static let channelColors: [Color] = [.cyan, .orange, .green, .yellow]
|
||||||
|
private static let backgroundColor: Color = Color(white: 0.08)
|
||||||
|
private static let zeroLineOpacity: Double = 0.25
|
||||||
|
private static let separatorOpacity: Double = 0.3
|
||||||
|
private static let waveformHeightFraction: CGFloat = 0.44
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Canvas { ctx, size in
|
||||||
|
ctx.fill(Path(CGRect(origin: .zero, size: size)),
|
||||||
|
with: .color(ScratchScopeView.backgroundColor))
|
||||||
|
guard !channels.isEmpty else { return }
|
||||||
|
let count: Int = channels.count
|
||||||
|
let rowH: CGFloat = size.height / CGFloat(count)
|
||||||
|
|
||||||
|
for (ch, samples): (Int, [Float]) in channels.enumerated() {
|
||||||
|
let midY: CGFloat = rowH * (CGFloat(ch) + 0.5)
|
||||||
|
let halfH: CGFloat = rowH * ScratchScopeView.waveformHeightFraction
|
||||||
|
|
||||||
|
var guide: Path = Path()
|
||||||
|
guide.move(to: CGPoint(x: 0, y: midY))
|
||||||
|
guide.addLine(to: CGPoint(x: size.width, y: midY))
|
||||||
|
ctx.stroke(guide, with: .color(.white.opacity(ScratchScopeView.zeroLineOpacity)),
|
||||||
|
lineWidth: 0.5)
|
||||||
|
|
||||||
|
if ch < count - 1 {
|
||||||
|
let sepY: CGFloat = rowH * CGFloat(ch + 1)
|
||||||
|
var sep: Path = Path()
|
||||||
|
sep.move(to: CGPoint(x: 0, y: sepY))
|
||||||
|
sep.addLine(to: CGPoint(x: size.width, y: sepY))
|
||||||
|
ctx.stroke(sep, with: .color(.white.opacity(ScratchScopeView.separatorOpacity)),
|
||||||
|
lineWidth: 0.5)
|
||||||
|
}
|
||||||
|
|
||||||
|
guard samples.count > 1 else { continue }
|
||||||
|
let color: Color = ScratchScopeView.channelColors[ch % ScratchScopeView.channelColors.count]
|
||||||
|
let xStep: CGFloat = size.width / CGFloat(samples.count - 1)
|
||||||
|
var path: Path = Path()
|
||||||
|
for (i, sample): (Int, Float) in samples.enumerated() {
|
||||||
|
let x: CGFloat = CGFloat(i) * xStep
|
||||||
|
let y: CGFloat = midY - CGFloat(sample) * halfH
|
||||||
|
if i == 0 { path.move(to: CGPoint(x: x, y: y)) }
|
||||||
|
else { path.addLine(to: CGPoint(x: x, y: y)) }
|
||||||
|
}
|
||||||
|
ctx.stroke(path, with: .color(color), lineWidth: 1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.background(ScratchScopeView.backgroundColor)
|
||||||
|
.clipShape(RoundedRectangle(cornerRadius: 4))
|
||||||
|
.task {
|
||||||
|
while !Task.isCancelled {
|
||||||
|
channels = capture.snapshot()
|
||||||
|
try? await Task.sleep(nanoseconds: ScratchScopeView.pollIntervalNs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
// ScratchSwiftTokenizer.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdUI/LiveCompile
|
||||||
|
//
|
||||||
|
// A small, dependency-free lexer that classifies the colorable spans of Swift
|
||||||
|
// source — comments, string literals, numbers, keywords, and Capitalized type
|
||||||
|
// names — for the scratch editor's syntax highlighting. It is intentionally
|
||||||
|
// approximate (a highlighter, not a parser): good enough to read code at a
|
||||||
|
// glance, and re-run whole on every keystroke — a full grapheme walk of the
|
||||||
|
// buffer, fine for typical snippet sizes (not tuned or validated for very large
|
||||||
|
// documents). Pure (no AppKit) so it is unit-testable. Ranges are `NSRange`
|
||||||
|
// (UTF-16), matching `NSTextView`.
|
||||||
|
//
|
||||||
|
// macOS only — consumed by the macOS-only scratch editor.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Classifies Swift source into colorable token spans for syntax highlighting.
|
||||||
|
enum ScratchSwiftTokenizer {
|
||||||
|
|
||||||
|
/// A colorable category. Uncategorized text (identifiers, punctuation,
|
||||||
|
/// whitespace) produces no token and renders in the default text color.
|
||||||
|
enum Kind: Equatable {
|
||||||
|
case keyword
|
||||||
|
case type
|
||||||
|
case string
|
||||||
|
case number
|
||||||
|
case comment
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One colorable span. `range` is a UTF-16 `NSRange` into the source.
|
||||||
|
struct Token: Equatable {
|
||||||
|
let range: NSRange
|
||||||
|
let kind: Kind
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Swift keywords (plus a few common contextual ones) colored as keywords.
|
||||||
|
private static let keywords: Set<String> = [
|
||||||
|
"associatedtype", "class", "deinit", "enum", "extension", "fileprivate",
|
||||||
|
"func", "import", "init", "inout", "internal", "let", "open", "operator",
|
||||||
|
"private", "precedencegroup", "protocol", "public", "rethrows", "static",
|
||||||
|
"struct", "subscript", "typealias", "var",
|
||||||
|
"break", "case", "continue", "default", "defer", "do", "else",
|
||||||
|
"fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch",
|
||||||
|
"where", "while",
|
||||||
|
"as", "await", "catch", "false", "is", "nil", "self", "Self", "super",
|
||||||
|
"throw", "throws", "true", "try", "Any",
|
||||||
|
"async", "some", "any", "mutating", "nonmutating", "weak", "unowned",
|
||||||
|
"final", "lazy", "indirect", "convenience", "required", "optional",
|
||||||
|
"override", "dynamic", "willSet", "didSet", "get", "set",
|
||||||
|
"actor", "nonisolated", "isolated", "distributed", "consuming",
|
||||||
|
"borrowing", "sending", "each",
|
||||||
|
]
|
||||||
|
|
||||||
|
/// UTF-16 length of the `"""` multiline-string delimiter.
|
||||||
|
private static let tripleQuoteDelimiterLength: Int = 3
|
||||||
|
|
||||||
|
/// Classify `text` into colorable token spans, left to right.
|
||||||
|
static func tokens(in text: String) -> [Token] {
|
||||||
|
let chars: [Character] = Array(text)
|
||||||
|
let count: Int = chars.count
|
||||||
|
// Prefix table of UTF-16 offsets so `[a, b)` maps to an exact NSRange
|
||||||
|
// even with multi-unit characters (emoji in a comment, etc.).
|
||||||
|
var utf16Starts: [Int] = [Int](repeating: 0, count: count + 1)
|
||||||
|
var acc: Int = 0
|
||||||
|
for k: Int in 0..<count {
|
||||||
|
utf16Starts[k] = acc
|
||||||
|
acc += chars[k].utf16.count
|
||||||
|
}
|
||||||
|
utf16Starts[count] = acc
|
||||||
|
|
||||||
|
func makeRange(_ start: Int, _ end: Int) -> NSRange {
|
||||||
|
NSRange(location: utf16Starts[start], length: utf16Starts[end] - utf16Starts[start])
|
||||||
|
}
|
||||||
|
|
||||||
|
var tokens: [Token] = []
|
||||||
|
var i: Int = 0
|
||||||
|
while i < count {
|
||||||
|
let c: Character = chars[i]
|
||||||
|
|
||||||
|
// Line comment: // … end of line
|
||||||
|
if c == "/", i + 1 < count, chars[i + 1] == "/" {
|
||||||
|
let start: Int = i
|
||||||
|
i += 2
|
||||||
|
while i < count, chars[i] != "\n" { i += 1 }
|
||||||
|
tokens.append(Token(range: makeRange(start, i), kind: .comment))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Block comment: /* … */ with Swift's nesting.
|
||||||
|
if c == "/", i + 1 < count, chars[i + 1] == "*" {
|
||||||
|
let start: Int = i
|
||||||
|
i += 2
|
||||||
|
var depth: Int = 1
|
||||||
|
while i < count, depth > 0 {
|
||||||
|
if chars[i] == "/", i + 1 < count, chars[i + 1] == "*" {
|
||||||
|
depth += 1
|
||||||
|
i += 2
|
||||||
|
} else if chars[i] == "*", i + 1 < count, chars[i + 1] == "/" {
|
||||||
|
depth -= 1
|
||||||
|
i += 2
|
||||||
|
} else {
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokens.append(Token(range: makeRange(start, i), kind: .comment))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// String literal: triple-quoted (multiline) or single-line.
|
||||||
|
if c == "\"" {
|
||||||
|
let start: Int = i
|
||||||
|
if i + 2 < count, chars[i + 1] == "\"", chars[i + 2] == "\"" {
|
||||||
|
i += tripleQuoteDelimiterLength
|
||||||
|
while i < count {
|
||||||
|
if chars[i] == "\\" { i = min(i + 2, count); continue }
|
||||||
|
if chars[i] == "\"", i + 2 < count,
|
||||||
|
chars[i + 1] == "\"", chars[i + 2] == "\"" {
|
||||||
|
i += tripleQuoteDelimiterLength
|
||||||
|
break
|
||||||
|
}
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
i += 1
|
||||||
|
while i < count {
|
||||||
|
if chars[i] == "\\" { i = min(i + 2, count); continue } // escape
|
||||||
|
if chars[i] == "\"" { i += 1; break }
|
||||||
|
if chars[i] == "\n" { break } // unterminated
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokens.append(Token(range: makeRange(start, i), kind: .string))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Number literal (must start with a digit here).
|
||||||
|
if c.isNumber {
|
||||||
|
let start: Int = i
|
||||||
|
i += 1
|
||||||
|
while i < count {
|
||||||
|
let d: Character = chars[i]
|
||||||
|
if (d == "e" || d == "E" || d == "p" || d == "P"),
|
||||||
|
i + 1 < count, chars[i + 1] == "+" || chars[i + 1] == "-" {
|
||||||
|
i += 2 // signed exponent, e.g. 1e-10
|
||||||
|
} else if d.isHexDigit || d == "_"
|
||||||
|
|| d == "x" || d == "X" || d == "o" || d == "O"
|
||||||
|
|| d == "b" || d == "B" || d == "e" || d == "E"
|
||||||
|
|| d == "p" || d == "P" {
|
||||||
|
i += 1
|
||||||
|
} else if d == ".", i + 1 < count, chars[i + 1].isNumber {
|
||||||
|
i += 1 // decimal point (not a range/member `.`)
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokens.append(Token(range: makeRange(start, i), kind: .number))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attribute: @escaping, @MainActor, …
|
||||||
|
if c == "@" {
|
||||||
|
let start: Int = i
|
||||||
|
i += 1
|
||||||
|
while i < count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
tokens.append(Token(range: makeRange(start, i), kind: .keyword))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Identifier: keyword, Capitalized type, or plain (no token).
|
||||||
|
if c.isLetter || c == "_" {
|
||||||
|
let start: Int = i
|
||||||
|
i += 1
|
||||||
|
while i < count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
let word: String = String(chars[start..<i])
|
||||||
|
if keywords.contains(word) {
|
||||||
|
tokens.append(Token(range: makeRange(start, i), kind: .keyword))
|
||||||
|
} else if let first: Character = word.first, first.isUppercase {
|
||||||
|
tokens.append(Token(range: makeRange(start, i), kind: .type))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
return tokens
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// ScratchSyntaxHighlighter.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
// LyrebirdUI/LiveCompile
|
||||||
|
//
|
||||||
|
// Paints ``ScratchSwiftTokenizer`` token colors onto an `NSTextStorage`. Split
|
||||||
|
// out of the SwiftUI `NSViewRepresentable` so the tokenizer→color→storage wiring
|
||||||
|
// is unit-testable against a plain `NSTextStorage` (no window / view needed).
|
||||||
|
//
|
||||||
|
// macOS only.
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import AppKit
|
||||||
|
|
||||||
|
enum ScratchSyntaxHighlighter {
|
||||||
|
|
||||||
|
/// Foreground color for a token kind. `NSColor.system*` are dynamic, so they
|
||||||
|
/// adapt to the editor's light/dark appearance automatically.
|
||||||
|
static func color(for kind: ScratchSwiftTokenizer.Kind) -> NSColor {
|
||||||
|
switch kind {
|
||||||
|
case .keyword: return .systemPink
|
||||||
|
case .type: return .systemPurple
|
||||||
|
case .string: return .systemRed
|
||||||
|
case .number: return .systemBlue
|
||||||
|
case .comment: return .systemGreen
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Normalize `baseAttributes` (font / paragraph / label color) over the whole
|
||||||
|
/// storage — so a paste or font change can't leave stray styling — then
|
||||||
|
/// overlay per-token foreground colors. Attribute-only: the string is not
|
||||||
|
/// changed, so the caller's selection is preserved.
|
||||||
|
static func apply(to storage: NSTextStorage, baseAttributes: [NSAttributedString.Key: Any]) {
|
||||||
|
let full: NSRange = NSRange(location: 0, length: storage.length)
|
||||||
|
storage.beginEditing()
|
||||||
|
storage.setAttributes(baseAttributes, range: full)
|
||||||
|
for token: ScratchSwiftTokenizer.Token in ScratchSwiftTokenizer.tokens(in: storage.string) {
|
||||||
|
// Ranges come from the same string, but guard against any bounds
|
||||||
|
// drift before touching the storage.
|
||||||
|
let end: Int = token.range.location + token.range.length
|
||||||
|
if token.range.location >= 0, end <= storage.length {
|
||||||
|
storage.addAttribute(.foregroundColor,
|
||||||
|
value: color(for: token.kind),
|
||||||
|
range: token.range)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
storage.endEditing()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
// ToolchainAlert.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import AppKit
|
||||||
|
import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
/// User-facing text for a missing-toolchain warning. Pure/value type so the
|
||||||
|
/// status → message mapping is unit-testable without presenting a modal.
|
||||||
|
public struct ToolchainAlertContent: Equatable {
|
||||||
|
/// Alert title (the `NSAlert.messageText`).
|
||||||
|
public let title: String
|
||||||
|
/// Alert body explaining the problem and the fix (the `NSAlert.informativeText`).
|
||||||
|
public let message: String
|
||||||
|
/// Whether "Install Command Line Tools" is an appropriate remedy (it is for a
|
||||||
|
/// missing toolchain, but not for a present-but-incomplete SDK).
|
||||||
|
public let offersCommandLineToolsInstall: Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Map a toolchain status to alert content, or `nil` when nothing needs saying
|
||||||
|
/// (`.available`). Pure — no side effects.
|
||||||
|
public func toolchainAlertContent(for status: SwiftToolchainStatus) -> ToolchainAlertContent? {
|
||||||
|
let dslNote: String = " The Graph DSL mode works without a toolchain if you'd rather not install one."
|
||||||
|
switch status {
|
||||||
|
case .available:
|
||||||
|
return nil
|
||||||
|
case .missingDeveloperTools:
|
||||||
|
return ToolchainAlertContent(
|
||||||
|
title: "Swift toolchain not found",
|
||||||
|
message: "The Swift scratchpad compiles snippets with swiftc, which needs "
|
||||||
|
+ "Xcode or the Command Line Tools." + dslNote,
|
||||||
|
offersCommandLineToolsInstall: true
|
||||||
|
)
|
||||||
|
case .missingSwiftc:
|
||||||
|
return ToolchainAlertContent(
|
||||||
|
title: "Swift compiler not found",
|
||||||
|
message: "A developer directory is selected, but swiftc could not be resolved. "
|
||||||
|
+ "Install or repair Xcode or the Command Line Tools." + dslNote,
|
||||||
|
offersCommandLineToolsInstall: true
|
||||||
|
)
|
||||||
|
case .missingSDK:
|
||||||
|
return ToolchainAlertContent(
|
||||||
|
title: "macOS SDK not found",
|
||||||
|
message: "swiftc was found but the macOS SDK is missing — your Xcode may be "
|
||||||
|
+ "incomplete. Install a full Xcode." + dslNote,
|
||||||
|
offersCommandLineToolsInstall: false
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// App Store product page for Xcode.
|
||||||
|
private let xcodeAppStoreURL: String = "macappstore://apps.apple.com/app/xcode/id497799835"
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
extension LyrebirdScratchMenuController {
|
||||||
|
|
||||||
|
/// Probe for a Swift toolchain off the main thread and, if missing, present a
|
||||||
|
/// one-time warning alert with install guidance. Safe no-op when the toolchain is
|
||||||
|
/// available. Called once at launch from `installMainMenu`.
|
||||||
|
public func warnIfSwiftToolchainMissing(probe: ToolchainProbe = ToolchainProbe()) {
|
||||||
|
DispatchQueue.global(qos: .utility).async {
|
||||||
|
let status: SwiftToolchainStatus = probe.status()
|
||||||
|
guard let content: ToolchainAlertContent = toolchainAlertContent(for: status) else { return }
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
LyrebirdScratchMenuController.presentToolchainAlert(content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Present the toolchain warning as a modal `NSAlert` with install actions.
|
||||||
|
static func presentToolchainAlert(_ content: ToolchainAlertContent) {
|
||||||
|
let alert: NSAlert = NSAlert()
|
||||||
|
alert.messageText = content.title
|
||||||
|
alert.informativeText = content.message
|
||||||
|
alert.alertStyle = .warning
|
||||||
|
|
||||||
|
// Buttons are added in first→last order; NSAlert returns .alertFirstButtonReturn
|
||||||
|
// for the first, +1 for the next, etc.
|
||||||
|
let installButton: NSButton? = content.offersCommandLineToolsInstall
|
||||||
|
? alert.addButton(withTitle: "Install Command Line Tools")
|
||||||
|
: nil
|
||||||
|
let xcodeButton: NSButton = alert.addButton(withTitle: "Get Xcode")
|
||||||
|
let okButton: NSButton = alert.addButton(withTitle: "OK")
|
||||||
|
|
||||||
|
// Make OK the default (Return) so an accidental Return dismisses rather than
|
||||||
|
// launching the installer / App Store. Clearing the other buttons' key
|
||||||
|
// equivalents removes their default-button status.
|
||||||
|
installButton?.keyEquivalent = ""
|
||||||
|
xcodeButton.keyEquivalent = ""
|
||||||
|
okButton.keyEquivalent = "\r"
|
||||||
|
|
||||||
|
let response: NSApplication.ModalResponse = alert.runModal()
|
||||||
|
let firstButton: NSApplication.ModalResponse = .alertFirstButtonReturn
|
||||||
|
let secondButton: NSApplication.ModalResponse =
|
||||||
|
NSApplication.ModalResponse(rawValue: firstButton.rawValue + 1)
|
||||||
|
|
||||||
|
if content.offersCommandLineToolsInstall {
|
||||||
|
if response == firstButton {
|
||||||
|
launchCommandLineToolsInstaller()
|
||||||
|
} else if response == secondButton {
|
||||||
|
openXcodeInAppStore()
|
||||||
|
}
|
||||||
|
// third button = OK: dismiss.
|
||||||
|
} else {
|
||||||
|
if response == firstButton {
|
||||||
|
openXcodeInAppStore()
|
||||||
|
}
|
||||||
|
// second button = OK: dismiss.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Launch Apple's Command Line Tools installer (`xcode-select --install`). This
|
||||||
|
/// opens Apple's own GUI installer dialog — the app never installs silently.
|
||||||
|
private static func launchCommandLineToolsInstaller() {
|
||||||
|
let xcodeSelectPath: String = "/usr/bin/xcode-select"
|
||||||
|
// Mirror the executable-file pre-check used by the other subprocess helpers.
|
||||||
|
guard FileManager.default.isExecutableFile(atPath: xcodeSelectPath) else {
|
||||||
|
openXcodeInAppStore()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let process: Process = Process()
|
||||||
|
process.executableURL = URL(fileURLWithPath: xcodeSelectPath)
|
||||||
|
process.arguments = ["--install"]
|
||||||
|
do {
|
||||||
|
try process.run()
|
||||||
|
} catch {
|
||||||
|
// If we can't launch it, fall back to the App Store (Xcode includes the tools).
|
||||||
|
openXcodeInAppStore()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open Xcode's App Store product page.
|
||||||
|
private static func openXcodeInAppStore() {
|
||||||
|
guard let url: URL = URL(string: xcodeAppStoreURL) else { return }
|
||||||
|
NSWorkspace.shared.open(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
// ArtifactStagingTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
/// Verifies that a staged artifacts directory is a self-contained, working
|
||||||
|
/// compile root: a snippet compiled against the staged `-I` / `-L` / rpath
|
||||||
|
/// succeeds without reaching back into the original build tree.
|
||||||
|
@Suite("LiveSession artifact staging")
|
||||||
|
struct ArtifactStagingTests {
|
||||||
|
|
||||||
|
/// The dev SPM build dir the tests run from — the staging source.
|
||||||
|
private func buildDir() -> URL? {
|
||||||
|
LiveSession.currentBuildDir()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func umbrellaHeaderPathParses() {
|
||||||
|
let map: String = """
|
||||||
|
module LyrebirdC {
|
||||||
|
umbrella header "/abs/path/Sources/LyrebirdC/include/LyrebirdC.h"
|
||||||
|
export *
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
#expect(LiveSession.umbrellaHeaderPath(in: map) == "/abs/path/Sources/LyrebirdC/include/LyrebirdC.h")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func umbrellaHeaderPathNilWhenAbsent() {
|
||||||
|
#expect(LiveSession.umbrellaHeaderPath(in: "module Foo { export * }") == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func stageProducesPopulatedRootWithStagedModuleMap() throws {
|
||||||
|
guard let src: URL = buildDir() else {
|
||||||
|
// No build dir discoverable (unusual for a test run) — nothing to stage.
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let dest: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
defer { try? FileManager.default.removeItem(at: dest) }
|
||||||
|
|
||||||
|
let staged: URL? = LiveSession.stageArtifacts(from: src, to: dest)
|
||||||
|
#expect(staged == dest)
|
||||||
|
#expect(LiveSession.isArtifactsDirPopulated(dest))
|
||||||
|
|
||||||
|
// The staged C module map must point at the staged header copy, not the
|
||||||
|
// original absolute path under the source tree.
|
||||||
|
let stagedMap: URL = dest
|
||||||
|
.appendingPathComponent("LyrebirdC.build", isDirectory: true)
|
||||||
|
.appendingPathComponent("module.modulemap", isDirectory: false)
|
||||||
|
if FileManager.default.fileExists(atPath: stagedMap.path) {
|
||||||
|
let text: String = try String(contentsOf: stagedMap, encoding: .utf8)
|
||||||
|
#expect(text.contains("\(dest.path)/LyrebirdC.headers"))
|
||||||
|
#expect(!text.contains("/Sources/LyrebirdC/include"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func refusesToClobberNonStagingDir() throws {
|
||||||
|
guard let src: URL = buildDir() else { return }
|
||||||
|
let dest: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
try FileManager.default.createDirectory(at: dest, withIntermediateDirectories: true)
|
||||||
|
defer { try? FileManager.default.removeItem(at: dest) }
|
||||||
|
// A pre-existing file that does NOT look like a staging root.
|
||||||
|
let precious: URL = dest.appendingPathComponent("precious.txt", isDirectory: false)
|
||||||
|
try "keep me".write(to: precious, atomically: true, encoding: .utf8)
|
||||||
|
|
||||||
|
let staged: URL? = LiveSession.stageArtifacts(from: src, to: dest)
|
||||||
|
#expect(staged == nil) // refused
|
||||||
|
#expect(FileManager.default.fileExists(atPath: precious.path)) // untouched
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func idempotentSecondStageKeepsRoot() throws {
|
||||||
|
guard let src: URL = buildDir() else { return }
|
||||||
|
let dest: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
defer { try? FileManager.default.removeItem(at: dest) }
|
||||||
|
|
||||||
|
#expect(LiveSession.stageArtifacts(from: src, to: dest) == dest)
|
||||||
|
// Second call with an unchanged source: still a valid, current root.
|
||||||
|
#expect(LiveSession.stageArtifacts(from: src, to: dest) == dest)
|
||||||
|
#expect(LiveSession.isArtifactsDirPopulated(dest))
|
||||||
|
#expect(LiveSession.stagedDirIsCurrent(dest))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func snippetCompilesFromStagedRoot() async throws {
|
||||||
|
guard let src: URL = buildDir() else { return }
|
||||||
|
guard LiveSession.hasLyrebirdDylib(in: src) else {
|
||||||
|
// Xcode-SPM layout (no dylib) — the staged-link path under test needs
|
||||||
|
// the bare-SPM dylib present; skip when absent.
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let dest: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
defer { try? FileManager.default.removeItem(at: dest) }
|
||||||
|
|
||||||
|
guard let staged: URL = LiveSession.stageArtifacts(from: src, to: dest) else {
|
||||||
|
Issue.record("staging produced no root")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
// Point the session ONLY at the staged root — no original build dir.
|
||||||
|
let session: LiveSession = await LiveSession(
|
||||||
|
engine: engine,
|
||||||
|
attachScope: false,
|
||||||
|
importPaths: [staged, staged.appendingPathComponent("Modules")],
|
||||||
|
librarySearchPaths: [staged],
|
||||||
|
libraries: ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
|
||||||
|
rpaths: [staged]
|
||||||
|
)
|
||||||
|
// A trivial snippet that touches the LyrebirdSynth API proves the module
|
||||||
|
// resolves from the staged root.
|
||||||
|
try await session.compileAndRunAsync("context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||||
|
await session.clearTracked()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -15,8 +15,11 @@ struct DiagnosticParserTests {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
func parsesSingleErrorAtUserBodyLine() throws {
|
func parsesSingleErrorAtUserBodyLine() throws {
|
||||||
// Wrapped snippet preamble is 8 lines; user body starts at line 9.
|
// Representative offset: for a preamble whose user body starts at line 9,
|
||||||
// swiftc reports an error on wrapped line 10 → maps to user line 2.
|
// a swiftc error on wrapped line 10 maps to user line 2. (This tests the
|
||||||
|
// parser's arithmetic directly; the actual harness offset — which shifts
|
||||||
|
// when the preamble changes — is exercised by
|
||||||
|
// `endToEndOffsetMatchesSnippetHarness` below.)
|
||||||
let stderr: String = "/tmp/Snippet.swift:10:14: error: cannot find 'foo' in scope"
|
let stderr: String = "/tmp/Snippet.swift:10:14: error: cannot find 'foo' in scope"
|
||||||
let diagnostics: [Diagnostic] = DiagnosticParser.parse(stderr: stderr, userBodyLineOffset: 9)
|
let diagnostics: [Diagnostic] = DiagnosticParser.parse(stderr: stderr, userBodyLineOffset: 9)
|
||||||
try #require(diagnostics.count == 1)
|
try #require(diagnostics.count == 1)
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// GraphDSLDiagnosticMapperTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdGraphDSLEmbedded
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
@Suite("GraphDSLDiagnosticMapper")
|
||||||
|
struct GraphDSLDiagnosticMapperTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func parseErrorMapsSpanToLineAndColumn() {
|
||||||
|
// Offset 4 in "abc\nX" → line 2, column 1 (the char after the newline).
|
||||||
|
let span: DSLSpan = DSLSpan.point(4)
|
||||||
|
let error: DSLParseError = DSLParseError(kind: .unexpectedCharacter("%"), span: span)
|
||||||
|
let diags: [Diagnostic] = GraphDSLDiagnosticMapper.diagnostics(for: error, source: "abc\n%")
|
||||||
|
#expect(diags.count == 1)
|
||||||
|
#expect(diags[0].line == 2)
|
||||||
|
#expect(diags[0].column == 1)
|
||||||
|
#expect(diags[0].severity == .error)
|
||||||
|
#expect(diags[0].message.contains("unexpected"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func firstColumnOfFirstLineIsOneOne() {
|
||||||
|
let error: DSLParseError = DSLParseError(kind: .unclosedParen, span: DSLSpan.point(0))
|
||||||
|
let diags: [Diagnostic] = GraphDSLDiagnosticMapper.diagnostics(for: error, source: "OscSin(")
|
||||||
|
#expect(diags[0].line == 1)
|
||||||
|
#expect(diags[0].column == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func buildErrorHasNoLine() {
|
||||||
|
let error: DSLBuildError = DSLBuildError.unknownBuiltin("Nope")
|
||||||
|
let diags: [Diagnostic] = GraphDSLDiagnosticMapper.diagnostics(for: error, source: "Nope()")
|
||||||
|
#expect(diags.count == 1)
|
||||||
|
#expect(diags[0].line == nil)
|
||||||
|
#expect(diags[0].message.contains("Nope"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func offsetPastEndClampsToFinalPosition() {
|
||||||
|
let error: DSLParseError = DSLParseError(kind: .unclosedParen, span: DSLSpan.point(1_000))
|
||||||
|
let diags: [Diagnostic] = GraphDSLDiagnosticMapper.diagnostics(for: error, source: "ab\ncd")
|
||||||
|
// Two lines, second is "cd": clamps to line 2, column 3 (past 'd').
|
||||||
|
#expect(diags[0].line == 2)
|
||||||
|
#expect(diags[0].column == 3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -86,6 +86,48 @@ struct LiveCompilerTests {
|
|||||||
// The resolved path must point at an actual executable on disk.
|
// The resolved path must point at an actual executable on disk.
|
||||||
#expect(FileManager.default.isExecutableFile(atPath: path))
|
#expect(FileManager.default.isExecutableFile(atPath: path))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Prewarm
|
||||||
|
|
||||||
|
/// Module-resolution args pointing at the built Lyrebird modules, mirroring
|
||||||
|
/// `LiveSession.makeModuleResolutionArgs()`.
|
||||||
|
private func moduleResolutionArgs() -> [String] {
|
||||||
|
let importPaths: [URL] = LiveSession.defaultImportPaths()
|
||||||
|
var args: [String] = []
|
||||||
|
for path: URL in importPaths {
|
||||||
|
args += ["-I", path.path]
|
||||||
|
}
|
||||||
|
for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) {
|
||||||
|
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||||
|
}
|
||||||
|
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
|
||||||
|
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||||
|
}
|
||||||
|
return args
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The prewarm type-checks `import LyrebirdSynth` / `import LyrebirdLiveCompile`;
|
||||||
|
/// with real module-resolution args it must succeed (cold ~2–3 s the first
|
||||||
|
/// time it builds the `.pcm`). This exercises the mechanism directly, not
|
||||||
|
/// behind `LiveSession.prewarm()`'s error-swallowing `try?`.
|
||||||
|
@Test
|
||||||
|
func prewarmSucceedsWithModuleResolutionArgs() throws {
|
||||||
|
try LiveCompiler.prewarm(extraSwiftcArgs: moduleResolutionArgs())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func prewarmThrowsWhenModulesUnresolvable() {
|
||||||
|
// No `-I`: `import LyrebirdSynth` cannot be found → type-check fails.
|
||||||
|
do {
|
||||||
|
try LiveCompiler.prewarm(extraSwiftcArgs: [])
|
||||||
|
Issue.record("expected prewarm to throw with no module paths")
|
||||||
|
} catch let LiveCompileError.compileFailed(exitCode, stderr) {
|
||||||
|
#expect(exitCode != 0)
|
||||||
|
#expect(!stderr.isEmpty)
|
||||||
|
} catch {
|
||||||
|
Issue.record("expected LiveCompileError.compileFailed, got \(error)")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -0,0 +1,176 @@
|
|||||||
|
// LiveSessionGraphDSLTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdGraphDSLEmbedded
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("LiveSession graph-DSL")
|
||||||
|
struct LiveSessionGraphDSLTests {
|
||||||
|
|
||||||
|
/// NRT engine — `start()` is never called. The DSL graphs use only
|
||||||
|
/// oscillators (no `LyrebirdBuffer`), so no engine run cycle is needed and
|
||||||
|
/// the buffer-teardown race is avoided.
|
||||||
|
private func makeSession() -> LiveSession {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LiveSession(engine: engine)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func anonymousStatementIsTracked() throws {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
|
||||||
|
#expect(session.trackedSynthCount == 1)
|
||||||
|
#expect(session.slotCount == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func multipleAnonymousStatementsEachTrack() throws {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
try session.runGraphDSL("OscSin(freq: 440) * 0.1\nOscSawtooth(freq: 55) * 0.2")
|
||||||
|
#expect(session.trackedSynthCount == 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func namedStatementGoesToASlotNotTracked() throws {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
try session.runGraphDSL("bass = OscSawtooth(freq: 55) * 0.2")
|
||||||
|
#expect(session.trackedSynthCount == 0)
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
#expect(session.slotNames == ["bass"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func nonAdditiveReRunReplacesAnonymousSynths() throws {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
|
||||||
|
try session.runGraphDSL("OscSin(freq: 220) * 0.1")
|
||||||
|
#expect(session.trackedSynthCount == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func additiveReRunKeepsPriorSynths() throws {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
|
||||||
|
try session.runGraphDSL("OscSin(freq: 220) * 0.1", additive: true)
|
||||||
|
#expect(session.trackedSynthCount == 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func namedSlotSurvivesNonAdditiveReRun() throws {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
try session.runGraphDSL("bass = OscSawtooth(freq: 55) * 0.2")
|
||||||
|
// A plain anonymous re-run should not disturb the slot.
|
||||||
|
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
#expect(session.trackedSynthCount == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func parseErrorThrowsGraphDSLFailedWithLine() {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
// `%` starts no token — a lex error on the second line.
|
||||||
|
#expect {
|
||||||
|
try session.runGraphDSL("OscSin(freq: 1)\n%%%")
|
||||||
|
} throws: { error in
|
||||||
|
guard case LiveSessionError.graphDSLFailed(let diags, _) = error else { return false }
|
||||||
|
return diags.count == 1 && diags[0].line == 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func buildErrorThrowsGraphDSLFailedWithoutLine() {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
#expect {
|
||||||
|
try session.runGraphDSL("NotAGenerator(freq: 1)")
|
||||||
|
} throws: { error in
|
||||||
|
guard case LiveSessionError.graphDSLFailed(let diags, _) = error else { return false }
|
||||||
|
return diags.count == 1 && diags[0].line == nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func failedEvaluationLeavesPriorGraphUntouched() throws {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
try session.runGraphDSL("OscSin(freq: 440) * 0.1")
|
||||||
|
#expect(session.trackedSynthCount == 1)
|
||||||
|
// A broken non-additive re-run must NOT clear the playing graph — the
|
||||||
|
// program is built before any engine mutation.
|
||||||
|
#expect(throws: LiveSessionError.self) {
|
||||||
|
try session.runGraphDSL("Nope(freq: 1)")
|
||||||
|
}
|
||||||
|
#expect(session.trackedSynthCount == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Engine whose `pendingQueue` holds only `capacity` (power-of-two) adds
|
||||||
|
/// before it fills — and it is never processed, so it never drains. Lets a
|
||||||
|
/// test drive a deterministic mid-run `.pendingQueueFull`.
|
||||||
|
private func makeSmallQueueSession(capacity: Int) -> LiveSession {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: capacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LiveSession(engine: engine)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func engineRejectionIsPerStatementNotAbortAll() {
|
||||||
|
// A small pending queue fills partway through eight statements. Continue-
|
||||||
|
// on-error attempts EVERY statement, so `tracked + failed == 8` and more
|
||||||
|
// than one failed. An abort-on-first-error loop would stop at the first
|
||||||
|
// rejection, leaving `tracked + failed < 8` and exactly one diagnostic.
|
||||||
|
let session: LiveSession = makeSmallQueueSession(capacity: 4)
|
||||||
|
let count: Int = 8
|
||||||
|
let source: String = (0..<count)
|
||||||
|
.map { "OscSin(freq: \(100 + $0)) * 0.1" }
|
||||||
|
.joined(separator: "\n")
|
||||||
|
var thrownDiags: [Diagnostic] = []
|
||||||
|
do {
|
||||||
|
try session.runGraphDSL(source)
|
||||||
|
Issue.record("expected a pendingQueueFull failure")
|
||||||
|
} catch let LiveSessionError.graphDSLFailed(diags, _) {
|
||||||
|
thrownDiags = diags
|
||||||
|
} catch {
|
||||||
|
Issue.record("unexpected error: \(error)")
|
||||||
|
}
|
||||||
|
#expect(session.trackedSynthCount + thrownDiags.count == count)
|
||||||
|
#expect(thrownDiags.count >= 2)
|
||||||
|
#expect(session.trackedSynthCount >= 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func resetAllClearsDSLTrackedAndSlots() throws {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
try session.runGraphDSL("bass = OscSawtooth(freq: 55) * 0.2\nOscSin(freq: 440) * 0.1")
|
||||||
|
#expect(session.trackedSynthCount == 1)
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
session.resetAll()
|
||||||
|
#expect(session.trackedSynthCount == 0)
|
||||||
|
#expect(session.slotCount == 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -95,6 +95,158 @@ struct LiveSessionTests {
|
|||||||
#expect(session.trackedSynthCount == 1)
|
#expect(session.trackedSynthCount == 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Bare-graph `context.play { … }` — no `SynthesizerBase` subclass — adds
|
||||||
|
/// and tracks a synth, exercising the `ClosureSynthesizer` forwarder.
|
||||||
|
@Test
|
||||||
|
func closurePlayAddsAndTracksBareGraph() async throws {
|
||||||
|
let engine: SynthesisEngine = makeEngine()
|
||||||
|
let session: LiveSession = LiveSession(engine: engine)
|
||||||
|
#expect(session.trackedSynthCount == 0)
|
||||||
|
_ = try await session.compileAndRunAsync(
|
||||||
|
"context.play { OscSin.Audio(freq: 440, mul: 0.1) }"
|
||||||
|
)
|
||||||
|
#expect(session.trackedSynthCount == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Named slots
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func assignSlotReplacesInPlaceKeepingOneVoice() throws {
|
||||||
|
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||||
|
let first: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
|
||||||
|
try session.engine.add(first)
|
||||||
|
session.assignSlot("bass", synth: first)
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
#expect(session.slotNames == ["bass"])
|
||||||
|
// Re-assigning the same name replaces the voice — count stays 1.
|
||||||
|
let second: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
|
||||||
|
try session.engine.add(second)
|
||||||
|
session.assignSlot("bass", synth: second)
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
// Slots are separate from the anonymous tracked list.
|
||||||
|
#expect(session.trackedSynthCount == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func clearSlotRemovesNamedSlotOnly() throws {
|
||||||
|
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||||
|
let a: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
|
||||||
|
let b: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
|
||||||
|
try session.engine.add(a); session.assignSlot("a", synth: a)
|
||||||
|
try session.engine.add(b); session.assignSlot("b", synth: b)
|
||||||
|
#expect(session.slotCount == 2)
|
||||||
|
#expect(session.clearSlot("a") == true)
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
#expect(session.slotNames == ["b"])
|
||||||
|
// Clearing an empty slot is a no-op.
|
||||||
|
#expect(session.clearSlot("missing") == false)
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func clearSlotsRemovesAllSlots() throws {
|
||||||
|
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||||
|
let a: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
|
||||||
|
let b: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
|
||||||
|
try session.engine.add(a); session.assignSlot("a", synth: a)
|
||||||
|
try session.engine.add(b); session.assignSlot("b", synth: b)
|
||||||
|
#expect(session.slotCount == 2)
|
||||||
|
session.clearSlots()
|
||||||
|
#expect(session.slotCount == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func clearTrackedLeavesSlotsIntact() throws {
|
||||||
|
// Slots must survive a non-additive re-evaluation (that is the whole
|
||||||
|
// point) — `clearTracked()` clears only the anonymous list.
|
||||||
|
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||||
|
let anon: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
|
||||||
|
let slotted: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
|
||||||
|
try session.engine.add(anon); session.track(anon)
|
||||||
|
try session.engine.add(slotted); session.assignSlot("bass", synth: slotted)
|
||||||
|
#expect(session.trackedSynthCount == 1)
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
session.clearTracked()
|
||||||
|
#expect(session.trackedSynthCount == 0)
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Swap quantization
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func quantizedSwapSchedulesAndReportsPendingBeat() throws {
|
||||||
|
let engine: SynthesisEngine = makeEngine()
|
||||||
|
let session: LiveSession = LiveSession(engine: engine)
|
||||||
|
session.swapClock = LyrebirdClock(engine: engine, bpm: 120)
|
||||||
|
session.swapQuantize = .nextBeat
|
||||||
|
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
// Offline clock sits at beat 0, so the swap targets beat 1 and is pending.
|
||||||
|
#expect(session.pendingSwapBeat == 1.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func immediateSwapReportsNoPendingBeat() throws {
|
||||||
|
let engine: SynthesisEngine = makeEngine()
|
||||||
|
let session: LiveSession = LiveSession(engine: engine)
|
||||||
|
// No clock set → immediate regardless of the quantize mode.
|
||||||
|
session.swapQuantize = .nextBeat
|
||||||
|
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
#expect(session.pendingSwapBeat == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A running engine: two quantized swaps of the same slot must leave exactly
|
||||||
|
/// one voice in the node tree once the scheduled events have fired.
|
||||||
|
@Test
|
||||||
|
func quantizedSwapReplaceEndsWithOneVoiceInTree() throws {
|
||||||
|
let engine: SynthesisEngine = makeEngine()
|
||||||
|
try engine.start()
|
||||||
|
let session: LiveSession = LiveSession(engine: engine)
|
||||||
|
session.swapClock = LyrebirdClock(engine: engine, bpm: 120)
|
||||||
|
session.swapQuantize = .nextBeat
|
||||||
|
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
|
||||||
|
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.2 })
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
// Beat 1 @ 120 bpm / 48 kHz = 24000 samples; 64-sample blocks.
|
||||||
|
for _: Int in 0..<500 { engine.processBlock(inputSamples: []) }
|
||||||
|
#expect(engine.synthesizerCount == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Regression: clearing a slot *before* its scheduled quantized add fires
|
||||||
|
/// must not orphan the pending voice. The removal is scheduled no earlier
|
||||||
|
/// than the add, so the add and remove cancel out — the tree ends empty.
|
||||||
|
@Test
|
||||||
|
func clearSlotsBeforeScheduledSwapFiresLeavesNoOrphan() throws {
|
||||||
|
let engine: SynthesisEngine = makeEngine()
|
||||||
|
try engine.start()
|
||||||
|
let session: LiveSession = LiveSession(engine: engine)
|
||||||
|
session.swapClock = LyrebirdClock(engine: engine, bpm: 120)
|
||||||
|
session.swapQuantize = .nextBeat
|
||||||
|
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
|
||||||
|
session.clearSlots()
|
||||||
|
#expect(session.slotCount == 0)
|
||||||
|
for _: Int in 0..<500 { engine.processBlock(inputSamples: []) }
|
||||||
|
#expect(engine.synthesizerCount == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// End-to-end through the real swiftc pipeline: `context.play(slot:) { }`
|
||||||
|
/// installs one voice, and a non-additive re-run of the same slot replaces
|
||||||
|
/// it in place (still one voice) — the slot survives the non-additive clear.
|
||||||
|
@Test
|
||||||
|
func closureSlotPlayReplacesAcrossReevaluations() async throws {
|
||||||
|
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||||
|
_ = try await session.compileAndRunAsync(
|
||||||
|
"context.play(slot: \"bass\") { OscSin.Audio(freq: 110, mul: 0.1) }"
|
||||||
|
)
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
#expect(session.trackedSynthCount == 0)
|
||||||
|
_ = try await session.compileAndRunAsync(
|
||||||
|
"context.play(slot: \"bass\") { OscSin.Audio(freq: 220, mul: 0.1) }"
|
||||||
|
)
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
func asyncCompileFailureSurfacesDiagnosticsThroughSnippetCompileFailed() async {
|
func asyncCompileFailureSurfacesDiagnosticsThroughSnippetCompileFailed() async {
|
||||||
let engine: SynthesisEngine = makeEngine()
|
let engine: SynthesisEngine = makeEngine()
|
||||||
@@ -122,6 +274,102 @@ struct LiveSessionTests {
|
|||||||
#expect(session.trackedSynthCount == 0)
|
#expect(session.trackedSynthCount == 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func discoverSPMModuleMapsMatchesTopLevelBuildDirMapsAndDedups() throws {
|
||||||
|
// Fixture mirroring the `swift build` layout: a C target's generated map
|
||||||
|
// sits at `<buildDir>/<Target>.build/module.modulemap`, while a Swift
|
||||||
|
// target's map is one level deeper (`.build/include/module.modulemap`)
|
||||||
|
// and must NOT be picked up.
|
||||||
|
let fm: FileManager = FileManager.default
|
||||||
|
let root: URL = fm.temporaryDirectory
|
||||||
|
.appendingPathComponent("spm-maps-\(UUID().uuidString)", isDirectory: true)
|
||||||
|
defer { try? fm.removeItem(at: root) }
|
||||||
|
|
||||||
|
let cTargetMap: URL = root
|
||||||
|
.appendingPathComponent("LyrebirdC.build", isDirectory: true)
|
||||||
|
.appendingPathComponent("module.modulemap")
|
||||||
|
let swiftTargetMap: URL = root
|
||||||
|
.appendingPathComponent("LyrebirdSynth.build", isDirectory: true)
|
||||||
|
.appendingPathComponent("include", isDirectory: true)
|
||||||
|
.appendingPathComponent("module.modulemap")
|
||||||
|
let nonBuildMap: URL = root
|
||||||
|
.appendingPathComponent("Modules", isDirectory: true)
|
||||||
|
.appendingPathComponent("module.modulemap")
|
||||||
|
for url: URL in [cTargetMap, swiftTargetMap, nonBuildMap] {
|
||||||
|
try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||||
|
try "module X {}".write(to: url, atomically: true, encoding: .utf8)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pass the same path twice to exercise dedup.
|
||||||
|
let found: [URL] = LiveSession.discoverSPMModuleMaps(in: [root, root])
|
||||||
|
#expect(found.count == 1)
|
||||||
|
// Suffix match, not full-path equality: the temp dir resolves through
|
||||||
|
// the `/var` → `/private/var` symlink, so `contentsOfDirectory` returns
|
||||||
|
// a differently-prefixed but equivalent path.
|
||||||
|
#expect(found.first?.path.hasSuffix("LyrebirdC.build/module.modulemap") == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Session reset + snippet accounting
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func resetAllClearsTrackedAndSlots() throws {
|
||||||
|
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||||
|
let anon: ClosureSynthesizer = ClosureSynthesizer { 0.1 }
|
||||||
|
let slotted: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
|
||||||
|
try session.engine.add(anon); session.track(anon)
|
||||||
|
try session.engine.add(slotted); session.assignSlot("bass", synth: slotted)
|
||||||
|
#expect(session.trackedSynthCount == 1)
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
session.resetAll()
|
||||||
|
#expect(session.trackedSynthCount == 0)
|
||||||
|
#expect(session.slotCount == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func resetAllClearsPendingSwap() throws {
|
||||||
|
let engine: SynthesisEngine = makeEngine()
|
||||||
|
let session: LiveSession = LiveSession(engine: engine)
|
||||||
|
session.swapClock = LyrebirdClock(engine: engine, bpm: 120)
|
||||||
|
session.swapQuantize = .nextBeat
|
||||||
|
try session.swapSlot("bass", synth: ClosureSynthesizer { 0.1 })
|
||||||
|
#expect(session.pendingSwapBeat == 1.0)
|
||||||
|
session.resetAll()
|
||||||
|
#expect(session.pendingSwapBeat == nil)
|
||||||
|
#expect(session.slotCount == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func loadedSnippetCountGrowsPerCompile() async throws {
|
||||||
|
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||||
|
#expect(session.loadedSnippetCount == 0)
|
||||||
|
_ = try await session.compileAndRunAsync("context.reportMessage(\"a\")")
|
||||||
|
#expect(session.loadedSnippetCount == 1)
|
||||||
|
_ = try await session.compileAndRunAsync("context.reportMessage(\"b\")")
|
||||||
|
#expect(session.loadedSnippetCount == 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Module-cache prewarm
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func prewarmCompletesAndSetsFlag() async {
|
||||||
|
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||||
|
#expect(session.isPrewarmed == false)
|
||||||
|
// Await the detached prewarm task (a real `swiftc -typecheck` that warms
|
||||||
|
// swiftc's default module cache — cold ~2–3 s the first time).
|
||||||
|
await session.prewarm().value
|
||||||
|
#expect(session.isPrewarmed == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func prewarmIsIdempotentAfterCompletion() async {
|
||||||
|
let session: LiveSession = LiveSession(engine: makeEngine())
|
||||||
|
await session.prewarm().value
|
||||||
|
#expect(session.isPrewarmed == true)
|
||||||
|
// A second call is a no-op (already warmed) and returns immediately.
|
||||||
|
await session.prewarm().value
|
||||||
|
#expect(session.isPrewarmed == true)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
func swiftcArgsIncludeImportLibrarySearchAndRpathFlags() {
|
func swiftcArgsIncludeImportLibrarySearchAndRpathFlags() {
|
||||||
let buildDir: URL = URL(fileURLWithPath: "/tmp/fake-build")
|
let buildDir: URL = URL(fileURLWithPath: "/tmp/fake-build")
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
// MessageLogTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("LiveSession message log")
|
||||||
|
struct MessageLogTests {
|
||||||
|
|
||||||
|
private func makeSession() -> LiveSession {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LiveSession(engine: engine)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func accumulatesAndDrains() {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
session.appendMessage("a")
|
||||||
|
session.appendMessage("b")
|
||||||
|
#expect(session.lastSnippetMessage == "b") // last value, for tests
|
||||||
|
#expect(session.drainMessages() == ["a", "b"])
|
||||||
|
// Drained → empty.
|
||||||
|
#expect(session.lastSnippetMessage == nil)
|
||||||
|
#expect(session.drainMessages().isEmpty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
// ScopeAttachTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("LiveSession scope attach")
|
||||||
|
struct ScopeAttachTests {
|
||||||
|
|
||||||
|
private func makeEngine(outChannels: Int = 2) -> SynthesisEngine {
|
||||||
|
SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: outChannels,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func attachesStereoScopeByDefault() {
|
||||||
|
let engine: SynthesisEngine = makeEngine(outChannels: 2)
|
||||||
|
let session: LiveSession = LiveSession(engine: engine)
|
||||||
|
let scope: ScopeCapture? = session.scope
|
||||||
|
#expect(scope != nil)
|
||||||
|
#expect(scope?.buses == [0, 1])
|
||||||
|
// Installed on the engine so the RT thread writes to it.
|
||||||
|
#expect(engine.scopeTap === scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func attachScopeFalseInstallsNothing() {
|
||||||
|
let engine: SynthesisEngine = makeEngine()
|
||||||
|
let session: LiveSession = LiveSession(engine: engine, attachScope: false)
|
||||||
|
#expect(session.scope == nil)
|
||||||
|
#expect(engine.scopeTap == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func monoEngineTapsOneBus() {
|
||||||
|
let engine: SynthesisEngine = makeEngine(outChannels: 1)
|
||||||
|
let session: LiveSession = LiveSession(engine: engine)
|
||||||
|
#expect(session.scope?.buses == [0])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func reusesExistingTapRatherThanReplacing() {
|
||||||
|
let engine: SynthesisEngine = makeEngine()
|
||||||
|
let existing: ScopeCapture = ScopeCapture(buses: [0], bufferSize: 256)
|
||||||
|
engine.scopeTap = existing
|
||||||
|
let session: LiveSession = LiveSession(engine: engine) // attach on, but a tap exists
|
||||||
|
#expect(session.scope === existing)
|
||||||
|
#expect(engine.scopeTap === existing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
// SlotReleaseTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("LiveSession slot release")
|
||||||
|
struct SlotReleaseTests {
|
||||||
|
|
||||||
|
/// A synth whose graceful `release` succeeds (records the call) — stands in
|
||||||
|
/// for a gated `EnvGen` voice.
|
||||||
|
private final class GatedSynth: SynthesizerBase, @unchecked Sendable {
|
||||||
|
var released: Bool = false
|
||||||
|
override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.1)) }
|
||||||
|
override func release(engine: SynthesisEngine) throws { released = true }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A synth with no gate — inherits the default `release` that throws `.noGate`.
|
||||||
|
private final class GatelessSynth: SynthesizerBase, @unchecked Sendable {
|
||||||
|
override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.1)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeStartedSession() throws -> LiveSession {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
let session: LiveSession = LiveSession(engine: engine)
|
||||||
|
try engine.start()
|
||||||
|
return session
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func releaseGatedSlotTriggersReleaseAndDropsHandle() throws {
|
||||||
|
let session: LiveSession = try makeStartedSession()
|
||||||
|
let voice: GatedSynth = GatedSynth()
|
||||||
|
try session.swapSlot("pad", synth: voice)
|
||||||
|
#expect(session.slotNames.contains("pad"))
|
||||||
|
|
||||||
|
let released: Bool = session.releaseSlot("pad")
|
||||||
|
#expect(released)
|
||||||
|
#expect(voice.released) // graceful release fired
|
||||||
|
#expect(session.slotNames.contains("pad") == false) // handle dropped, name free
|
||||||
|
// Safety net: the released voice moves to the tracked list so it stays
|
||||||
|
// reclaimable by resetAll() / Clear Synths even if it never self-frees.
|
||||||
|
#expect(session.trackedSynthCount == 1)
|
||||||
|
session.resetAll()
|
||||||
|
#expect(session.trackedSynthCount == 0)
|
||||||
|
session.engine.stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func nameIsReusableAfterRelease() throws {
|
||||||
|
let session: LiveSession = try makeStartedSession()
|
||||||
|
try session.swapSlot("pad", synth: GatedSynth())
|
||||||
|
#expect(session.releaseSlot("pad"))
|
||||||
|
// The name is free again — a fresh voice claims the slot cleanly.
|
||||||
|
try session.swapSlot("pad", synth: GatedSynth())
|
||||||
|
#expect(session.slotNames.contains("pad"))
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
session.engine.stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func releaseGatelessSlotFailsAndKeepsHandle() throws {
|
||||||
|
let session: LiveSession = try makeStartedSession()
|
||||||
|
try session.swapSlot("bass", synth: GatelessSynth())
|
||||||
|
|
||||||
|
let released: Bool = session.releaseSlot("bass")
|
||||||
|
#expect(released == false)
|
||||||
|
// Not orphaned — still in the slot, still stoppable with a hard clear.
|
||||||
|
#expect(session.slotNames.contains("bass"))
|
||||||
|
#expect(session.clearSlot("bass"))
|
||||||
|
session.engine.stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func releaseEmptySlotReturnsFalse() throws {
|
||||||
|
let session: LiveSession = try makeStartedSession()
|
||||||
|
#expect(session.releaseSlot("nothing-here") == false)
|
||||||
|
session.engine.stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
// SnippetCompletionServiceTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
/// Integration tests that spawn the toolchain's real `sourcekit-lsp` and drive
|
||||||
|
/// it end-to-end. Serialised (`.serialized`) because each launches a server
|
||||||
|
/// subprocess; kept out of the fast unit path by their inherent latency.
|
||||||
|
@MainActor
|
||||||
|
@Suite("SnippetCompletionService", .serialized)
|
||||||
|
struct SnippetCompletionServiceTests {
|
||||||
|
|
||||||
|
private func makeSession() -> LiveSession {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LiveSession(engine: engine)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Member completion after `OscSin.` resolves the generator's nested types —
|
||||||
|
/// proof that sourcekit-lsp sees `LyrebirdSynth` via the generated
|
||||||
|
/// `compile_commands.json`.
|
||||||
|
@Test func completesGeneratorMembers() async throws {
|
||||||
|
let service: SnippetCompletionService = SnippetCompletionService(session: makeSession())
|
||||||
|
try await service.start()
|
||||||
|
defer { service.shutdownSynchronously() }
|
||||||
|
|
||||||
|
let body: String = "let x = OscSin."
|
||||||
|
let items: [LSPCompletionItem] = try await service.completions(
|
||||||
|
userBody: body, line: 0, character: body.count)
|
||||||
|
|
||||||
|
let labels: Set<String> = Set(items.map { $0.label })
|
||||||
|
#expect(labels.contains("Audio"), "expected OscSin.Audio; got \(labels.sorted())")
|
||||||
|
#expect(labels.contains("Control"), "expected OscSin.Control; got \(labels.sorted())")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The injected `context` binding is in scope for the snippet body, so its
|
||||||
|
/// members (`play`, `engine`, …) complete.
|
||||||
|
@Test func completesContextMembers() async throws {
|
||||||
|
let service: SnippetCompletionService = SnippetCompletionService(session: makeSession())
|
||||||
|
try await service.start()
|
||||||
|
defer { service.shutdownSynchronously() }
|
||||||
|
|
||||||
|
let body: String = "context."
|
||||||
|
let items: [LSPCompletionItem] = try await service.completions(
|
||||||
|
userBody: body, line: 0, character: body.count)
|
||||||
|
|
||||||
|
let labels: Set<String> = Set(items.map { $0.label })
|
||||||
|
#expect(labels.contains("engine"), "expected context.engine; got \(labels.sorted())")
|
||||||
|
#expect(labels.contains { $0.hasPrefix("play") },
|
||||||
|
"expected a context.play member; got \(labels.sorted())")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -16,6 +16,9 @@ struct SnippetHarnessTests {
|
|||||||
@Test
|
@Test
|
||||||
func wrappedSourceContainsPreambleAndUserBody() {
|
func wrappedSourceContainsPreambleAndUserBody() {
|
||||||
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: "context.reportMessage(\"hello\")")
|
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: "context.reportMessage(\"hello\")")
|
||||||
|
// Foundation so snippets can use `pow`, `sin`, `Date`, … without an import
|
||||||
|
// (a snippet can't declare one — its body is inside the entry function).
|
||||||
|
#expect(wrapped.source.contains("import Foundation"))
|
||||||
#expect(wrapped.source.contains("import LyrebirdSynth"))
|
#expect(wrapped.source.contains("import LyrebirdSynth"))
|
||||||
#expect(wrapped.source.contains("import LyrebirdLiveCompile"))
|
#expect(wrapped.source.contains("import LyrebirdLiveCompile"))
|
||||||
#expect(wrapped.source.contains("@_cdecl(\"lyrebird_snippet_entry\")"))
|
#expect(wrapped.source.contains("@_cdecl(\"lyrebird_snippet_entry\")"))
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
// SnippetScheduledLoopTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
/// Proves the scratch editor runs *functional* Swift — a real `for` loop that
|
||||||
|
/// schedules a timed sequence — not just single-graph expressions.
|
||||||
|
@MainActor
|
||||||
|
@Suite("Snippet scheduled loop")
|
||||||
|
struct SnippetScheduledLoopTests {
|
||||||
|
|
||||||
|
@Test func snippetCanUseFoundationMath() throws {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 512,
|
||||||
|
controlBlockSize: 64,
|
||||||
|
sampleRate: 44_100,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
let session: LiveSession = LiveSession(engine: engine, attachScope: false)
|
||||||
|
try engine.start()
|
||||||
|
// `pow` / `sin` come from Foundation, which the harness preamble imports —
|
||||||
|
// a snippet can't add the import itself. This would fail to compile
|
||||||
|
// ("cannot find 'pow' in scope") without it.
|
||||||
|
let snippet: String = """
|
||||||
|
let semitone: Double = pow(2.0, 1.0 / 12.0)
|
||||||
|
let freq: Double = 440.0 * semitone
|
||||||
|
context.play { OscSin.Audio(freq: freq) * (0.1 * sin(0.0) + 0.1) }
|
||||||
|
context.reportMessage("math ok \\(freq)")
|
||||||
|
"""
|
||||||
|
try session.compileAndRun(snippet)
|
||||||
|
#expect(session.lastSnippetMessage?.hasPrefix("math ok") == true)
|
||||||
|
session.clearTracked()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func loopSchedulesTenSelfFreeingTones() throws {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 512,
|
||||||
|
controlBlockSize: 64,
|
||||||
|
sampleRate: 44_100,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
let session: LiveSession = LiveSession(engine: engine)
|
||||||
|
try engine.start()
|
||||||
|
|
||||||
|
// A `for` loop that schedules ten short sine tones, 0.35 s apart. Each is
|
||||||
|
// a decaying amplitude envelope (`Line` with `doneAction: .freeNode`)
|
||||||
|
// times a sine, so it plays ~0.2 s and then frees itself — no manual
|
||||||
|
// cleanup, no blocking the main thread.
|
||||||
|
let snippet: String = """
|
||||||
|
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0,
|
||||||
|
440.0, 493.88, 523.25, 587.33, 659.25]
|
||||||
|
for i in 0..<10 {
|
||||||
|
let freq: Double = scale[i]
|
||||||
|
let tone = ClosureSynthesizer {
|
||||||
|
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
|
||||||
|
* OscSin.Audio(freq: freq)
|
||||||
|
}
|
||||||
|
do { try context.engine.schedule(tone, after: Double(i) * 0.35) }
|
||||||
|
catch { context.reportMessage("schedule failed: \\(error)") }
|
||||||
|
}
|
||||||
|
context.reportMessage("scheduled 10 tones")
|
||||||
|
"""
|
||||||
|
|
||||||
|
try session.compileAndRun(snippet)
|
||||||
|
// The `for` loop and the scheduling calls compiled and ran.
|
||||||
|
#expect(session.lastSnippetMessage == "scheduled 10 tones")
|
||||||
|
|
||||||
|
// Advance ~4.5 s of audio; the scheduled adds fire over time. (Each
|
||||||
|
// tone's `.freeNode` self-frees via the engine's async auto-free watcher
|
||||||
|
// in the running app — that background timer doesn't get a turn inside
|
||||||
|
// this synchronous processBlock loop, so here the tones accumulate; the
|
||||||
|
// auto-free path itself is covered by `AutoFreeOnDoneTests`.)
|
||||||
|
let blocks: Int = Int(4.5 * 44_100 / 512)
|
||||||
|
var peakActive: Int = 0
|
||||||
|
var producedAudio: Bool = false
|
||||||
|
for _ in 0..<blocks {
|
||||||
|
engine.processBlock(inputSamples: [])
|
||||||
|
peakActive = max(peakActive, engine.synthesizerCount)
|
||||||
|
if engine.audioBuses[0].contains(where: { $0 != 0 }) { producedAudio = true }
|
||||||
|
}
|
||||||
|
|
||||||
|
#expect(peakActive == 10, "all ten scheduled tones should have entered the tree over time")
|
||||||
|
#expect(producedAudio, "the scheduled tones should have written audio to the bus")
|
||||||
|
engine.stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// SourceKitLSPClientTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
@Suite("SourceKitLSPClient")
|
||||||
|
struct SourceKitLSPClientTests {
|
||||||
|
|
||||||
|
/// A server that never answers must make a request FAIL (`timedOut`) within
|
||||||
|
/// the timeout — not hang. Uses `/bin/sleep` as a stand-in process that stays
|
||||||
|
/// alive but speaks no LSP, so the `initialize` request in `start()` times
|
||||||
|
/// out. Regression guard for the task-group/continuation deadlock where a
|
||||||
|
/// dropped-but-not-resumed continuation left `request(...)` awaiting forever.
|
||||||
|
@Test func requestTimesOutOnUnresponsiveServer() async {
|
||||||
|
let client: SourceKitLSPClient = SourceKitLSPClient(
|
||||||
|
executableURL: URL(fileURLWithPath: "/bin/sleep"),
|
||||||
|
arguments: ["3600"],
|
||||||
|
requestTimeout: 0.5
|
||||||
|
)
|
||||||
|
let start: Date = Date()
|
||||||
|
await #expect(throws: SourceKitLSPError.self) {
|
||||||
|
try await client.start(rootURI: "file:///tmp")
|
||||||
|
}
|
||||||
|
let elapsed: TimeInterval = Date().timeIntervalSince(start)
|
||||||
|
// Must resolve near the 0.5 s timeout, not hang (the old bug never returned).
|
||||||
|
#expect(elapsed < 5.0, "start() took \(elapsed)s — expected a prompt timeout")
|
||||||
|
client.shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A server that launches then exits immediately (EOF on stdout) must fail
|
||||||
|
/// an in-flight request promptly rather than hang the full timeout — the
|
||||||
|
/// reader marks the client not-running and fails pending requests on EOF.
|
||||||
|
/// `/usr/bin/true` exits 0 at once.
|
||||||
|
@Test func serverExitFailsRequestPromptly() async {
|
||||||
|
let client: SourceKitLSPClient = SourceKitLSPClient(
|
||||||
|
executableURL: URL(fileURLWithPath: "/usr/bin/true"),
|
||||||
|
requestTimeout: 10.0
|
||||||
|
)
|
||||||
|
let start: Date = Date()
|
||||||
|
await #expect(throws: SourceKitLSPError.self) {
|
||||||
|
try await client.start(rootURI: "file:///tmp")
|
||||||
|
}
|
||||||
|
let elapsed: TimeInterval = Date().timeIntervalSince(start)
|
||||||
|
#expect(elapsed < 5.0, "server-exit took \(elapsed)s — expected a prompt failure, not a timeout")
|
||||||
|
client.shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Launching a non-existent executable surfaces `.launchFailed` rather than
|
||||||
|
/// crashing or hanging.
|
||||||
|
@Test func launchFailureIsReported() async {
|
||||||
|
let client: SourceKitLSPClient = SourceKitLSPClient(
|
||||||
|
executableURL: URL(fileURLWithPath: "/nonexistent/sourcekit-lsp-xyz"),
|
||||||
|
requestTimeout: 0.5
|
||||||
|
)
|
||||||
|
await #expect(throws: SourceKitLSPError.self) {
|
||||||
|
try await client.start(rootURI: "file:///tmp")
|
||||||
|
}
|
||||||
|
client.shutdown()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
// SwapQuantizeTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("SwapQuantize")
|
||||||
|
struct SwapQuantizeTests {
|
||||||
|
|
||||||
|
/// Offline engine that never processes a block, so `clock.currentBeat`
|
||||||
|
/// stays at 0 — target beats are then deterministic.
|
||||||
|
private func makeClock(bpm: Double = 120) -> LyrebirdClock {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LyrebirdClock(engine: engine, bpm: bpm)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func immediateHasNoTargetBeat() {
|
||||||
|
#expect(SwapQuantize.immediate.targetBeat(clock: makeClock()) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func nextBeatTargetsUpcomingWholeBeat() {
|
||||||
|
#expect(SwapQuantize.nextBeat.targetBeat(clock: makeClock()) == 1.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func nextBarTargetsUpcomingBarBoundary() {
|
||||||
|
#expect(SwapQuantize.nextBar(beatsPerBar: 4).targetBeat(clock: makeClock()) == 4.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func nextBarClampsNonPositiveBeatsPerBar() {
|
||||||
|
// beatsPerBar <= 0 clamps to 1, behaving like `.nextBeat`.
|
||||||
|
#expect(SwapQuantize.nextBar(beatsPerBar: 0).targetBeat(clock: makeClock()) == 1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
// SwiftFormatterTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
@Suite("SwiftFormatter")
|
||||||
|
struct SwiftFormatterTests {
|
||||||
|
|
||||||
|
@Test func formatsMessySource() throws {
|
||||||
|
guard SwiftFormatter.isAvailable else { return } // no toolchain formatter — skip
|
||||||
|
let messy: String = "let x=1\nstruct Foo{let a:Int}\n"
|
||||||
|
let formatted: String = try SwiftFormatter.format(source: messy)
|
||||||
|
// Canonical spacing appears; the mangled originals are gone.
|
||||||
|
#expect(formatted.contains("let x = 1"))
|
||||||
|
#expect(!formatted.contains("let x=1"))
|
||||||
|
#expect(!formatted.contains("struct Foo"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func alreadyFormattedIsStable() throws {
|
||||||
|
guard SwiftFormatter.isAvailable else { return }
|
||||||
|
let clean: String = "let x = 1\n"
|
||||||
|
let once: String = try SwiftFormatter.format(source: clean)
|
||||||
|
let twice: String = try SwiftFormatter.format(source: once)
|
||||||
|
#expect(once == twice) // idempotent
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func parseErrorThrowsFormatFailed() {
|
||||||
|
guard SwiftFormatter.isAvailable else { return }
|
||||||
|
// Unbalanced brace — swift-format should exit non-zero.
|
||||||
|
let broken: String = "func f( {\n"
|
||||||
|
var caught: SwiftFormatterError?
|
||||||
|
do {
|
||||||
|
_ = try SwiftFormatter.format(source: broken)
|
||||||
|
} catch let error as SwiftFormatterError {
|
||||||
|
caught = error
|
||||||
|
} catch {
|
||||||
|
Issue.record("unexpected error type: \(error)")
|
||||||
|
}
|
||||||
|
guard case .formatFailed = caught else {
|
||||||
|
Issue.record("expected .formatFailed, got \(String(describing: caught))")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// ToolchainProbeTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
|
||||||
|
@Suite("ToolchainProbe")
|
||||||
|
struct ToolchainProbeTests {
|
||||||
|
|
||||||
|
private func probe(swiftc: String?, sdk: String?, devDir: String?) -> ToolchainProbe {
|
||||||
|
ToolchainProbe(
|
||||||
|
swiftcResolver: { swiftc },
|
||||||
|
sdkResolver: { sdk },
|
||||||
|
developerDirResolver: { devDir }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("swiftc + SDK both present → available")
|
||||||
|
func availableWhenBothResolve() {
|
||||||
|
#expect(probe(swiftc: "/usr/bin/swiftc", sdk: "/SDK", devDir: "/Dev").status() == .available)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("no swiftc and no developer dir → missingDeveloperTools")
|
||||||
|
func missingDeveloperTools() {
|
||||||
|
#expect(probe(swiftc: nil, sdk: nil, devDir: nil).status() == .missingDeveloperTools)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("no swiftc but developer dir present → missingSwiftc")
|
||||||
|
func missingSwiftc() {
|
||||||
|
#expect(probe(swiftc: nil, sdk: nil, devDir: "/Dev").status() == .missingSwiftc)
|
||||||
|
// SDK value is irrelevant when swiftc is unresolved.
|
||||||
|
#expect(probe(swiftc: nil, sdk: "/SDK", devDir: "/Dev").status() == .missingSwiftc)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("swiftc present but SDK missing → missingSDK")
|
||||||
|
func missingSDK() {
|
||||||
|
#expect(probe(swiftc: "/usr/bin/swiftc", sdk: nil, devDir: "/Dev").status() == .missingSDK)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("default probe on a build machine finds developer tools")
|
||||||
|
func defaultProbeFindsDeveloperTools() {
|
||||||
|
// Any machine that can build/test this package has a developer directory, so
|
||||||
|
// the real (non-injected) resolvers must never report missingDeveloperTools —
|
||||||
|
// this smoke-tests that the default xcode-select / xcrun probes actually run.
|
||||||
|
// (Not asserting strict `.available`: a full-SDK requirement would couple the
|
||||||
|
// suite to the host's exact toolchain completeness.)
|
||||||
|
#expect(ToolchainProbe().status() != .missingDeveloperTools)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
// EditorPositionMappingTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("editorLineAndUTF16Char")
|
||||||
|
struct EditorPositionMappingTests {
|
||||||
|
|
||||||
|
@Test func offsetZeroIsOrigin() {
|
||||||
|
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "abc\ndef", utf16Offset: 0)
|
||||||
|
#expect(line == 0)
|
||||||
|
#expect(char == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func withinFirstLineCountsColumns() {
|
||||||
|
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "let x = OscSin.", utf16Offset: 15)
|
||||||
|
#expect(line == 0)
|
||||||
|
#expect(char == 15)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func afterNewlineResetsColumn() {
|
||||||
|
// "abc\nde" — offset 5 is the 'e' on line 1, column 2.
|
||||||
|
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "abc\nde", utf16Offset: 5)
|
||||||
|
#expect(line == 1)
|
||||||
|
#expect(char == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func startOfSecondLineIsColumnZero() {
|
||||||
|
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "ab\ncd", utf16Offset: 3)
|
||||||
|
#expect(line == 1)
|
||||||
|
#expect(char == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func offsetPastEndClampsToFinalPosition() {
|
||||||
|
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "ab\ncd", utf16Offset: 999)
|
||||||
|
#expect(line == 1)
|
||||||
|
#expect(char == 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func astralCharacterCountsAsTwoUTF16Units() {
|
||||||
|
// "😀x" — the emoji is a surrogate pair (2 UTF-16 units); 'x' is at char 2.
|
||||||
|
let (line, char): (Int, Int) = editorLineAndUTF16Char(in: "😀x", utf16Offset: 2)
|
||||||
|
#expect(line == 0)
|
||||||
|
#expect(char == 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -64,7 +64,9 @@ struct LyrebirdScratchModelTests {
|
|||||||
#expect(model.diagnostics.isEmpty)
|
#expect(model.diagnostics.isEmpty)
|
||||||
#expect(model.statusMessage.contains("replaced"))
|
#expect(model.statusMessage.contains("replaced"))
|
||||||
#expect(model.statusMessage.contains("Tracked synths: 0"))
|
#expect(model.statusMessage.contains("Tracked synths: 0"))
|
||||||
#expect(session.lastSnippetMessage == "hello")
|
// The report message is drained from the session into the console.
|
||||||
|
#expect(model.consoleEntries.contains { $0.kind == .message && $0.text == "hello" })
|
||||||
|
#expect(session.lastSnippetMessage == nil) // drained
|
||||||
#expect(model.isCompiling == false)
|
#expect(model.isCompiling == false)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,7 +97,7 @@ struct LyrebirdScratchModelTests {
|
|||||||
await model.run(additive: false)
|
await model.run(additive: false)
|
||||||
model.clearTracked()
|
model.clearTracked()
|
||||||
#expect(model.trackedSynthCount == 0)
|
#expect(model.trackedSynthCount == 0)
|
||||||
#expect(model.statusMessage == "Cleared tracked synths.")
|
#expect(model.statusMessage == "Cleared all synths (tracked + slots).")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -166,6 +168,151 @@ struct LyrebirdScratchModelTests {
|
|||||||
#expect(model.text == original)
|
#expect(model.text == original)
|
||||||
#expect(model.documentURL == nil)
|
#expect(model.documentURL == nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Re-eval readiness signal
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func blankInitialTextIsEmptyState() {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: " \n\t")
|
||||||
|
#expect(model.reevalState == .empty)
|
||||||
|
#expect(model.reevalState.canEvaluate == false)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func nonBlankInitialTextIsDirtyState() {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// hi")
|
||||||
|
#expect(model.reevalState == .dirty)
|
||||||
|
#expect(model.reevalState.canEvaluate == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func editingBlankToContentGoesDirty() {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "")
|
||||||
|
#expect(model.reevalState == .empty)
|
||||||
|
model.text = "context.reportMessage(\"x\")"
|
||||||
|
#expect(model.reevalState == .dirty)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A successful run drives the buffer `.dirty` → `.compiling` → `.clean`.
|
||||||
|
// (`LiveSession.discoverSPMModuleMaps` makes the snippet compile under a
|
||||||
|
// bare `swift test`, so a valid snippet reliably succeeds here.)
|
||||||
|
@Test
|
||||||
|
func runSettlesToCleanOnSuccess() async {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||||
|
session: session,
|
||||||
|
initialText: "context.reportMessage(\"x\")"
|
||||||
|
)
|
||||||
|
#expect(model.reevalState == .dirty)
|
||||||
|
let ok: Bool = await model.run(additive: false)
|
||||||
|
#expect(ok)
|
||||||
|
#expect(model.reevalState == .clean)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func editingAfterCleanReturnsToDirty() async {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||||
|
session: session,
|
||||||
|
initialText: "context.reportMessage(\"x\")"
|
||||||
|
)
|
||||||
|
let ok: Bool = await model.run(additive: false)
|
||||||
|
#expect(ok)
|
||||||
|
#expect(model.reevalState == .clean)
|
||||||
|
model.text = "context.reportMessage(\"y\")"
|
||||||
|
#expect(model.reevalState == .dirty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func failedRunEntersFailedWithDiagnosticCount() async {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||||
|
session: session,
|
||||||
|
initialText: "let x: Int = \"nope\"\n"
|
||||||
|
)
|
||||||
|
await model.run(additive: false)
|
||||||
|
#expect(model.reevalState == .failed(diagnosticCount: model.diagnostics.count))
|
||||||
|
#expect(model.diagnostics.isEmpty == false)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func clearTrackedDropsBaselineToDirty() async {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||||
|
session: session,
|
||||||
|
initialText: "context.reportMessage(\"x\")"
|
||||||
|
)
|
||||||
|
let ok: Bool = await model.run(additive: false)
|
||||||
|
#expect(ok)
|
||||||
|
#expect(model.reevalState == .clean)
|
||||||
|
model.clearTracked()
|
||||||
|
// Nothing the buffer produced is still playing → a re-run is meaningful.
|
||||||
|
#expect(model.reevalState == .dirty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func quantizedRunEntersQueuedThenSettles() async throws {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
session.swapClock = LyrebirdClock(engine: session.engine, bpm: 120)
|
||||||
|
session.swapQuantize = .nextBeat
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||||
|
session: session,
|
||||||
|
initialText: "context.play(slot: \"bass\") { OscSin.Audio(freq: 110, mul: 0.1) }"
|
||||||
|
)
|
||||||
|
let ok: Bool = await model.run(additive: false)
|
||||||
|
#expect(ok)
|
||||||
|
// Compiled + scheduled: queued until beat 1 (offline clock sits at 0).
|
||||||
|
if case .queued(let beat) = model.reevalState {
|
||||||
|
#expect(beat == 1.0)
|
||||||
|
} else {
|
||||||
|
Issue.record("expected .queued, got \(model.reevalState)")
|
||||||
|
}
|
||||||
|
// Still pending → refresh is a no-op.
|
||||||
|
model.refreshQueuedState()
|
||||||
|
if case .queued = model.reevalState {} else {
|
||||||
|
Issue.record("expected still .queued")
|
||||||
|
}
|
||||||
|
// Once the swap is no longer pending (here: clock dropped), it settles
|
||||||
|
// to .clean since the buffer is unchanged.
|
||||||
|
session.swapClock = nil
|
||||||
|
model.refreshQueuedState()
|
||||||
|
#expect(model.reevalState == .clean)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func clearTrackedFullResetAlsoClearsSlots() throws {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// x")
|
||||||
|
let slotted: ClosureSynthesizer = ClosureSynthesizer { 0.2 }
|
||||||
|
try session.engine.add(slotted)
|
||||||
|
session.assignSlot("bass", synth: slotted)
|
||||||
|
#expect(session.slotCount == 1)
|
||||||
|
// The model's "Clear Synths" is a full reset — tracked + slots.
|
||||||
|
model.clearTracked()
|
||||||
|
#expect(session.slotCount == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func loadEntersDirtyEvenIfContentMatchesPriorRun() async throws {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
let source: String = "context.reportMessage(\"x\")"
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: source)
|
||||||
|
let ok: Bool = await model.run(additive: false)
|
||||||
|
#expect(ok)
|
||||||
|
#expect(model.reevalState == .clean)
|
||||||
|
// Load the *same* source from disk: the run baseline is dropped, so it
|
||||||
|
// reads as dirty rather than clean.
|
||||||
|
let url: URL = FileManager.default
|
||||||
|
.temporaryDirectory
|
||||||
|
.appendingPathComponent("scratch_\(UUID().uuidString).swift")
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
try source.write(to: url, atomically: true, encoding: .utf8)
|
||||||
|
try model.load(from: url)
|
||||||
|
#expect(model.reevalState == .dirty)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// ReevalStateTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("ReevalState")
|
||||||
|
struct ReevalStateTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func canEvaluateFalseWhenEmptyOrCompiling() {
|
||||||
|
#expect(ReevalState.empty.canEvaluate == false)
|
||||||
|
#expect(ReevalState.compiling.canEvaluate == false)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func canEvaluateTrueWhenRunnable() {
|
||||||
|
#expect(ReevalState.dirty.canEvaluate == true)
|
||||||
|
#expect(ReevalState.clean.canEvaluate == true)
|
||||||
|
#expect(ReevalState.queued(untilBeat: 4.0).canEvaluate == true)
|
||||||
|
#expect(ReevalState.failed(diagnosticCount: 0).canEvaluate == true)
|
||||||
|
#expect(ReevalState.failed(diagnosticCount: 3).canEvaluate == true)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func failedCarriesDiagnosticCount() {
|
||||||
|
#expect(ReevalState.failed(diagnosticCount: 2) == .failed(diagnosticCount: 2))
|
||||||
|
#expect(ReevalState.failed(diagnosticCount: 2) != .failed(diagnosticCount: 5))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
// RenderOptionsAccessoryTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import AppKit
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
// Serialized: these tests mutate a shared `UserDefaults` key (the persisted
|
||||||
|
// last-format), so they must not interleave.
|
||||||
|
@Suite("RenderOptionsAccessory", .serialized)
|
||||||
|
@MainActor
|
||||||
|
struct RenderOptionsAccessoryTests {
|
||||||
|
|
||||||
|
// Popup order (see RenderOptionsAccessory.options).
|
||||||
|
private let wavFloat32Index: Int = 0
|
||||||
|
private let wavInt24Index: Int = 2
|
||||||
|
private let rf64Float32Index: Int = 5
|
||||||
|
|
||||||
|
private func makeAccessory() -> (RenderOptionsAccessory, NSSavePanel) {
|
||||||
|
let panel: NSSavePanel = NSSavePanel()
|
||||||
|
let accessory: RenderOptionsAccessory = RenderOptionsAccessory(
|
||||||
|
baseName: "render", initialDuration: 5.0, savePanel: panel
|
||||||
|
)
|
||||||
|
return (accessory, panel)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Duration parsing
|
||||||
|
|
||||||
|
@Test("parseDuration accepts positive finite numbers and rejects the rest")
|
||||||
|
func durationParsing() {
|
||||||
|
#expect(RenderOptionsAccessory.parseDuration("5.0") == 5.0)
|
||||||
|
#expect(RenderOptionsAccessory.parseDuration(" 2.5 ") == 2.5)
|
||||||
|
#expect(RenderOptionsAccessory.parseDuration("0") == nil)
|
||||||
|
#expect(RenderOptionsAccessory.parseDuration("-1") == nil)
|
||||||
|
#expect(RenderOptionsAccessory.parseDuration("") == nil)
|
||||||
|
#expect(RenderOptionsAccessory.parseDuration("abc") == nil)
|
||||||
|
#expect(RenderOptionsAccessory.parseDuration("nan") == nil)
|
||||||
|
#expect(RenderOptionsAccessory.parseDuration("inf") == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Format read-out
|
||||||
|
|
||||||
|
@Test("Selecting a format updates selectedFormat")
|
||||||
|
func selectedFormatReflectsPopup() {
|
||||||
|
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||||
|
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||||
|
let (accessory, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||||
|
|
||||||
|
accessory.selectFormatForTesting(at: wavFloat32Index)
|
||||||
|
#expect(accessory.selectedFormat == .wavFloat32)
|
||||||
|
accessory.selectFormatForTesting(at: wavInt24Index)
|
||||||
|
#expect(accessory.selectedFormat == .wavInt24)
|
||||||
|
accessory.selectFormatForTesting(at: rf64Float32Index)
|
||||||
|
#expect(accessory.selectedFormat == .rf64Float32)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Panel filename sync
|
||||||
|
|
||||||
|
@Test("Changing format preserves a user-typed filename stem")
|
||||||
|
func formatChangePreservesUserStem() {
|
||||||
|
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||||
|
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||||
|
let (accessory, panel): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||||
|
|
||||||
|
// User renames the target, then switches format.
|
||||||
|
panel.nameFieldStringValue = "mySound.caf"
|
||||||
|
accessory.selectFormatForTesting(at: wavFloat32Index)
|
||||||
|
#expect(panel.nameFieldStringValue == "mySound.wav")
|
||||||
|
|
||||||
|
// Switching again keeps the stem, swaps only the extension.
|
||||||
|
accessory.selectFormatForTesting(at: rf64Float32Index)
|
||||||
|
#expect(panel.nameFieldStringValue == "mySound.wav") // RF64 keeps .wav
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("Empty filename falls back to the base name")
|
||||||
|
func emptyStemFallsBackToBaseName() {
|
||||||
|
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||||
|
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||||
|
let (accessory, panel): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||||
|
panel.nameFieldStringValue = ""
|
||||||
|
accessory.selectFormatForTesting(at: wavInt24Index)
|
||||||
|
#expect(panel.nameFieldStringValue == "render.wav")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Persistence
|
||||||
|
|
||||||
|
@Test("Last-selected format persists to a fresh accessory")
|
||||||
|
func formatSelectionPersists() {
|
||||||
|
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||||
|
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||||
|
|
||||||
|
let (first, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||||
|
first.selectFormatForTesting(at: rf64Float32Index) // persists "rf64F32"
|
||||||
|
|
||||||
|
// A brand-new accessory should open on the remembered format.
|
||||||
|
let (second, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||||
|
#expect(second.selectedFormat == .rf64Float32)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
// ScratchModelCompletionTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
/// Integration: `LyrebirdScratchModel.completionItems` end-to-end through the
|
||||||
|
/// real `sourcekit-lsp`. Serialized (each launches a server).
|
||||||
|
@Suite("LyrebirdScratchModel completion", .serialized)
|
||||||
|
@MainActor
|
||||||
|
struct ScratchModelCompletionTests {
|
||||||
|
|
||||||
|
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func swiftModeCompletesGeneratorMembers() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "let x = OscSin.")
|
||||||
|
let items: [LSPCompletionItem] = await model.completionItems(line: 0, character: 15)
|
||||||
|
let labels: Set<String> = Set(items.map { $0.label })
|
||||||
|
#expect(labels.contains("Audio"))
|
||||||
|
#expect(labels.contains("Control"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func graphDSLModeReturnsNoCompletions() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "OscSin.")
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
// DSL mode needs no swiftc/LSP; completion is a no-op (and no server spawns).
|
||||||
|
let items: [LSPCompletionItem] = await model.completionItems(line: 0, character: 7)
|
||||||
|
#expect(items.isEmpty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
// ScratchModelConsoleTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("LyrebirdScratchModel console")
|
||||||
|
@MainActor
|
||||||
|
struct ScratchModelConsoleTests {
|
||||||
|
|
||||||
|
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func successfulRunLogsInfo() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
_ = await model.run(additive: false)
|
||||||
|
#expect(model.consoleEntries.contains { $0.kind == .info })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func failedRunLogsErrorEntries() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "NotAGenerator(freq: 1)")
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
_ = await model.run(additive: false)
|
||||||
|
#expect(model.consoleEntries.contains { $0.kind == .error })
|
||||||
|
#expect(model.consoleEntries.contains { $0.text.contains("NotAGenerator") })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func reportMessagesAppearAsMessages() async {
|
||||||
|
// A DSL run pushes no messages; drive the log directly to prove the
|
||||||
|
// message → console wiring (drainMessages → .message entries).
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
model.session.appendMessage("hello from snippet")
|
||||||
|
_ = await model.run(additive: false)
|
||||||
|
#expect(model.consoleEntries.contains { $0.kind == .message && $0.text == "hello from snippet" })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func clearConsoleEmpties() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
_ = await model.run(additive: false)
|
||||||
|
#expect(!model.consoleEntries.isEmpty)
|
||||||
|
model.clearConsole()
|
||||||
|
#expect(model.consoleEntries.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func resetSessionClearsConsole() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
_ = await model.run(additive: false)
|
||||||
|
#expect(!model.consoleEntries.isEmpty)
|
||||||
|
model.resetSession()
|
||||||
|
#expect(model.consoleEntries.isEmpty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
// ScratchModelEngineTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("LyrebirdScratchModel engine toggle")
|
||||||
|
@MainActor
|
||||||
|
struct ScratchModelEngineTests {
|
||||||
|
|
||||||
|
private func makeModel() -> LyrebirdScratchModel {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LyrebirdScratchModel(session: LiveSession(engine: engine))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func toggleStartsThenStopsEngine() throws {
|
||||||
|
let model: LyrebirdScratchModel = makeModel()
|
||||||
|
let engine: SynthesisEngine = model.session.engine
|
||||||
|
#expect(engine.isRunning == false)
|
||||||
|
|
||||||
|
model.toggleEngine()
|
||||||
|
#expect(engine.isRunning)
|
||||||
|
#expect(model.statusMessage == "Engine started.")
|
||||||
|
|
||||||
|
model.toggleEngine()
|
||||||
|
#expect(engine.isRunning == false)
|
||||||
|
#expect(model.statusMessage == "Engine stopped.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
// ScratchModelFormatTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("LyrebirdScratchModel formatting")
|
||||||
|
@MainActor
|
||||||
|
struct ScratchModelFormatTests {
|
||||||
|
|
||||||
|
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LyrebirdScratchModel(session: LiveSession(engine: engine, attachScope: false), initialText: text)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func formatRewritesMessyBufferAndLogs() async {
|
||||||
|
guard SwiftFormatter.isAvailable else { return } // no toolchain formatter — skip
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "let x=1\n")
|
||||||
|
await model.formatBuffer()
|
||||||
|
#expect(model.text.contains("let x = 1"))
|
||||||
|
#expect(model.consoleEntries.contains { $0.kind == .info })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func formatBlankBufferIsNoOp() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: " \n")
|
||||||
|
let before: String = model.text
|
||||||
|
await model.formatBuffer()
|
||||||
|
#expect(model.text == before)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
// ScratchModelGraphDSLTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("LyrebirdScratchModel graph-DSL mode")
|
||||||
|
@MainActor
|
||||||
|
struct ScratchModelGraphDSLTests {
|
||||||
|
|
||||||
|
private func makeSession() -> LiveSession {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LiveSession(engine: engine)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func defaultsToSwiftMode() {
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: makeSession())
|
||||||
|
#expect(model.evalMode == .swift)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func graphDSLPlaceholderIsGraphOnly() {
|
||||||
|
let placeholder: String = LyrebirdScratchModel.graphDSLPlaceholder
|
||||||
|
#expect(placeholder.contains("OscSin.Audio"))
|
||||||
|
// No `context` API in the DSL surface.
|
||||||
|
#expect(!placeholder.contains("context"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func switchModeSwapsUntouchedPlaceholder() {
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: makeSession())
|
||||||
|
// Buffer still holds the untouched Swift placeholder.
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
#expect(model.evalMode == .graphDSL)
|
||||||
|
#expect(model.text == LyrebirdScratchModel.graphDSLPlaceholder)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func switchModePreservesEditedBuffer() {
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||||
|
session: makeSession(),
|
||||||
|
initialText: "OscSin(freq: 440) * 0.1"
|
||||||
|
)
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
#expect(model.evalMode == .graphDSL)
|
||||||
|
#expect(model.text == "OscSin(freq: 440) * 0.1")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func switchModeToSameModeIsNoOp() {
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: makeSession())
|
||||||
|
let before: String = model.text
|
||||||
|
model.switchMode(to: .swift)
|
||||||
|
#expect(model.text == before)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func switchModeClearsStaleDiagnostics() async {
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||||
|
session: makeSession(),
|
||||||
|
initialText: "NotAGenerator(freq: 1)"
|
||||||
|
)
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
_ = await model.run(additive: false)
|
||||||
|
#expect(!model.diagnostics.isEmpty)
|
||||||
|
// Switching modes must not leave the old run's gutter markers behind.
|
||||||
|
model.switchMode(to: .swift)
|
||||||
|
#expect(model.diagnostics.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func switchModeDropsRunBaselineSoBufferReadsDirty() async {
|
||||||
|
// A buffer that matches the last Swift run must NOT read as `.clean`
|
||||||
|
// after switching to the DSL evaluator, which never ran it.
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||||
|
session: makeSession(),
|
||||||
|
initialText: "OscSin(freq: 440) * 0.1"
|
||||||
|
)
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
_ = await model.run(additive: false)
|
||||||
|
#expect(model.reevalState == .clean)
|
||||||
|
// Back to Swift with the same text: the Swift evaluator hasn't run it.
|
||||||
|
model.switchMode(to: .swift)
|
||||||
|
#expect(model.reevalState == .dirty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func runValidGraphDSLReachesCleanAndTracks() async {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||||
|
session: session,
|
||||||
|
initialText: "OscSin(freq: 440) * 0.1"
|
||||||
|
)
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
let ok: Bool = await model.run(additive: false)
|
||||||
|
#expect(ok)
|
||||||
|
#expect(model.reevalState == .clean)
|
||||||
|
#expect(model.trackedSynthCount == 1)
|
||||||
|
#expect(model.diagnostics.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func runBrokenGraphDSLFailsWithDiagnostics() async {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||||
|
session: session,
|
||||||
|
initialText: "NotAGenerator(freq: 1)"
|
||||||
|
)
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
let ok: Bool = await model.run(additive: false)
|
||||||
|
#expect(!ok)
|
||||||
|
#expect(!model.diagnostics.isEmpty)
|
||||||
|
if case .failed = model.reevalState {} else {
|
||||||
|
Issue.record("expected .failed, got \(model.reevalState)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
func brokenReRunKeepsPriorGraphPlaying() async {
|
||||||
|
let session: LiveSession = makeSession()
|
||||||
|
let model: LyrebirdScratchModel = LyrebirdScratchModel(
|
||||||
|
session: session,
|
||||||
|
initialText: "OscSin(freq: 440) * 0.1"
|
||||||
|
)
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
_ = await model.run(additive: false)
|
||||||
|
#expect(model.trackedSynthCount == 1)
|
||||||
|
model.text = "Nope(freq: 1)"
|
||||||
|
let ok: Bool = await model.run(additive: false)
|
||||||
|
#expect(!ok)
|
||||||
|
// The prior graph is untouched — a bad edit never drops audio.
|
||||||
|
#expect(model.trackedSynthCount == 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// ScratchModelMemoryTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("LyrebirdScratchModel snippet memory")
|
||||||
|
@MainActor
|
||||||
|
struct ScratchModelMemoryTests {
|
||||||
|
|
||||||
|
private func makeModel() -> LyrebirdScratchModel {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LyrebirdScratchModel(session: LiveSession(engine: engine))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func freshModelMirrorsZeroMappedSnippets() {
|
||||||
|
let model: LyrebirdScratchModel = makeModel()
|
||||||
|
#expect(model.loadedSnippetCount == 0)
|
||||||
|
#expect(model.snippetMemoryHint == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func hintIsNilBelowThreshold() {
|
||||||
|
let below: Int = LyrebirdScratchModel.snippetRestartThreshold - 1
|
||||||
|
#expect(LyrebirdScratchModel.snippetMemoryHint(count: 0) == nil)
|
||||||
|
#expect(LyrebirdScratchModel.snippetMemoryHint(count: below) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func hintAppearsAtAndAboveThreshold() {
|
||||||
|
let at: Int = LyrebirdScratchModel.snippetRestartThreshold
|
||||||
|
let atHint: String? = LyrebirdScratchModel.snippetMemoryHint(count: at)
|
||||||
|
#expect(atHint != nil)
|
||||||
|
#expect(atHint?.contains("\(at)") == true)
|
||||||
|
#expect(LyrebirdScratchModel.snippetMemoryHint(count: at + 100) != nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func clearTrackedRefreshesSnippetMirror() {
|
||||||
|
// resetAll (behind clearTracked) does not reclaim dylibs, so the mirror
|
||||||
|
// stays in sync with the session — 0 on a fresh session.
|
||||||
|
let model: LyrebirdScratchModel = makeModel()
|
||||||
|
model.clearTracked()
|
||||||
|
#expect(model.loadedSnippetCount == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func hintMentionsRestartAndDSLAlternative() {
|
||||||
|
let hint: String = LyrebirdScratchModel.snippetMemoryHint(
|
||||||
|
count: LyrebirdScratchModel.snippetRestartThreshold) ?? ""
|
||||||
|
#expect(hint.lowercased().contains("restart"))
|
||||||
|
#expect(hint.contains("Graph DSL"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
// ScratchModelRenderTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import AudioToolbox
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("LyrebirdScratchModel render-to-file")
|
||||||
|
@MainActor
|
||||||
|
struct ScratchModelRenderTests {
|
||||||
|
|
||||||
|
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LyrebirdScratchModel(session: LiveSession(engine: engine, attachScope: false), initialText: text)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func rendersWholeBufferToCAF() async throws {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||||
|
let url: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
|
||||||
|
let duration: Double = 0.25
|
||||||
|
let ok: Bool = await model.renderToFile(url: url, duration: duration)
|
||||||
|
#expect(ok)
|
||||||
|
#expect(FileManager.default.fileExists(atPath: url.path))
|
||||||
|
#expect(model.consoleEntries.contains { $0.kind == .info })
|
||||||
|
|
||||||
|
// The CAF should hold roughly `duration` seconds at the engine's rate.
|
||||||
|
var fileRef: ExtAudioFileRef?
|
||||||
|
#expect(ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr)
|
||||||
|
guard let fileRef: ExtAudioFileRef = fileRef else {
|
||||||
|
Issue.record("could not open rendered CAF")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer { ExtAudioFileDispose(fileRef) }
|
||||||
|
var frames: Int64 = 0
|
||||||
|
var size: UInt32 = UInt32(MemoryLayout<Int64>.size)
|
||||||
|
#expect(ExtAudioFileGetProperty(fileRef, kExtAudioFileProperty_FileLengthFrames, &size, &frames) == noErr)
|
||||||
|
// Allow a block of slack either way.
|
||||||
|
let expected: Double = duration * 48_000
|
||||||
|
#expect(Double(frames) > expected - 128 && Double(frames) < expected + 512)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func rendersSelectionWhenPresent() async {
|
||||||
|
// Whole buffer has two statements; select only the first and render it.
|
||||||
|
let model: LyrebirdScratchModel = makeModel(
|
||||||
|
text: "context.play { OscSin.Audio(freq: 440) * 0.1 }\ncontext.play { OscSin.Audio(freq: 880) * 0.1 }")
|
||||||
|
model.updateSelection("context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||||
|
#expect(model.hasSelection)
|
||||||
|
let url: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
let ok: Bool = await model.renderToFile(url: url, duration: 0.1)
|
||||||
|
#expect(ok)
|
||||||
|
#expect(FileManager.default.fileExists(atPath: url.path))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func nonPositiveDurationFails() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||||
|
let url: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
let ok: Bool = await model.renderToFile(url: url, duration: 0)
|
||||||
|
#expect(!ok)
|
||||||
|
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||||
|
#expect(model.consoleEntries.contains { $0.kind == .error })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func blankBufferRendersNothing() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: " \n")
|
||||||
|
let url: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
let ok: Bool = await model.renderToFile(url: url, duration: 0.1)
|
||||||
|
#expect(!ok)
|
||||||
|
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `format:` argument reaches the NRT driver: rendering to a WAV Int24 target
|
||||||
|
/// and an RF64 target produces files with the requested on-disk encoding.
|
||||||
|
@Test(arguments: [
|
||||||
|
(AudioFileFormat.wavInt24, "wav", UInt32(24), false),
|
||||||
|
(AudioFileFormat.rf64Float32, "wav", UInt32(32), true),
|
||||||
|
])
|
||||||
|
func rendersHonourFormat(format: AudioFileFormat, ext: String, bits: UInt32, isFloat: Bool) async throws {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||||
|
let url: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("LBRenderTest-\(UUID().uuidString)").appendingPathExtension(ext)
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
|
||||||
|
let ok: Bool = await model.renderToFile(url: url, format: format, duration: 0.1)
|
||||||
|
#expect(ok)
|
||||||
|
#expect(FileManager.default.fileExists(atPath: url.path))
|
||||||
|
|
||||||
|
var fileRef: ExtAudioFileRef?
|
||||||
|
#expect(ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr)
|
||||||
|
let ref: ExtAudioFileRef = try #require(fileRef)
|
||||||
|
defer { ExtAudioFileDispose(ref) }
|
||||||
|
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||||
|
var size: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
|
||||||
|
#expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr)
|
||||||
|
#expect(asbd.mBitsPerChannel == bits)
|
||||||
|
#expect((asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0) == isFloat)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
// ScratchModelResetTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("LyrebirdScratchModel resetSession")
|
||||||
|
@MainActor
|
||||||
|
struct ScratchModelResetTests {
|
||||||
|
|
||||||
|
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func resetStopsAudioAndClearsDiagnosticsButKeepsBuffer() async {
|
||||||
|
let source: String = "OscSin(freq: 440) * 0.1"
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: source)
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
_ = await model.run(additive: false) // tracked 1
|
||||||
|
#expect(model.trackedSynthCount == 1)
|
||||||
|
|
||||||
|
model.resetSession()
|
||||||
|
|
||||||
|
#expect(model.trackedSynthCount == 0) // audio stopped
|
||||||
|
#expect(model.diagnostics.isEmpty)
|
||||||
|
// Non-destructive: the user's buffer is preserved.
|
||||||
|
#expect(model.text == source)
|
||||||
|
#expect(model.statusMessage.contains("reset"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func resetLeavesAFreshDirtyBaseline() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
_ = await model.run(additive: false) // .clean
|
||||||
|
model.resetSession()
|
||||||
|
// The placeholder buffer was never run in this fresh session → .dirty.
|
||||||
|
#expect(model.reevalState == .dirty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
// ScratchModelRunSelectionTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdSynth
|
||||||
|
@testable import LyrebirdLiveCompile
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("LyrebirdScratchModel run selection")
|
||||||
|
@MainActor
|
||||||
|
struct ScratchModelRunSelectionTests {
|
||||||
|
|
||||||
|
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 64,
|
||||||
|
controlBlockSize: 16,
|
||||||
|
sampleRate: 48_000,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 16,
|
||||||
|
numControlBuses: 16,
|
||||||
|
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||||
|
driver: OfflineDriver()
|
||||||
|
)
|
||||||
|
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func hasSelectionReflectsNonWhitespaceSelection() {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||||
|
#expect(model.hasSelection == false)
|
||||||
|
model.updateSelection("OscSin(freq: 220) * 0.1")
|
||||||
|
#expect(model.hasSelection)
|
||||||
|
model.updateSelection(" \n ") // whitespace only
|
||||||
|
#expect(model.hasSelection == false)
|
||||||
|
model.updateSelection("")
|
||||||
|
#expect(model.hasSelection == false)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func runSelectionWithNoSelectionIsNoOp() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
let ok: Bool = await model.runSelection()
|
||||||
|
#expect(ok == false)
|
||||||
|
#expect(model.trackedSynthCount == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func runSelectionAddsToRunningWithoutDisturbingBaseline() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
|
||||||
|
// Whole-buffer run establishes the baseline → clean, one synth.
|
||||||
|
_ = await model.run(additive: false)
|
||||||
|
#expect(model.reevalState == .clean)
|
||||||
|
#expect(model.trackedSynthCount == 1)
|
||||||
|
|
||||||
|
// Run a selected fragment: additive (adds a second synth) and leaves the
|
||||||
|
// whole-buffer baseline intact (buffer still matches the last whole run).
|
||||||
|
model.updateSelection("OscSin(freq: 220) * 0.1")
|
||||||
|
let ok: Bool = await model.runSelection()
|
||||||
|
#expect(ok)
|
||||||
|
#expect(model.trackedSynthCount == 2)
|
||||||
|
#expect(model.reevalState == .clean) // baseline untouched
|
||||||
|
#expect(model.diagnostics.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func selectionRunAddsEvenFromADirtyBuffer() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
_ = await model.run(additive: false) // tracked 1, .clean
|
||||||
|
// Dirty the buffer (edited since the last whole run).
|
||||||
|
model.text = "OscSin(freq: 440) * 0.1\n# edited"
|
||||||
|
#expect(model.reevalState == .dirty)
|
||||||
|
|
||||||
|
model.updateSelection("OscSin(freq: 330) * 0.1")
|
||||||
|
_ = await model.runSelection() // additive → tracked 2
|
||||||
|
model.updateSelection("OscSin(freq: 110) * 0.1")
|
||||||
|
_ = await model.runSelection() // additive → tracked 3
|
||||||
|
#expect(model.trackedSynthCount == 3)
|
||||||
|
// The selection runs never replaced, and the buffer stays dirty.
|
||||||
|
#expect(model.reevalState == .dirty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func failedSelectionRunLeavesWholeBufferBadgeUntouched() async {
|
||||||
|
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||||
|
model.switchMode(to: .graphDSL)
|
||||||
|
_ = await model.run(additive: false) // .clean
|
||||||
|
#expect(model.reevalState == .clean)
|
||||||
|
|
||||||
|
// A selection with an unknown generator fails to build.
|
||||||
|
model.updateSelection("NotAGenerator(freq: 1)")
|
||||||
|
let ok: Bool = await model.runSelection()
|
||||||
|
#expect(ok == false)
|
||||||
|
#expect(!model.diagnostics.isEmpty)
|
||||||
|
// The whole-buffer badge must stay clean — the buffer itself is fine.
|
||||||
|
#expect(model.reevalState == .clean)
|
||||||
|
#expect(model.statusMessage.hasPrefix("Selection"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
// ScratchSwiftTokenizerTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("ScratchSwiftTokenizer")
|
||||||
|
struct ScratchSwiftTokenizerTests {
|
||||||
|
|
||||||
|
/// The token kind covering the first occurrence of `substring`, or `nil` if
|
||||||
|
/// no token exactly covers it. Verifies the range maps back to `substring`.
|
||||||
|
private func kind(of substring: String, in source: String) -> ScratchSwiftTokenizer.Kind? {
|
||||||
|
let ns: NSString = source as NSString
|
||||||
|
let target: NSRange = ns.range(of: substring)
|
||||||
|
for token: ScratchSwiftTokenizer.Token in ScratchSwiftTokenizer.tokens(in: source) {
|
||||||
|
if NSEqualRanges(token.range, target) { return token.kind }
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func keywordsAndTypesAndPlainIdentifiers() {
|
||||||
|
let src: String = "let osc = OscSin.Audio(freq: 440)"
|
||||||
|
#expect(kind(of: "let", in: src) == .keyword)
|
||||||
|
#expect(kind(of: "OscSin", in: src) == .type)
|
||||||
|
// Lowercase identifiers produce no token.
|
||||||
|
#expect(kind(of: "osc", in: src) == nil)
|
||||||
|
#expect(kind(of: "freq", in: src) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func numbers() {
|
||||||
|
#expect(kind(of: "440", in: "freq: 440") == .number)
|
||||||
|
#expect(kind(of: "0.15", in: "mul: 0.15") == .number)
|
||||||
|
#expect(kind(of: "0xFF", in: "let x = 0xFF") == .number)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func numberDoesNotEatRangeOperator() {
|
||||||
|
// `1...5` must not be swallowed into one number token — the `.` is only
|
||||||
|
// consumed when followed by a digit.
|
||||||
|
let src: String = "for i in 1...5 {}"
|
||||||
|
#expect(kind(of: "1", in: src) == .number)
|
||||||
|
#expect(kind(of: "5", in: src) == .number)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func strings() {
|
||||||
|
#expect(kind(of: "\"hello\"", in: "reportMessage(\"hello\")") == .string)
|
||||||
|
// Escaped quote stays inside the string.
|
||||||
|
let esc: String = "let s = \"a\\\"b\""
|
||||||
|
#expect(kind(of: "\"a\\\"b\"", in: esc) == .string)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func lineAndBlockComments() {
|
||||||
|
#expect(kind(of: "// hello", in: "let x = 1 // hello") == .comment)
|
||||||
|
// Nested block comment closes at the outer `*/`.
|
||||||
|
let nested: String = "/* a /* b */ c */"
|
||||||
|
#expect(kind(of: nested, in: nested) == .comment)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func attributesColorAsKeyword() {
|
||||||
|
#expect(kind(of: "@MainActor", in: "@MainActor func f() {}") == .keyword)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func utf16RangesSurviveMultiUnitCharacters() {
|
||||||
|
// An emoji (2 UTF-16 units) before a keyword: the keyword's NSRange must
|
||||||
|
// still line up with the NSString substring.
|
||||||
|
let src: String = "// 🎹\nlet x = 1"
|
||||||
|
#expect(kind(of: "let", in: src) == .keyword)
|
||||||
|
#expect(kind(of: "1", in: src) == .number)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func emptyStringProducesNoTokens() {
|
||||||
|
#expect(ScratchSwiftTokenizer.tokens(in: "").isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Regression: a lone trailing backslash inside an unterminated string used to
|
||||||
|
// overrun the UTF-16 offset table and trap. Tokenizing must not crash, for
|
||||||
|
// both single-line and triple-quoted strings.
|
||||||
|
@Test func trailingBackslashAtEndOfBufferDoesNotCrash() {
|
||||||
|
_ = ScratchSwiftTokenizer.tokens(in: "\"\\") // opening " then \
|
||||||
|
_ = ScratchSwiftTokenizer.tokens(in: "\"\"\"\\") // triple-open then \
|
||||||
|
_ = ScratchSwiftTokenizer.tokens(in: "let s = \"abc\\") // realistic edit
|
||||||
|
// A backslash as the very last character overall.
|
||||||
|
_ = ScratchSwiftTokenizer.tokens(in: "\\")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func signedExponentIsOneNumberToken() {
|
||||||
|
#expect(kind(of: "1e-10", in: "let x = 1e-10") == .number)
|
||||||
|
#expect(kind(of: "2.5E+3", in: "let y = 2.5E+3") == .number)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func concurrencyKeywords() {
|
||||||
|
#expect(kind(of: "actor", in: "actor A {}") == .keyword)
|
||||||
|
#expect(kind(of: "nonisolated", in: "nonisolated func f() {}") == .keyword)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// ScratchSyntaxHighlighterTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import AppKit
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("ScratchSyntaxHighlighter")
|
||||||
|
@MainActor
|
||||||
|
struct ScratchSyntaxHighlighterTests {
|
||||||
|
|
||||||
|
private func color(_ storage: NSTextStorage, at index: Int) -> NSColor? {
|
||||||
|
storage.attribute(.foregroundColor, at: index, effectiveRange: nil) as? NSColor
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func paintsTokenColorsOntoStorage() {
|
||||||
|
let source: String = "let x = 1 // note"
|
||||||
|
let storage: NSTextStorage = NSTextStorage(string: source)
|
||||||
|
let base: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor.labelColor]
|
||||||
|
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
|
||||||
|
|
||||||
|
let ns: NSString = source as NSString
|
||||||
|
// Keyword, number, comment each get their kind's color.
|
||||||
|
#expect(color(storage, at: ns.range(of: "let").location)
|
||||||
|
== ScratchSyntaxHighlighter.color(for: .keyword))
|
||||||
|
#expect(color(storage, at: ns.range(of: "1").location)
|
||||||
|
== ScratchSyntaxHighlighter.color(for: .number))
|
||||||
|
#expect(color(storage, at: ns.range(of: "// note").location)
|
||||||
|
== ScratchSyntaxHighlighter.color(for: .comment))
|
||||||
|
// A plain identifier keeps the base color.
|
||||||
|
#expect(color(storage, at: ns.range(of: "x").location) == NSColor.labelColor)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func reapplyNormalizesAwayStaleColors() {
|
||||||
|
// Edit the source so a previously-colored keyword becomes a plain
|
||||||
|
// identifier; re-applying must reset it to the base color, not leave the
|
||||||
|
// old keyword color behind.
|
||||||
|
let storage: NSTextStorage = NSTextStorage(string: "let value = 1")
|
||||||
|
let base: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor.labelColor]
|
||||||
|
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
|
||||||
|
// "let" -> "lot" (no longer a keyword).
|
||||||
|
let ns0: NSString = "let value = 1" as NSString
|
||||||
|
storage.replaceCharacters(in: ns0.range(of: "let"), with: "lot")
|
||||||
|
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
|
||||||
|
let ns1: NSString = storage.string as NSString
|
||||||
|
#expect(color(storage, at: ns1.range(of: "lot").location) == NSColor.labelColor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
// ScratchTextViewTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import AppKit
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("ScratchTextView.rangeForUserCompletion")
|
||||||
|
@MainActor
|
||||||
|
struct ScratchTextViewTests {
|
||||||
|
|
||||||
|
private func makeTextView(_ text: String, caret: Int) -> ScratchTextView {
|
||||||
|
let tv: ScratchTextView = ScratchTextView(frame: .zero)
|
||||||
|
tv.string = text
|
||||||
|
tv.setSelectedRange(NSRange(location: caret, length: 0))
|
||||||
|
return tv
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Right after a `.`, the completion range is EMPTY at the caret — so a
|
||||||
|
/// member completion inserts after the dot instead of replacing the
|
||||||
|
/// receiver expression (the `context.` → erases `context` bug).
|
||||||
|
@Test func afterDotRangeIsEmptyAtCaret() {
|
||||||
|
let tv: ScratchTextView = makeTextView("context.", caret: 8)
|
||||||
|
let range: NSRange = tv.rangeForUserCompletion
|
||||||
|
#expect(range == NSRange(location: 8, length: 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A dotted member expression: completing after the second dot must not
|
||||||
|
/// reach back over `context.engine`.
|
||||||
|
@Test func afterNestedDotRangeIsEmptyAtCaret() {
|
||||||
|
let text: String = "context.engine."
|
||||||
|
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||||
|
let range: NSRange = tv.rangeForUserCompletion
|
||||||
|
#expect(range == NSRange(location: text.utf16.count, length: 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mid-identifier (no preceding dot): the range covers the run of identifier
|
||||||
|
/// characters before the caret, so the partial word gets replaced.
|
||||||
|
@Test func partialIdentifierCoversWordRange() {
|
||||||
|
let tv: ScratchTextView = makeTextView("OscSi", caret: 5)
|
||||||
|
let range: NSRange = tv.rangeForUserCompletion
|
||||||
|
#expect(range == NSRange(location: 0, length: 5))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Right after an open paren, the range is EMPTY at the caret — an argument
|
||||||
|
/// label (`freq:`) inserts there instead of replacing the receiver
|
||||||
|
/// (`OscSin.Audio(` → erases `OscSin.Audio` bug).
|
||||||
|
@Test func afterOpenParenRangeIsEmptyAtCaret() {
|
||||||
|
let text: String = "OscSin.Audio("
|
||||||
|
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||||
|
let range: NSRange = tv.rangeForUserCompletion
|
||||||
|
#expect(range == NSRange(location: text.utf16.count, length: 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After a comma + space (next argument position), the range is empty too.
|
||||||
|
@Test func afterCommaSpaceRangeIsEmptyAtCaret() {
|
||||||
|
let text: String = "OscSin.Audio(freq: 440, "
|
||||||
|
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||||
|
let range: NSRange = tv.rangeForUserCompletion
|
||||||
|
#expect(range == NSRange(location: text.utf16.count, length: 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A partial argument label inside parens replaces just that partial word,
|
||||||
|
/// not the receiver expression.
|
||||||
|
@Test func partialArgLabelCoversOnlyThePartial() {
|
||||||
|
let text: String = "OscSin.Audio(fr"
|
||||||
|
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||||
|
let range: NSRange = tv.rangeForUserCompletion
|
||||||
|
// `fr` starts at offset 13 (after `OscSin.Audio(`), length 2.
|
||||||
|
#expect(range == NSRange(location: 13, length: 2))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Underscore is an identifier character, so a leading-underscore partial is
|
||||||
|
/// covered whole.
|
||||||
|
@Test func underscoreIsIdentifierChar() {
|
||||||
|
let tv: ScratchTextView = makeTextView("_foo", caret: 4)
|
||||||
|
let range: NSRange = tv.rangeForUserCompletion
|
||||||
|
#expect(range == NSRange(location: 0, length: 4))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
// ToolchainAlertTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#if os(macOS)
|
||||||
|
import Testing
|
||||||
|
import LyrebirdLiveCompile
|
||||||
|
@testable import LyrebirdLiveCompileUI
|
||||||
|
|
||||||
|
@Suite("ToolchainAlert content")
|
||||||
|
struct ToolchainAlertTests {
|
||||||
|
|
||||||
|
@Test("available status produces no alert content")
|
||||||
|
func availableIsNil() {
|
||||||
|
#expect(toolchainAlertContent(for: .available) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("missing-toolchain statuses offer the Command Line Tools install")
|
||||||
|
func missingOffersCLTInstall() {
|
||||||
|
for status: SwiftToolchainStatus in [.missingDeveloperTools, .missingSwiftc] {
|
||||||
|
let content: ToolchainAlertContent? = toolchainAlertContent(for: status)
|
||||||
|
#expect(content != nil)
|
||||||
|
#expect(content?.offersCommandLineToolsInstall == true)
|
||||||
|
#expect(content?.title.isEmpty == false)
|
||||||
|
// Steers the user to the dependency-free fallback.
|
||||||
|
#expect(content?.message.contains("Graph DSL") == true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("missing-SDK does not offer CLT install (needs a full Xcode)")
|
||||||
|
func missingSDKNoCLT() {
|
||||||
|
let content: ToolchainAlertContent? = toolchainAlertContent(for: .missingSDK)
|
||||||
|
#expect(content != nil)
|
||||||
|
#expect(content?.offersCommandLineToolsInstall == false)
|
||||||
|
#expect(content?.message.contains("Xcode") == true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
location = "group:Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj">
|
location = "group:Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj">
|
||||||
</FileRef>
|
</FileRef>
|
||||||
<FileRef
|
<FileRef
|
||||||
location = "group:Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj">
|
location = "group:Demos/LyrebirdScratch/LyrebirdScratch.xcodeproj">
|
||||||
</FileRef>
|
</FileRef>
|
||||||
<FileRef
|
<FileRef
|
||||||
location = "group:Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj">
|
location = "group:Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj">
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ let package = Package(
|
|||||||
// never reference this product — they use `Lyrebird` (static) above.
|
// never reference this product — they use `Lyrebird` (static) above.
|
||||||
.library(name: "LyrebirdDynamic", type: .dynamic, targets: ["LyrebirdSynth"]),
|
.library(name: "LyrebirdDynamic", type: .dynamic, targets: ["LyrebirdSynth"]),
|
||||||
.library(name: "LyrebirdUI", targets: ["LyrebirdUI"]),
|
.library(name: "LyrebirdUI", targets: ["LyrebirdUI"]),
|
||||||
|
.library(name: "LyrebirdGraphDSL", targets: ["LyrebirdGraphDSL"]),
|
||||||
.executable(name: "LyrebirdCLI", targets: ["LyrebirdCLI"]),
|
.executable(name: "LyrebirdCLI", targets: ["LyrebirdCLI"]),
|
||||||
],
|
],
|
||||||
dependencies: [
|
dependencies: [
|
||||||
@@ -110,6 +111,16 @@ let package = Package(
|
|||||||
path: "Sources/LyrebirdBenchmark",
|
path: "Sources/LyrebirdBenchmark",
|
||||||
swiftSettings: [.unsafeFlags(["-O"])]
|
swiftSettings: [.unsafeFlags(["-O"])]
|
||||||
),
|
),
|
||||||
|
// Interpreted graph-DSL. Pure Swift over core `LyrebirdSynth` types —
|
||||||
|
// no swiftc, no AppKit — so it is cross-platform (iOS included). The
|
||||||
|
// `DSLBuiltin` registry it consumes is emitted by the separate
|
||||||
|
// `DSLRegistryGen` code-gen tool (the only thing that depends on
|
||||||
|
// swift-syntax); this shipped target does not.
|
||||||
|
.target(
|
||||||
|
name: "LyrebirdGraphDSL",
|
||||||
|
dependencies: ["LyrebirdSynth"],
|
||||||
|
path: "Sources/LyrebirdGraphDSL"
|
||||||
|
),
|
||||||
.testTarget(
|
.testTarget(
|
||||||
name: "LyrebirdTests",
|
name: "LyrebirdTests",
|
||||||
dependencies: ["LyrebirdSynth"],
|
dependencies: ["LyrebirdSynth"],
|
||||||
@@ -127,6 +138,18 @@ let package = Package(
|
|||||||
],
|
],
|
||||||
path: "Tests/LyrebirdUITests"
|
path: "Tests/LyrebirdUITests"
|
||||||
),
|
),
|
||||||
|
.testTarget(
|
||||||
|
name: "LyrebirdGraphDSLTests",
|
||||||
|
dependencies: [
|
||||||
|
"LyrebirdGraphDSL",
|
||||||
|
"LyrebirdSynth",
|
||||||
|
],
|
||||||
|
path: "Tests/LyrebirdGraphDSLTests",
|
||||||
|
linkerSettings: [
|
||||||
|
.linkedFramework("AudioToolbox"),
|
||||||
|
.linkedFramework("Accelerate"),
|
||||||
|
]
|
||||||
|
),
|
||||||
.testTarget(
|
.testTarget(
|
||||||
name: "LyrebirdCLITests",
|
name: "LyrebirdCLITests",
|
||||||
dependencies: ["LyrebirdCLI"],
|
dependencies: ["LyrebirdCLI"],
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ tone.amp = 0.1
|
|||||||
engine.remove(tone) // fades out at the next block boundary
|
engine.remove(tone) // fades out at the next block boundary
|
||||||
```
|
```
|
||||||
|
|
||||||
Prefer a GUI? The `LyrebirdScratchDemo` app embeds `LyrebirdScratchView`: type a snippet, press **⌘↩** to compile-and-hot-swap it against the live engine (or **⌘⇧↩** to layer additively). Each snippet receives a `SnippetContext` — `context.engine` and `context.play(_:)`:
|
Prefer a GUI? The `LyrebirdScratch` app embeds `LyrebirdScratchView`: type a snippet, press **⌘↩** to compile-and-hot-swap it against the live engine (or **⌘⇧↩** to layer additively). Each snippet receives a `SnippetContext` — `context.engine` and `context.play(_:)`:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
// Snippet body — `context: SnippetContext` is in scope.
|
// Snippet body — `context: SnippetContext` is in scope.
|
||||||
@@ -122,6 +122,8 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
|
|||||||
|
|
||||||
**Read [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md)** — it covers the eight demo projects, how to open the workspace, where to add synthesizers, and the gotchas that will bite you.
|
**Read [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md)** — it covers the eight demo projects, how to open the workspace, where to add synthesizers, and the gotchas that will bite you.
|
||||||
|
|
||||||
|
**New to Swift itself?** [`docs/learning-swift/`](docs/learning-swift/README.md) is a four-part intro to Swift written for Lyrebird users (not iOS developers): a Hello-World tone, Swift basics and best practices, the type system and functional style applied to synthesis graphs, and Xcode / packages / Debug-vs-Release / debugging.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
@@ -174,7 +176,7 @@ Workspace scheme selector exposes ten entries:
|
|||||||
| `LyrebirdNRTDemo` | CLI — offline render to CAF via `NRTDriver` | macOS |
|
| `LyrebirdNRTDemo` | CLI — offline render to CAF via `NRTDriver` | macOS |
|
||||||
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders to CAF via `NRTDriver` | macOS |
|
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders to CAF via `NRTDriver` | macOS |
|
||||||
| `LyrebirdAUv3Demo` | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro, etc. Run the host app once to register the extension. | macOS |
|
| `LyrebirdAUv3Demo` | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro, etc. Run the host app once to register the extension. | macOS |
|
||||||
| `LyrebirdScratchDemo` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
| `LyrebirdScratch` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||||
|
|
||||||
Use `Lyrebird-Package` for day-to-day development of the engine and tests.
|
Use `Lyrebird-Package` for day-to-day development of the engine and tests.
|
||||||
|
|
||||||
@@ -216,7 +218,7 @@ All eight live in [`Demos/`](Demos/). Open via `Lyrebird.xcworkspace`.
|
|||||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render to CAF file via `NRTDriver` | macOS |
|
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render to CAF file via `NRTDriver` | macOS |
|
||||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | CLI — notated `Score` → MusicXML export + offline render to CAF via `NRTDriver` | macOS |
|
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | CLI — notated `Score` → MusicXML export + offline render to CAF via `NRTDriver` | macOS |
|
||||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro | macOS |
|
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro | macOS |
|
||||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
| [`LyrebirdScratch`](Demos/LyrebirdScratch/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||||
|
|
||||||
Each demo has a `Synthesizers/` folder — drop new `SynthesizerBase` subclasses there. See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for step-by-step instructions and per-demo notes.
|
Each demo has a `Synthesizers/` folder — drop new `SynthesizerBase` subclasses there. See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for step-by-step instructions and per-demo notes.
|
||||||
|
|
||||||
@@ -282,7 +284,7 @@ LyrebirdII/
|
|||||||
│ ├── LyrebirdNRTDemo/ # offline renderer
|
│ ├── LyrebirdNRTDemo/ # offline renderer
|
||||||
│ ├── LyrebirdScoreDemo/ # notated Score → MusicXML + offline render
|
│ ├── LyrebirdScoreDemo/ # notated Score → MusicXML + offline render
|
||||||
│ ├── LyrebirdAUv3Demo/ # AUv3 `aumu` plugin reference (LyrebirdFM)
|
│ ├── LyrebirdAUv3Demo/ # AUv3 `aumu` plugin reference (LyrebirdFM)
|
||||||
│ └── LyrebirdScratchDemo/ # live-coding scratchpad (macOS, no sandbox)
|
│ └── LyrebirdScratch/ # live-coding scratchpad (macOS, no sandbox)
|
||||||
├── Tests/
|
├── Tests/
|
||||||
│ ├── LyrebirdTests/ # 5253 engine + generator tests
|
│ ├── LyrebirdTests/ # 5253 engine + generator tests
|
||||||
│ ├── LyrebirdUITests/ # SwiftUI component tests
|
│ ├── LyrebirdUITests/ # SwiftUI component tests
|
||||||
@@ -337,6 +339,7 @@ swift package --disable-sandbox preview-documentation --target Lyrebird
|
|||||||
| Topic | Doc |
|
| Topic | Doc |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **Start here / demo projects** | [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) |
|
| **Start here / demo projects** | [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) |
|
||||||
|
| **New to Swift? Intro for Lyrebird users** | [`docs/learning-swift/README.md`](docs/learning-swift/README.md) |
|
||||||
| **What's new / release notes** | [`RELEASES.md`](RELEASES.md) |
|
| **What's new / release notes** | [`RELEASES.md`](RELEASES.md) |
|
||||||
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
|
| Engine setup and Core Audio | `docs/engine/synthesis-engine.md` |
|
||||||
| Bus memory / In / Out | `docs/engine/bus-system.md` |
|
| Bus memory / In / Out | `docs/engine/bus-system.md` |
|
||||||
|
|||||||
@@ -7,6 +7,476 @@ functionality in a backward-compatible way.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 1.6.4 — `LookAheadLimiter` release time decoupled from look-ahead
|
||||||
|
|
||||||
|
A patch release. One backward-compatible library addition.
|
||||||
|
|
||||||
|
`LookAheadLimiter` gains a `releaseTime` parameter, independent of
|
||||||
|
`lookAheadTime`:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
LookAheadLimiter(in:maxAmplitude:lookAheadTime:releaseTime:sampleRate:)
|
||||||
|
```
|
||||||
|
|
||||||
|
Previously the gain-release one-pole coefficient was derived from
|
||||||
|
`lookAheadTime` (default 5 ms), so the release was fast enough to modulate the
|
||||||
|
gain within a single cycle of a low-frequency signal — audible as distortion on
|
||||||
|
sustained bass when the limiter was driven hard. `releaseTime` (default
|
||||||
|
`0.050`) is now a separate control, read per block from a `ValidGeneratorInput`
|
||||||
|
so it can be driven by a live parameter / knob. The look-ahead window size and
|
||||||
|
the no-overshoot ceiling guarantee are unchanged.
|
||||||
|
|
||||||
|
The new parameter has a default, so existing call sites are source-compatible.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.6.3 — Notarization-ready `macos-ui-xcode` template
|
||||||
|
|
||||||
|
A patch release. Project-scaffolding fixes; no library API changes.
|
||||||
|
|
||||||
|
The `macos-ui-xcode` template (`lyrebird new MyApp --template macos-ui-xcode`)
|
||||||
|
now scaffolds a distributable, notarization-ready macOS performance app out of
|
||||||
|
the box:
|
||||||
|
|
||||||
|
- **Entitlements shipped and wired** — `<name>.entitlements` grants
|
||||||
|
`com.apple.security.device.audio-input` (wired via `CODE_SIGN_ENTITLEMENTS`
|
||||||
|
in both build configs), plus `NSMicrophoneUsageDescription` in `Info.plist`.
|
||||||
|
Under the Hardened Runtime (already enabled) the OS hard-kills the process the
|
||||||
|
moment the AUHAL input bus opens without these. They are harmless for
|
||||||
|
output-only synths — no permission prompt fires until input is actually used.
|
||||||
|
The app is deliberately **unsandboxed**: a live-performance app needs
|
||||||
|
unrestricted audio-device / file / MIDI / OSC access the App Sandbox gates.
|
||||||
|
|
||||||
|
- **Compiles under Swift 6** — fixed a latent actor-isolation error that kept
|
||||||
|
the generated project from building: `NoteController` (calls the engine's
|
||||||
|
`@MainActor add(_:)`) and `AppDelegate` (constructs the main-actor controller
|
||||||
|
and synth) are now `@MainActor`. Xcode app templates are excluded from the
|
||||||
|
`swift build` CI matrix, so this had never been compile-checked; it is now
|
||||||
|
verified end-to-end with `xcodebuild`.
|
||||||
|
|
||||||
|
A normal Lyrebird app needs no module-bundling: Lyrebird is statically linked
|
||||||
|
from SPM source. (The swiftmodule / `LyrebirdC` bundling in `LyrebirdScratch`,
|
||||||
|
added in 1.6.2, is unique to its runtime `swiftc` scratchpad.)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.6.2 — Live Scratch: distributable / notarized app
|
||||||
|
|
||||||
|
A patch release. Live Scratch packaging only; no library API changes.
|
||||||
|
|
||||||
|
A notarized, moved-off-the-build-machine `LyrebirdScratch.app` could not compile
|
||||||
|
snippets — the Swift scratchpad shells out to `swiftc`, and the modules it needs
|
||||||
|
(`LyrebirdSynth`, `LyrebirdLiveCompile`, and the `LyrebirdC` C-shim they depend on)
|
||||||
|
lived only in the dev build tree. Two failures surfaced in order — `no such module
|
||||||
|
'LyrebirdSynth'`, then `missing required module 'LyrebirdC'`. Both are now fixed:
|
||||||
|
|
||||||
|
- **Swiftmodules bundled** — a build phase copies the Lyrebird `.swiftmodule`s into
|
||||||
|
`Resources/LyrebirdArtifacts/Modules` inside the app, and the live compiler adds
|
||||||
|
that directory to its import search path.
|
||||||
|
- **LyrebirdC module relocatable** — the SPM *source* `module.modulemap` (relative
|
||||||
|
header path, so map + `include/` are self-contained) is bundled into
|
||||||
|
`LyrebirdArtifacts/LyrebirdC.build/`, and staging copies relative-header module
|
||||||
|
maps verbatim so the Clang module resolves from the bundle rather than the
|
||||||
|
absolute dev path Xcode's generated map baked in.
|
||||||
|
|
||||||
|
Verified end-to-end: a snippet compile resolving modules **only** from the app
|
||||||
|
bundle typechecks clean, and the notarized app runs the Swift scratchpad on a
|
||||||
|
machine without the dev tree.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.6.1 — Live Scratch: Swift-toolchain detection
|
||||||
|
|
||||||
|
A patch release. Live Scratch quality-of-life; no library API changes.
|
||||||
|
|
||||||
|
The Swift scratchpad compiles snippets by shelling out to `swiftc` (Xcode or the
|
||||||
|
Command Line Tools). Previously a missing toolchain only surfaced as a compile
|
||||||
|
error in the console on the first Run. Now the app **detects it at launch** and
|
||||||
|
shows an alert with actionable install guidance:
|
||||||
|
|
||||||
|
- **Install Command Line Tools** — launches Apple's own installer (`xcode-select
|
||||||
|
--install`); the app never installs anything silently.
|
||||||
|
- **Get Xcode** — opens the App Store product page.
|
||||||
|
|
||||||
|
The check is alert-only and never blocks the app: the **Graph DSL mode needs no
|
||||||
|
toolchain**, so it's the zero-install fallback. (`ToolchainProbe` classifies the
|
||||||
|
toolchain into available / missing-developer-tools / missing-swiftc / missing-SDK,
|
||||||
|
with injectable resolvers so the missing states are unit-tested without uninstalling
|
||||||
|
anything.)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.6.0 — Soundfile format expansion
|
||||||
|
|
||||||
|
A minor release. Backward-compatible — the existing default write formats are
|
||||||
|
unchanged; everything here is additive. One shared `AudioFileFormat` enum now
|
||||||
|
drives every writer (`LyrebirdBuffer.write`, offline `NRTDriver` renders, and the
|
||||||
|
real-time `DiskOut.Audio` recorder).
|
||||||
|
|
||||||
|
### New — audio output formats
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// Buffer / NRT / DiskOut (PCM):
|
||||||
|
try buf.write(to: url, format: .wavInt24, sampleRate: 48000) // 16 / 24-bit WAV
|
||||||
|
try buf.write(to: url, format: .aiffFloat32, sampleRate: 48000) // AIFF-C float
|
||||||
|
try buf.write(to: url, format: .cafFloat32, sampleRate: 48000) // CAF (uncapped)
|
||||||
|
|
||||||
|
// Files past 4 GB — RF64/BW64, keeps the .wav extension:
|
||||||
|
try buf.write(to: url, format: .rf64Float32, sampleRate: 96000)
|
||||||
|
try buf.write(to: url, format: .rf64Int24, sampleRate: 96000)
|
||||||
|
|
||||||
|
// Compressed .m4a — offline writers only (LyrebirdBuffer.write / NRTDriver):
|
||||||
|
try buf.write(to: url, format: .aacHigh, sampleRate: 44100) // AAC ~256 kbps
|
||||||
|
try buf.write(to: url, format: .aacMedium, sampleRate: 44100) // AAC ~128 kbps
|
||||||
|
try buf.write(to: url, format: .alac, sampleRate: 44100) // Apple Lossless
|
||||||
|
```
|
||||||
|
|
||||||
|
- **WAV bit depths** — 16-bit and 24-bit signed-integer PCM alongside 32-bit float.
|
||||||
|
- **AIFF-C** and **CAF** float output across all writers.
|
||||||
|
- **RF64 / BW64** (EBU Tech 3306) — the 64-bit-sized WAV variant for files past the
|
||||||
|
4 GB limit, written by Lyrebird's own `RF64Writer` (CoreAudio has no RF64 *writer*;
|
||||||
|
it reads them back fine). Opt-in `.rf64Float32` / `.rf64Int24`.
|
||||||
|
- **Compressed AAC + Apple Lossless** (`.m4a`) — encoded natively through
|
||||||
|
`ExtAudioFile`/`AudioConverter`, no third-party dependency. **Offline writers only**
|
||||||
|
(`LyrebirdBuffer.write`, `NRTDriver`); `DiskOut.Audio` streams PCM/RF64 only. (MP3 is
|
||||||
|
not offered — CoreAudio has no MP3 encoder.)
|
||||||
|
- **Selectable NRT output** — `NRTDriver` / `NRTJob` take a `format:` (default CAF/float,
|
||||||
|
unchanged), so offline renders and the multi-engine batch pool can bounce to any format.
|
||||||
|
|
||||||
|
### New — large-file safety
|
||||||
|
|
||||||
|
Plain WAV and AIFF-C carry 32-bit size fields (a 4 GB cap). A write projected past
|
||||||
|
that now **throws `fileTooLargeForContainer`** (buffer / NRT) or stops cleanly and sets
|
||||||
|
a pollable `fileTooLarge` flag (streaming `DiskOut`) instead of silently producing a
|
||||||
|
truncated file. CAF and RF64 are 64-bit-sized and uncapped. `NRTDriver` also validates
|
||||||
|
its `duration` (finite, non-negative) — `NRTDriverError.invalidDuration`.
|
||||||
|
|
||||||
|
### New — Live Scratch: Render-to-File format picker
|
||||||
|
|
||||||
|
The Scratch **Render to File** (⌥⌘R) save dialog now carries a **Format** popup (WAV
|
||||||
|
32-bit float / 16-bit / 24-bit, AIFF, CAF, RF64 WAV, and compressed AAC / Apple
|
||||||
|
Lossless) plus the duration field, folded into one dialog. It remembers the last
|
||||||
|
format. Sample rate and channel count still mirror the live engine.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **`DiskOutFormat` is deprecated** — it is now a type alias for `AudioFileFormat`.
|
||||||
|
Existing `DiskOutFormat.wavFloat32` / `.aiff` / etc. spellings keep compiling (with a
|
||||||
|
deprecation warning); migrate to `AudioFileFormat` directly.
|
||||||
|
- `LyrebirdEventList.record(directory:format:)` now takes an `AudioFileFormat`. Stem
|
||||||
|
recording is PCM/RF64 only — a compressed format is rejected with a logged message
|
||||||
|
(stems stream through `DiskOut`, which does not do compressed).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.5.0 — `LyrebirdRandom` + the Live Scratch editor grows up
|
||||||
|
|
||||||
|
A minor release. Backward-compatible — new public API plus a wave of Live Scratch
|
||||||
|
tooling. No changes to existing behavior.
|
||||||
|
|
||||||
|
### New — scalar draws from any distribution (`LyrebirdRandom`)
|
||||||
|
|
||||||
|
Lyrebird had distribution-tied **signals** (noise generators), **sequences**
|
||||||
|
(`Pattern`, `TemporalStream`), and the `DistributionKind` sampling math — but no
|
||||||
|
ergonomic way to get *one value* from a named distribution. `LyrebirdRandom`
|
||||||
|
fills that gap:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
var r = LyrebirdRandom(seed: 42)
|
||||||
|
let freq: Double = r.exponentialRange(low: 200, high: 2000) // Hz, log-uniform
|
||||||
|
let dur: Double = r.uniform(low: 0.1, high: 0.5) // seconds
|
||||||
|
let jitter: Double = r.gauss(mean: 0, dev: 0.02)
|
||||||
|
let skew: Double = r.beta(low: 0, high: 1, alpha: 2, beta: 5)
|
||||||
|
let spike: Double = r.laplace(scale: 1.0)
|
||||||
|
```
|
||||||
|
|
||||||
|
- **`LyrebirdRandom`** — a seedable value type owning a xorshift64 state, so a
|
||||||
|
seed gives a fully reproducible stream of draws (what scored/rendered music
|
||||||
|
wants). Named methods for every family in `DistributionKind` (uniform, low/
|
||||||
|
high/mean-biased, exponential-range, exponential, gamma, laplace, asymmetric
|
||||||
|
laplace, half-cosine, logistic, poisson, arcsin, beta, cauchy, gauss), plus a
|
||||||
|
generic `value(_:parX:parY:parA:parB:)` reaching any kind.
|
||||||
|
- **`LyrebirdRandom.shared`** (`SharedRandom`) — a process-wide, thread-safe
|
||||||
|
source for throwaway draws (system-seeded, non-reproducible). The global
|
||||||
|
**`Random`** is a shorthand for it, for the common non-seeded case:
|
||||||
|
`Random.uniform(low: 0, high: 1)`. (Takes a lock — not RT-safe; use an owned
|
||||||
|
`LyrebirdRandom` inside a Generator.)
|
||||||
|
- **`DistributionKind.sample(parX:parY:parA:parB:using:)`** — the public
|
||||||
|
single-draw dispatcher, now the single source of truth for the case→sampler
|
||||||
|
mapping: `TemporalTendency` and `DemandTemporalTendency` were refactored onto it
|
||||||
|
(behavior pinned by the golden-value tests), so a scalar draw and a stream of
|
||||||
|
the same distribution agree given the same seed.
|
||||||
|
|
||||||
|
For a plain uniform scalar the Swift stdlib (`Double.random(in:)`) is still the
|
||||||
|
lightest choice; reach for `LyrebirdRandom` when you want a *shaped* distribution
|
||||||
|
or a reproducible seeded stream.
|
||||||
|
|
||||||
|
### Live Scratch — renamed and a lot more capable
|
||||||
|
|
||||||
|
The macOS live-coding scratchpad graduated from a demo to a shipping app:
|
||||||
|
**`LyrebirdScratchDemo` → `LyrebirdScratch`** (bundle id
|
||||||
|
`net.realizedsound.LyrebirdScratch`; project, scheme, entitlements renamed). New
|
||||||
|
in the editor:
|
||||||
|
|
||||||
|
- **Render to File (⌥⌘R)** — bounce the selection (or whole buffer) to a **CAF**
|
||||||
|
file offline instead of playing it live. Prompts for a path and duration, builds
|
||||||
|
the graph on a throwaway `NRTDriver` engine mirroring the live engine's settings
|
||||||
|
(so the bounce matches what you heard), renders faster-than-real-time off the
|
||||||
|
main thread, and reveals the file in Finder. Only **sample-clock** timing renders
|
||||||
|
(`engine.schedule`, in-graph triggers) — wall-clock routine/task waits don't.
|
||||||
|
- **Format Code (⌥⌘F)** — pretty-print the buffer with the toolchain's
|
||||||
|
`swift-format`. No-op on a blank buffer; parse errors go to the console.
|
||||||
|
- **Line-number gutter** — a floating `ScratchLineNumberGutter` overlay,
|
||||||
|
positioned from each row's line-fragment rect so numbers align on blank and
|
||||||
|
wrapped lines. (An `NSRulerView` attempt was abandoned — `rulersVisible`
|
||||||
|
mis-tiles the document view inside a SwiftUI `NSViewRepresentable`, blanking the
|
||||||
|
editor.)
|
||||||
|
- **`Foundation` in scope** — snippets can use `pow`, `sin`, `sqrt`, `Date`, … with
|
||||||
|
no `import` (a snippet can't declare one — its body is wrapped in the entry
|
||||||
|
function).
|
||||||
|
- **Manual code completion (Esc / F5)** — no more auto-trigger on `.` that
|
||||||
|
ambushed typing; completion replaces the partial word, not the receiver.
|
||||||
|
- **Fixed — editor scroll-jump**: the engine status readout refreshed via
|
||||||
|
`.id(engineTick)`, tearing down subviews every heartbeat and nudging the scroll
|
||||||
|
offset. Stats now update in place from an `@State` snapshot.
|
||||||
|
|
||||||
|
### New — compile artifacts stage into Application Support (no Documents prompt)
|
||||||
|
|
||||||
|
Swift-mode compilation points `swiftc` at the Lyrebird module artifacts, which in
|
||||||
|
a dev checkout live under `~/Documents` — tripping the macOS "wants to access your
|
||||||
|
Documents folder" gate. `LiveSession.stageArtifacts()` copies the minimal set into
|
||||||
|
`~/Library/Application Support/LyrebirdScratch/LiveCompile/` (ungated), rewriting
|
||||||
|
the C module map's absolute umbrella-header path to a staged copy so the compile
|
||||||
|
is self-contained. Idempotent (a receipt skips an unchanged source), best-effort
|
||||||
|
(falls back to the build dir). A **shipped** app carrying its artifacts in
|
||||||
|
`Contents/Resources/LyrebirdArtifacts` never reads a gated folder — groundwork for
|
||||||
|
a standalone `LyrebirdScratch.app` download.
|
||||||
|
|
||||||
|
### Docs
|
||||||
|
|
||||||
|
New guidance on snippet **timing / scheduling** — `engine.schedule`,
|
||||||
|
`LyrebirdRoutine` / `LyrebirdTask` (background-thread waits), `LyrebirdClock`,
|
||||||
|
in-graph triggers — the retention rule (the snippet is transient), and which
|
||||||
|
mechanisms survive an offline NRT render vs. which are wall-clock-only.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.4.2 — Live-coding: Run Selection + graceful slot release
|
||||||
|
|
||||||
|
A minor release. Backward-compatible — additive conveniences to the (macOS-only)
|
||||||
|
live-coding editor that make per-fragment evaluation and voice lifecycle feel
|
||||||
|
like a proper live-coding environment. No changes to existing public API.
|
||||||
|
|
||||||
|
### New — Run Selection (⌘E)
|
||||||
|
|
||||||
|
Evaluate just the **highlighted text** and *add* it to whatever is already
|
||||||
|
playing — always additively, never a replace. It leaves the rest of the buffer
|
||||||
|
and the whole-buffer re-evaluation baseline (the clean/dirty badge still reflects
|
||||||
|
your last full run) untouched. This is the live-coding "evaluate this line/region,
|
||||||
|
keep going" gesture: audition a single voice, layer it in, iterate. Works in both
|
||||||
|
Swift and Graph DSL modes; no-op with no selection. ⌘↩ / ⌘⇧↩ (whole buffer) are
|
||||||
|
unchanged.
|
||||||
|
|
||||||
|
### New — Start a voice, release it later (`context.release(slot:)`)
|
||||||
|
|
||||||
|
Named slots are the persistent **handle** across evaluations — the slot *name* is
|
||||||
|
your reference (Swift `let`/`var` bindings can't carry from one snippet to the
|
||||||
|
next, since each ⌘↩/⌘E is a separately-compiled unit). Pair that with Run
|
||||||
|
Selection to start a voice in one evaluation and let it go in another:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
// ⌘E this line — start a persistent, gated voice named "pad":
|
||||||
|
context.play(slot: "pad") { EnvGen(gate: 1, /* free-on-done */) * OscSaw.Audio(freq: 110) }
|
||||||
|
|
||||||
|
// …later, ⌘E this line — graceful release: the envelope tails out, then frees:
|
||||||
|
context.release(slot: "pad")
|
||||||
|
```
|
||||||
|
|
||||||
|
- `context.release(slot:)` triggers the voice's envelope **release** phase and
|
||||||
|
frees the name; the voice self-frees via its done-action (and, as a safety net,
|
||||||
|
stays reclaimable by **Clear Synths** if it never does).
|
||||||
|
- `context.free(slot:)` is the **immediate** hard stop — the counterpart, no tail.
|
||||||
|
|
||||||
|
### New — Engine panel (scope + status)
|
||||||
|
|
||||||
|
A panel at the bottom of the scratch window gives an always-on view of the
|
||||||
|
running engine: a live dual-channel **oscilloscope** of the output (fed by a
|
||||||
|
`ScopeCapture` the session attaches to the output buses), plus **CPU
|
||||||
|
average/peak** meter bars and **synth / group / snippet** counts.
|
||||||
|
|
||||||
|
### New — Reset Session + Restart to Reclaim Memory
|
||||||
|
|
||||||
|
Two Run-menu commands for the by-design snippet-dylib cost:
|
||||||
|
|
||||||
|
- **Reset Session** — an in-process, *non-destructive* reset: stops all snippet
|
||||||
|
audio, shuts down the code-completion server (freeing its subprocess and temp
|
||||||
|
files), and clears diagnostics. Your buffer is untouched.
|
||||||
|
- **Restart to Reclaim Memory…** — relaunches the app (with a confirmation), the
|
||||||
|
only way to actually free the mapped snippet dylibs, which cannot be unloaded
|
||||||
|
in-process.
|
||||||
|
|
||||||
|
### New — Console panel
|
||||||
|
|
||||||
|
An always-open panel down the right side logs everything: snippet
|
||||||
|
`context.reportMessage(_:)` output (the live-coding `print`), compile / Graph DSL
|
||||||
|
**errors** with their `line:col`, and a one-line notice per run — oldest first,
|
||||||
|
auto-scrolled, with a **Clear** button. Errors moved here from the old transient
|
||||||
|
bottom strip so they stay visible while you fix them.
|
||||||
|
|
||||||
|
### Faster typing
|
||||||
|
|
||||||
|
Cut the per-keystroke cost in the editor: syntax highlighting is debounced
|
||||||
|
(coalesced after a brief pause instead of a full-buffer re-tokenize on every
|
||||||
|
key), `updateNSView` fast-paths a pure text change, and redundant `@Published`
|
||||||
|
republishes (selection, re-eval state) are elided.
|
||||||
|
|
||||||
|
### Changed — code completion is now manual (Esc / F5)
|
||||||
|
|
||||||
|
Completion no longer auto-opens on `.`. The auto-trigger ambushed typing — after
|
||||||
|
`Pan2.` the popup opened and couldn't be dismissed by deleting, trapping the
|
||||||
|
caret until a candidate was picked. Invoke completion deliberately with **Esc**
|
||||||
|
(or **F5**); a member request after a dot still resolves. Wider default scratch
|
||||||
|
window too (75% of the visible screen width).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.4.1 — "Learning Swift for Lyrebird" intro guide
|
||||||
|
|
||||||
|
A documentation-only release, continuing the doc improvements begun in 1.3. No
|
||||||
|
source or public-API changes. Adds a four-part introduction to Swift written
|
||||||
|
specifically for Lyrebird users coming from SuperCollider, Max/MSP, Csound, and
|
||||||
|
similar tools — people who want just enough Swift to be productive without
|
||||||
|
wading through iOS-development tutorials.
|
||||||
|
|
||||||
|
### New — `docs/learning-swift/`
|
||||||
|
|
||||||
|
Four short guides, meant to be read in order, each grounded in audio examples
|
||||||
|
rather than app-building:
|
||||||
|
|
||||||
|
1. **Hello, World** — from a one-line `print` to a working 440 Hz tone, every
|
||||||
|
line of a Lyrebird program explained (engine → synthesizer → generator graph
|
||||||
|
→ output bus).
|
||||||
|
2. **Swift Basics & Best Practices** — `let`/`var`, the scalar types, optionals
|
||||||
|
(and why Lyrebird forbids force-unwrap `!`), control flow, functions, error
|
||||||
|
handling, and `struct` vs `class`.
|
||||||
|
3. **Types & Functional Programming** — enums, protocols, operator overloading,
|
||||||
|
closures, and `map`/`filter`/`reduce` applied to building synthesis graphs;
|
||||||
|
`expand` as `map` for multichannel generators.
|
||||||
|
4. **Xcode, Packages & Debugging** — Xcode vs. SwiftPM, adding Lyrebird as a
|
||||||
|
package, **Debug vs. Release** build configurations (and why Debug audio can
|
||||||
|
glitch), and breakpoints — including the rule to never break or `print` on
|
||||||
|
the real-time render thread, using `debugTap`/`debugTag` instead.
|
||||||
|
|
||||||
|
Throughout, examples use explicit **type annotations** on every binding — the
|
||||||
|
same practice the Lyrebird codebase enforces — for readability and faster
|
||||||
|
compilation on large, generic audio-graph expressions.
|
||||||
|
|
||||||
|
Linked from `README.md` and `LYREBIRD_START_HERE.md` for discovery.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.4.0 — Live-coding scratch editor, interpreted Graph DSL, `ClosureSynthesizer` + `SampleLoop`
|
||||||
|
|
||||||
|
A minor release. Fully backward-compatible — no changes to existing public API.
|
||||||
|
Adds a live-coding editor and an interpreted graph language on the tooling side,
|
||||||
|
two new core building blocks (`ClosureSynthesizer`, `SampleLoop`), and one
|
||||||
|
real-time correctness fix in the disk recorder.
|
||||||
|
|
||||||
|
### New — `ClosureSynthesizer`: play a graph without a subclass
|
||||||
|
|
||||||
|
The shortest path from a generator graph to sound. Instead of declaring a
|
||||||
|
`SynthesizerBase` subclass and overriding `build()`, hand a closure that returns
|
||||||
|
the output graph:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
try engine.add(ClosureSynthesizer { OscSin.Audio(freq: 440, mul: 0.1) })
|
||||||
|
try engine.add(ClosureSynthesizer(bus: 0) { Pan2(input: saw, pan: 0) })
|
||||||
|
```
|
||||||
|
|
||||||
|
The closure runs once, inside `build()`, on the main thread when the synth is
|
||||||
|
added — so each instance builds its own graph (the usual
|
||||||
|
graph-copy-per-instance rule). A multi-channel source fans out across
|
||||||
|
consecutive buses from `bus`, exactly as `output(bus:source:)` does. This is
|
||||||
|
also the primitive the scratch editor's "play a bare graph" and Graph DSL paths
|
||||||
|
build on.
|
||||||
|
|
||||||
|
### New — `SampleLoop`: inline per-sample DSP + single-sample feedback
|
||||||
|
|
||||||
|
The RT-safe escape hatch for custom sample-accurate DSP — including
|
||||||
|
**single-sample feedback loops** (one-pole filters, waveguides, comb/allpass
|
||||||
|
structures) — without declaring a whole new `Generator` type.
|
||||||
|
|
||||||
|
- **No per-block allocation.** `SampleLoop` owns its pre-allocated output buffer
|
||||||
|
(inherited `_result`) and resolves its inputs once per block via the fan-out
|
||||||
|
cache, then hands both to your closure to fill the whole block in one pass —
|
||||||
|
unlike `Closure`, which allocates a fresh `[Double]` and evaluates one sample
|
||||||
|
at a time.
|
||||||
|
- **Typed `inout` feedback state.** State is built by `makeState(numChannels)`
|
||||||
|
and passed `inout` to the body, so a filter can carry `y[n-1]` across samples
|
||||||
|
and blocks correctly.
|
||||||
|
- **Channel inference + broadcast.** Output width is inferred from the inputs
|
||||||
|
(`max` of their channel counts, or `1` with none); each input is broadcast up
|
||||||
|
to that width, so the same body scales to any channel count. Mismatched
|
||||||
|
multi-row inputs precondition-trap at construction, matching
|
||||||
|
`BinaryOpGenerator`'s policy.
|
||||||
|
|
||||||
|
### New — Live-coding scratch editor (`LyrebirdLiveCompile`, macOS)
|
||||||
|
|
||||||
|
An interactive scratch pad that compiles and plays Swift snippets against a
|
||||||
|
running engine, with hot-swap and safety scaffolding built in:
|
||||||
|
|
||||||
|
- **Bare-graph & subclass play** — `context.play { … }` for a graph,
|
||||||
|
`context.play(synth)` for a declared `Synthesizer`.
|
||||||
|
- **Named slots (Pdef-style hot-swap)** — re-running a `play(slot:)` replaces
|
||||||
|
just that voice in place; other slots keep playing. Swaps can quantize to the
|
||||||
|
next beat/bar for glitch-free, on-grid transitions.
|
||||||
|
- **Re-evaluation readiness** — a status badge (empty / dirty / compiling /
|
||||||
|
clean / queued / failed) gates the Run controls.
|
||||||
|
- **Syntax highlighting** and a line-number gutter.
|
||||||
|
- **Code completion** via the toolchain's `sourcekit-lsp`: typing `.` resolves
|
||||||
|
the real symbols the snippet would see at compile time — `LyrebirdSynth`
|
||||||
|
generators (`OscSin.` → `Audio`, `Control`), the injected `context`, and the
|
||||||
|
standard library.
|
||||||
|
- **Fast first sound** — the module cache is prewarmed at launch, so the first
|
||||||
|
⌘↩ is ~0.1 s instead of a ~2 s cold build.
|
||||||
|
- **Snippet-memory safety** — each compiled snippet maps a dylib that can't be
|
||||||
|
safely unloaded; the editor surfaces a live "snippets: N" count and nudges a
|
||||||
|
restart (or a switch to the leak-free Graph DSL mode) past a threshold.
|
||||||
|
|
||||||
|
### New — Interpreted Graph DSL (`LyrebirdGraphDSL`, cross-platform)
|
||||||
|
|
||||||
|
A small text→graph language that plays **instantly — no swiftc, no dylib, no
|
||||||
|
leak** — and is the structural answer to the snippet-dylib cost:
|
||||||
|
|
||||||
|
```
|
||||||
|
bass = OscSawtooth.Audio(freq: 55, mul: 0.15)
|
||||||
|
Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
- **304 built-in generators**, code-generated from generator init signatures, so
|
||||||
|
new generators appear automatically. Audio- and control-rate variants and
|
||||||
|
buffer resources are supported.
|
||||||
|
- **Paste-compatible** — the rate suffix is the exact Swift nested-class name
|
||||||
|
(`OscSin.Control`), so a graph expression written in the editor pastes into a
|
||||||
|
Lyrebird project unchanged.
|
||||||
|
- A mode toggle in the scratch editor runs the buffer through this path on the
|
||||||
|
same track/slot machinery as the Swift path, with errors in the same gutter.
|
||||||
|
|
||||||
|
### Fixed — `DiskOut` real-time data race
|
||||||
|
|
||||||
|
`DiskOut`'s ring buffer was a Swift `[[Float]]` shared between the real-time
|
||||||
|
render thread (writer) and its background disk-writer thread (reader). Even at
|
||||||
|
disjoint frame ranges, Swift `Array` access is not race-free — the subscript and
|
||||||
|
`withUnsafeMutableBufferPointer` touch the array's shared storage pointer and
|
||||||
|
copy-on-write / refcount bookkeeping, which the frame-counter atomics did not
|
||||||
|
fence. Under load this corrupted the heap (surfacing as retain-count aborts).
|
||||||
|
The ring is now backed by raw contiguous `UnsafeMutableBufferPointer<Float>`
|
||||||
|
storage, so the existing release/acquire frame-counter fence alone makes the
|
||||||
|
single-producer/single-consumer handoff correct. Confirmed with ThreadSanitizer;
|
||||||
|
also eliminated the long-standing parallel-`swift test` teardown crash.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 1.3.0 — Graceful-release fix, quickstart template, documentation accuracy pass
|
## 1.3.0 — Graceful-release fix, quickstart template, documentation accuracy pass
|
||||||
|
|
||||||
A minor release. Backward-compatible: one real-time behavior fix, one new
|
A minor release. Backward-compatible: one real-time behavior fix, one new
|
||||||
|
|||||||
@@ -7,11 +7,13 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import AudioToolbox
|
import AudioToolbox
|
||||||
|
|
||||||
/// Non-Real-Time audio driver. Renders synchronously to a CAF file.
|
/// Non-Real-Time audio driver. Renders synchronously to a soundfile in the
|
||||||
|
/// container/encoding chosen at init (``AudioFileFormat``, default `.cafFloat32`).
|
||||||
/// `start()` blocks until rendering is complete — suitable for score/script workflows.
|
/// `start()` blocks until rendering is complete — suitable for score/script workflows.
|
||||||
public final class NRTDriver: AudioDriver {
|
public final class NRTDriver: AudioDriver {
|
||||||
|
|
||||||
private let outputURL: URL
|
private let outputURL: URL
|
||||||
|
private let outputFormat: AudioFileFormat
|
||||||
private let duration: Double
|
private let duration: Double
|
||||||
|
|
||||||
// Optional soundfile fed into the engine as simulated hardware input.
|
// Optional soundfile fed into the engine as simulated hardware input.
|
||||||
@@ -38,8 +40,13 @@ public final class NRTDriver: AudioDriver {
|
|||||||
public var triggerListener: TriggerListener?
|
public var triggerListener: TriggerListener?
|
||||||
|
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - outputURL: Destination CAF file path.
|
/// - outputURL: Destination file path. The extension should match `format`
|
||||||
|
/// (`.caf` / `.wav` / `.aiff`); see ``AudioFileFormat/fileExtension``.
|
||||||
/// - duration: Render duration in seconds.
|
/// - duration: Render duration in seconds.
|
||||||
|
/// - format: Container and PCM encoding for the output file. Defaults to
|
||||||
|
/// `.cafFloat32`. CAF is 64-bit-sized (no 4 GB cap) and carries any channel
|
||||||
|
/// count, so it suits long or multichannel offline renders; `.wavFloat32` /
|
||||||
|
/// `.aiffFloat32` / the integer WAV cases are available for interchange.
|
||||||
/// - inputURL: Optional soundfile whose samples are written to the engine's input buses
|
/// - inputURL: Optional soundfile whose samples are written to the engine's input buses
|
||||||
/// each block, as if they came from a microphone. Channels are mapped in order starting
|
/// each block, as if they came from a microphone. Channels are mapped in order starting
|
||||||
/// at input bus 0. The engine's `numInputChannels` must be ≥ the file's channel count
|
/// at input bus 0. The engine's `numInputChannels` must be ≥ the file's channel count
|
||||||
@@ -50,11 +57,13 @@ public final class NRTDriver: AudioDriver {
|
|||||||
public init(
|
public init(
|
||||||
outputURL: URL,
|
outputURL: URL,
|
||||||
duration: Double,
|
duration: Double,
|
||||||
|
format: AudioFileFormat = .cafFloat32,
|
||||||
inputURL: URL? = nil,
|
inputURL: URL? = nil,
|
||||||
inputStartOffset: Double = 0.0
|
inputStartOffset: Double = 0.0
|
||||||
) {
|
) {
|
||||||
|
|
||||||
self.outputURL = outputURL
|
self.outputURL = outputURL
|
||||||
|
self.outputFormat = format
|
||||||
self.duration = duration
|
self.duration = duration
|
||||||
self.inputURL = inputURL
|
self.inputURL = inputURL
|
||||||
self.inputStartOffset = max(0.0, inputStartOffset)
|
self.inputStartOffset = max(0.0, inputStartOffset)
|
||||||
@@ -128,54 +137,112 @@ public final class NRTDriver: AudioDriver {
|
|||||||
count: inputChannelCount)
|
count: inputChannelCount)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Render synchronously to the output file.
|
||||||
|
///
|
||||||
|
/// - Throws: `NRTDriverError.invalidDuration` if `duration` is negative, NaN,
|
||||||
|
/// or infinite; `NRTDriverError.fileTooLargeForContainer` if a WAV/AIFF render
|
||||||
|
/// is projected past the 4 GB RIFF cap (use `.cafFloat32` for long renders);
|
||||||
|
/// or the file/IO error cases on create/write failure. For the `.rf64*`
|
||||||
|
/// formats, a ``RF64WriterError`` may surface instead of an `NRTDriverError`.
|
||||||
public func start() throws {
|
public func start() throws {
|
||||||
guard let engine: SynthesisEngine else { return }
|
guard let engine: SynthesisEngine else { return }
|
||||||
|
|
||||||
// Create and configure an ExtAudioFile for CAF / 32-bit float interleaved output
|
// Validate duration before any Double→Int conversion: Int(_:) traps on a
|
||||||
var fileRef: ExtAudioFileRef?
|
// non-finite or out-of-range value, and a negative duration would make the
|
||||||
var format: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
// render loop's `0..<totalBlocks` range crash. Throw instead.
|
||||||
mSampleRate: engine.sampleRate,
|
// The `< Double(Int.max)` bound also rejects a finite-but-astronomical
|
||||||
mFormatID: kAudioFormatLinearPCM,
|
// duration whose block count would overflow the `Int(_:)` conversion.
|
||||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
let blocksDouble: Double = (duration * engine.sampleRate / Double(engine.blockSize)).rounded(.up)
|
||||||
mBytesPerPacket: lyrebirdBytesPerSample * UInt32(engine.numOutputChannels),
|
guard duration.isFinite, duration >= 0, blocksDouble < Double(Int.max) else {
|
||||||
mFramesPerPacket: 1,
|
throw NRTDriverError.invalidDuration(duration)
|
||||||
mBytesPerFrame: lyrebirdBytesPerSample * UInt32(engine.numOutputChannels),
|
|
||||||
mChannelsPerFrame: UInt32(engine.numOutputChannels),
|
|
||||||
mBitsPerChannel: 32,
|
|
||||||
mReserved: 0
|
|
||||||
)
|
|
||||||
|
|
||||||
var status: OSStatus = ExtAudioFileCreateWithURL(
|
|
||||||
outputURL as CFURL,
|
|
||||||
kAudioFileCAFType,
|
|
||||||
&format,
|
|
||||||
nil,
|
|
||||||
AudioFileFlags.eraseFile.rawValue,
|
|
||||||
&fileRef
|
|
||||||
)
|
|
||||||
guard status == noErr, let fileRef: ExtAudioFileRef else {
|
|
||||||
throw NRTDriverError.cannotCreateFile(status)
|
|
||||||
}
|
}
|
||||||
// Guarantee disposal even if an error is thrown mid-render.
|
|
||||||
|
// Total render blocks — computed once and shared by the large-file guard and
|
||||||
|
// the render loop below, so the two can never drift out of sync.
|
||||||
|
let totalBlocks: Int = Int(blocksDouble)
|
||||||
|
|
||||||
|
// Large-file guard: reject a WAV/AIFF render projected past the 4 GB RIFF/AIFF
|
||||||
|
// cap before opening the file, so we never emit a truncated/corrupt output.
|
||||||
|
// CAF is exempt. `projectedByteCount` (inside riffOverflow) saturates on
|
||||||
|
// overflow, so a frame count near Int.max still yields the correct decision.
|
||||||
|
let (projectedFrames, framesOverflow): (Int, Bool) =
|
||||||
|
totalBlocks.multipliedReportingOverflow(by: engine.blockSize)
|
||||||
|
let effectiveFrames: Int = framesOverflow ? Int.max : projectedFrames
|
||||||
|
if let overflow: (projected: Int, cap: Int) = outputFormat.riffOverflow(
|
||||||
|
frameCount: effectiveFrames, channels: engine.numOutputChannels
|
||||||
|
) {
|
||||||
|
throw NRTDriverError.fileTooLargeForContainer(
|
||||||
|
projectedBytes: overflow.projected, cap: overflow.cap
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dispose the input file regardless of which output backend construction (or
|
||||||
|
// the render) throws below — registered before backend selection so an early
|
||||||
|
// throw can't leak it.
|
||||||
defer {
|
defer {
|
||||||
ExtAudioFileDispose(fileRef)
|
|
||||||
if let ref: ExtAudioFileRef = inputFileRef { ExtAudioFileDispose(ref) }
|
if let ref: ExtAudioFileRef = inputFileRef { ExtAudioFileDispose(ref) }
|
||||||
inputFileRef = nil
|
inputFileRef = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set client format (same as file format — already float32 interleaved)
|
// Choose the output backend: RF64Writer (hand-rolled 64-bit WAV) for the RF64
|
||||||
status = ExtAudioFileSetProperty(
|
// cases, else ExtAudioFile for CAF / WAV / AIFF. The engine renders Float32, so
|
||||||
fileRef,
|
// both back-ends receive native Float32 interleaved samples.
|
||||||
kExtAudioFileProperty_ClientDataFormat,
|
let rf64Writer: RF64Writer? = outputFormat.usesRF64Writer
|
||||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
? try RF64Writer(url: outputURL, format: outputFormat,
|
||||||
&format
|
sampleRate: engine.sampleRate, channels: engine.numOutputChannels)
|
||||||
)
|
: nil
|
||||||
guard status == noErr else {
|
|
||||||
throw NRTDriverError.cannotSetFormat(status)
|
var extFileRef: ExtAudioFileRef? = nil
|
||||||
|
if rf64Writer == nil {
|
||||||
|
var fileFormat: AudioStreamBasicDescription = outputFormat.makeFileASBD(
|
||||||
|
sampleRate: engine.sampleRate,
|
||||||
|
channels: engine.numOutputChannels
|
||||||
|
)
|
||||||
|
var createdRef: ExtAudioFileRef?
|
||||||
|
var status: OSStatus = ExtAudioFileCreateWithURL(
|
||||||
|
outputURL as CFURL,
|
||||||
|
outputFormat.audioFileTypeID,
|
||||||
|
&fileFormat,
|
||||||
|
nil,
|
||||||
|
AudioFileFlags.eraseFile.rawValue,
|
||||||
|
&createdRef
|
||||||
|
)
|
||||||
|
guard status == noErr, let createdRef: ExtAudioFileRef else {
|
||||||
|
throw NRTDriverError.cannotCreateFile(status)
|
||||||
|
}
|
||||||
|
// Client format: always native Float32 interleaved. ExtAudioFile converts
|
||||||
|
// Float32 → int16/int24 on write for the integer WAV formats.
|
||||||
|
var clientFormat: AudioStreamBasicDescription = outputFormat.makeClientASBD(
|
||||||
|
sampleRate: engine.sampleRate,
|
||||||
|
channels: engine.numOutputChannels
|
||||||
|
)
|
||||||
|
status = ExtAudioFileSetProperty(
|
||||||
|
createdRef,
|
||||||
|
kExtAudioFileProperty_ClientDataFormat,
|
||||||
|
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
||||||
|
&clientFormat
|
||||||
|
)
|
||||||
|
guard status == noErr else {
|
||||||
|
ExtAudioFileDispose(createdRef)
|
||||||
|
throw NRTDriverError.cannotSetFormat(status)
|
||||||
|
}
|
||||||
|
// Compressed (AAC) formats: push the target bitrate into the encoder.
|
||||||
|
let encoderStatus: OSStatus = outputFormat.applyEncoderConfig(to: createdRef)
|
||||||
|
guard encoderStatus == noErr else {
|
||||||
|
ExtAudioFileDispose(createdRef)
|
||||||
|
throw NRTDriverError.cannotSetFormat(encoderStatus)
|
||||||
|
}
|
||||||
|
extFileRef = createdRef
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render loop — synchronous, no RT constraints
|
// Guarantee disposal even if an error is thrown mid-render.
|
||||||
let totalBlocks: Int = Int(ceil(duration * engine.sampleRate / Double(engine.blockSize)))
|
defer {
|
||||||
|
if let ref: ExtAudioFileRef = extFileRef { ExtAudioFileDispose(ref) }
|
||||||
|
try? rf64Writer?.close() // idempotent; explicit close below patches ds64 sizes
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render loop — synchronous, no RT constraints. `totalBlocks` was computed
|
||||||
|
// once above (shared with the large-file guard).
|
||||||
let bs: Int = engine.blockSize
|
let bs: Int = engine.blockSize
|
||||||
let nch: Int = engine.numOutputChannels
|
let nch: Int = engine.numOutputChannels
|
||||||
|
|
||||||
@@ -222,25 +289,35 @@ public final class NRTDriver: AudioDriver {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write interleaved block to file — check status; a failure means a corrupt
|
// Write interleaved block to file — a failure means a corrupt or truncated
|
||||||
// or truncated file, so we throw rather than silently swallow the error.
|
// file, so we throw rather than silently swallow the error.
|
||||||
let writeStatus: OSStatus = writeBuffer.withUnsafeMutableBufferPointer { ptr in
|
if let rf64Writer: RF64Writer {
|
||||||
let frameCount: UInt32 = UInt32(bs)
|
try writeBuffer.withUnsafeBufferPointer { ptr in
|
||||||
var bufList: AudioBufferList = AudioBufferList(
|
try rf64Writer.writeFloat32Interleaved(ptr, frames: bs)
|
||||||
mNumberBuffers: 1,
|
}
|
||||||
mBuffers: AudioBuffer(
|
} else if let extFileRef: ExtAudioFileRef {
|
||||||
mNumberChannels: UInt32(nch),
|
let writeStatus: OSStatus = writeBuffer.withUnsafeMutableBufferPointer { ptr in
|
||||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
let frameCount: UInt32 = UInt32(bs)
|
||||||
mData: ptr.baseAddress
|
var bufList: AudioBufferList = AudioBufferList(
|
||||||
|
mNumberBuffers: 1,
|
||||||
|
mBuffers: AudioBuffer(
|
||||||
|
mNumberChannels: UInt32(nch),
|
||||||
|
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||||
|
mData: ptr.baseAddress
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
return ExtAudioFileWrite(extFileRef, frameCount, &bufList)
|
||||||
return ExtAudioFileWrite(fileRef, frameCount, &bufList)
|
}
|
||||||
}
|
guard writeStatus == noErr else {
|
||||||
guard writeStatus == noErr else {
|
throw NRTDriverError.writeFailed(writeStatus)
|
||||||
throw NRTDriverError.writeFailed(writeStatus)
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Patch the RF64 ds64 sizes now (idempotent with the defer) so the file is
|
||||||
|
// finalised before this method returns.
|
||||||
|
try rf64Writer?.close()
|
||||||
|
|
||||||
// Synchronous render is done and the freeWorker timer only starts after this
|
// Synchronous render is done and the freeWorker timer only starts after this
|
||||||
// returns — emit any per-block event-drop warning here so it reaches the console
|
// returns — emit any per-block event-drop warning here so it reaches the console
|
||||||
// even if the process exits before that timer (or `stop()`) runs.
|
// even if the process exits before that timer (or `stop()`) runs.
|
||||||
@@ -267,4 +344,11 @@ public enum NRTDriverError: Error {
|
|||||||
case cannotSetInputClientFormat(OSStatus)
|
case cannotSetInputClientFormat(OSStatus)
|
||||||
case cannotSeekInputFile(OSStatus)
|
case cannotSeekInputFile(OSStatus)
|
||||||
case inputReadFailed(OSStatus)
|
case inputReadFailed(OSStatus)
|
||||||
|
/// `duration` was negative, NaN, or infinite. Pass a finite, non-negative value.
|
||||||
|
case invalidDuration(Double)
|
||||||
|
/// The render is projected to exceed the output container's 4 GB (32-bit size
|
||||||
|
/// field) limit. Only WAV/AIFF are capped; CAF is exempt. `projectedBytes` is
|
||||||
|
/// the estimated audio-data size, `cap` is `lyrebirdMaxRIFFBytes`. Re-run with
|
||||||
|
/// `format: .cafFloat32` (64-bit sizes, uncapped) or shorten the duration.
|
||||||
|
case fileTooLargeForContainer(projectedBytes: Int, cap: Int)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,361 @@
|
|||||||
|
// AudioFileFormat.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import AudioToolbox
|
||||||
|
|
||||||
|
/// Container-and-encoding format shared by every Lyrebird soundfile writer:
|
||||||
|
/// ``LyrebirdBuffer/write(to:format:sampleRate:)`` (offline buffer dump),
|
||||||
|
/// ``DiskOut/Audio`` (real-time streaming recorder), and the NRT driver
|
||||||
|
/// (offline score render).
|
||||||
|
///
|
||||||
|
/// Each case pins both the container (WAV / AIFF-C / CAF) and the PCM sample
|
||||||
|
/// encoding (Float32, or signed-integer 16/24-bit). Writers always hand
|
||||||
|
/// `ExtAudioFile` native-Float32 samples as the *client* format (see
|
||||||
|
/// `makeClientASBD(sampleRate:channels:)`) and let it convert to the *file*
|
||||||
|
/// format (`makeFileASBD(sampleRate:channels:)`) — so integer encodings cost
|
||||||
|
/// the caller nothing beyond selecting the case.
|
||||||
|
///
|
||||||
|
/// ## Container notes
|
||||||
|
/// - **WAV** — little-endian, cross-platform standard. Supports Float32 and
|
||||||
|
/// signed-integer PCM. Classic RIFF caps total file size at 4 GB (32-bit size
|
||||||
|
/// fields); large renders should fall back to `.cafFloat32`.
|
||||||
|
/// - **AIFF-C** (`.aiffFloat32`) — big-endian by spec. Uses `kAudioFileAIFCType`
|
||||||
|
/// (not classic `kAudioFileAIFFType`, which is integer-only) so it can carry
|
||||||
|
/// Float32 while keeping the `.aiff` extension. Best restricted to ≤ 2 channels
|
||||||
|
/// for compatibility with legacy readers; also 4 GB-capped.
|
||||||
|
/// - **CAF** (`.cafFloat32`) — Apple's flexible container: any sample rate, any
|
||||||
|
/// channel count up to `lyrebirdMaxFileChannelCount`, 64-bit sizes (no 4 GB
|
||||||
|
/// cap). Default for buffer and NRT writes.
|
||||||
|
public enum AudioFileFormat: Sendable {
|
||||||
|
|
||||||
|
// MARK: - WAV variants
|
||||||
|
|
||||||
|
/// WAV container, 32-bit IEEE-754 float, little-endian.
|
||||||
|
case wavFloat32
|
||||||
|
/// WAV container, 16-bit signed integer, little-endian.
|
||||||
|
case wavInt16
|
||||||
|
/// WAV container, 24-bit signed integer (packed), little-endian.
|
||||||
|
case wavInt24
|
||||||
|
|
||||||
|
// MARK: - AIFF-C variants
|
||||||
|
|
||||||
|
/// AIFF-C container, 32-bit IEEE-754 float, big-endian.
|
||||||
|
case aiffFloat32
|
||||||
|
|
||||||
|
// MARK: - CAF variants
|
||||||
|
|
||||||
|
/// CAF container, 32-bit IEEE-754 float, little-endian.
|
||||||
|
case cafFloat32
|
||||||
|
|
||||||
|
// MARK: - RF64 / BW64 variants (64-bit-sized WAV, no 4 GB cap)
|
||||||
|
|
||||||
|
/// RF64 (BW64) container, 32-bit IEEE-754 float, little-endian. WAV extension.
|
||||||
|
/// Emitted by ``RF64Writer`` (not `ExtAudioFile`); readable by CoreAudio.
|
||||||
|
case rf64Float32
|
||||||
|
/// RF64 (BW64) container, 24-bit signed integer (packed), little-endian.
|
||||||
|
case rf64Int24
|
||||||
|
|
||||||
|
// MARK: - Compressed variants (M4A container — offline writers only)
|
||||||
|
|
||||||
|
/// AAC in an M4A container, ~256 kbps. Lossy; **not sample-accurate** (encoder
|
||||||
|
/// priming/padding). Encoded by `ExtAudioFile`/`AudioConverter`. Offline writers
|
||||||
|
/// only (`LyrebirdBuffer.write`, `NRTDriver`); ``DiskOut/Audio`` rejects it.
|
||||||
|
case aacHigh
|
||||||
|
/// AAC in an M4A container, ~128 kbps. See ``aacHigh``.
|
||||||
|
case aacMedium
|
||||||
|
/// Apple Lossless (ALAC) in an M4A container, 24-bit source. Lossless of the
|
||||||
|
/// 24-bit-quantised signal. Offline writers only; ``DiskOut/Audio`` rejects it.
|
||||||
|
case alac
|
||||||
|
|
||||||
|
// MARK: - Back-compat shorthands
|
||||||
|
|
||||||
|
/// WAV / Float32. Alias for ``wavFloat32``.
|
||||||
|
public static let wav: AudioFileFormat = .wavFloat32
|
||||||
|
/// AIFF-C / Float32. Alias for ``aiffFloat32``.
|
||||||
|
public static let aiff: AudioFileFormat = .aiffFloat32
|
||||||
|
/// CAF / Float32. Alias for ``cafFloat32``.
|
||||||
|
public static let caf: AudioFileFormat = .cafFloat32
|
||||||
|
|
||||||
|
// MARK: - Derived properties
|
||||||
|
|
||||||
|
/// AudioToolbox container type ID passed to `ExtAudioFileCreateWithURL`.
|
||||||
|
///
|
||||||
|
/// Not meaningful for the RF64 cases (they are written by ``RF64Writer``, not
|
||||||
|
/// `ExtAudioFile`); those return `kAudioFileWAVEType` as an inert default.
|
||||||
|
public var audioFileTypeID: AudioFileTypeID {
|
||||||
|
switch self {
|
||||||
|
case .wavFloat32, .wavInt16, .wavInt24, .rf64Float32, .rf64Int24:
|
||||||
|
return kAudioFileWAVEType
|
||||||
|
case .aiffFloat32:
|
||||||
|
return kAudioFileAIFCType // AIFF-C: carries Float32; classic AIFF does not
|
||||||
|
case .cafFloat32:
|
||||||
|
return kAudioFileCAFType
|
||||||
|
case .aacHigh, .aacMedium, .alac:
|
||||||
|
return kAudioFileM4AType
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Filesystem extension for the output file (no leading dot).
|
||||||
|
public var fileExtension: String {
|
||||||
|
switch self {
|
||||||
|
case .wavFloat32, .wavInt16, .wavInt24, .rf64Float32, .rf64Int24: return "wav"
|
||||||
|
case .aiffFloat32: return "aiff"
|
||||||
|
case .cafFloat32: return "caf"
|
||||||
|
case .aacHigh, .aacMedium, .alac: return "m4a"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bits per sample in the *PCM* encoded file. Not meaningful for the compressed
|
||||||
|
/// cases (they carry no fixed per-sample bit width); returns `0` there.
|
||||||
|
public var fileBitsPerChannel: UInt32 {
|
||||||
|
switch self {
|
||||||
|
case .wavFloat32, .aiffFloat32, .cafFloat32, .rf64Float32: return 32
|
||||||
|
case .wavInt16: return 16
|
||||||
|
case .wavInt24, .rf64Int24: return 24
|
||||||
|
case .aacHigh, .aacMedium, .alac: return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `true` when the file encoding is IEEE-754 float; `false` for signed-integer PCM
|
||||||
|
/// or a compressed codec.
|
||||||
|
public var isFloatEncoding: Bool {
|
||||||
|
switch self {
|
||||||
|
case .wavFloat32, .aiffFloat32, .cafFloat32, .rf64Float32: return true
|
||||||
|
case .wavInt16, .wavInt24, .rf64Int24, .aacHigh, .aacMedium, .alac: return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `true` when the container stores big-endian sample data (AIFF-C spec).
|
||||||
|
public var isBigEndian: Bool {
|
||||||
|
switch self {
|
||||||
|
case .aiffFloat32:
|
||||||
|
return true
|
||||||
|
case .wavFloat32, .wavInt16, .wavInt24, .cafFloat32, .rf64Float32, .rf64Int24,
|
||||||
|
.aacHigh, .aacMedium, .alac:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `true` for the compressed codecs (AAC, ALAC) — encoded by
|
||||||
|
/// `ExtAudioFile`/`AudioConverter` into an M4A container.
|
||||||
|
public var isCompressed: Bool {
|
||||||
|
switch self {
|
||||||
|
case .aacHigh, .aacMedium, .alac:
|
||||||
|
return true
|
||||||
|
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32,
|
||||||
|
.rf64Float32, .rf64Int24:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Target AAC encode bitrate in bits/second, or `nil` for non-AAC formats.
|
||||||
|
public var aacBitrate: Int? {
|
||||||
|
switch self {
|
||||||
|
case .aacHigh: return aacHighBitrate
|
||||||
|
case .aacMedium: return aacMediumBitrate
|
||||||
|
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32,
|
||||||
|
.rf64Float32, .rf64Int24, .alac:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `true` when the container can address files larger than 4 GB.
|
||||||
|
///
|
||||||
|
/// WAV (classic RIFF) and AIFF-C carry unsigned **32-bit** size fields, so
|
||||||
|
/// their total file size is capped at 4 GB (see `lyrebirdMaxRIFFBytes`). CAF
|
||||||
|
/// (64-bit sizes) and RF64/BW64 (64-bit sizes via the `ds64` chunk) have no such
|
||||||
|
/// cap. `ExtAudioFile` cannot emit RF64, so those cases are written by
|
||||||
|
/// ``RF64Writer`` — see ``usesRF64Writer``.
|
||||||
|
public var supportsLargeFiles: Bool {
|
||||||
|
switch self {
|
||||||
|
// CAF/RF64 are 64-bit-sized; the compressed M4A cases are not RIFF at all,
|
||||||
|
// so the 4 GB RIFF/AIFF guard never applies to them either.
|
||||||
|
case .cafFloat32, .rf64Float32, .rf64Int24, .aacHigh, .aacMedium, .alac:
|
||||||
|
return true
|
||||||
|
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `true` when this format is emitted by ``RF64Writer`` (hand-rolled 64-bit WAV)
|
||||||
|
/// rather than `ExtAudioFile`. The three soundfile writers branch on this.
|
||||||
|
public var usesRF64Writer: Bool {
|
||||||
|
switch self {
|
||||||
|
case .rf64Float32, .rf64Int24:
|
||||||
|
return true
|
||||||
|
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32,
|
||||||
|
.aacHigh, .aacMedium, .alac:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Large-file guard
|
||||||
|
|
||||||
|
extension AudioFileFormat {
|
||||||
|
|
||||||
|
/// Projected on-disk audio-data size in bytes for `frameCount` interleaved
|
||||||
|
/// frames across `channels`, at this format's bit depth. Excludes container
|
||||||
|
/// header/metadata (accounted for by the slack baked into `lyrebirdMaxRIFFBytes`).
|
||||||
|
///
|
||||||
|
/// Pure integer arithmetic — safe to evaluate for hypothetical sizes without
|
||||||
|
/// allocating anything. **Saturates to `Int.max` on overflow** rather than
|
||||||
|
/// trapping: any frame count large enough to overflow the byte product is, by
|
||||||
|
/// definition, far past any container cap, so a saturated value gives the guard
|
||||||
|
/// the correct "over cap" answer without a crash.
|
||||||
|
func projectedByteCount(frameCount: Int, channels: Int) -> Int {
|
||||||
|
let bytesPerSample: Int = Int(fileBitsPerChannel / bitsPerByte)
|
||||||
|
let (samples, sampleOverflow): (Int, Bool) = frameCount.multipliedReportingOverflow(by: channels)
|
||||||
|
if sampleOverflow { return Int.max }
|
||||||
|
let (bytes, byteOverflow): (Int, Bool) = samples.multipliedReportingOverflow(by: bytesPerSample)
|
||||||
|
return byteOverflow ? Int.max : bytes
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns `(projected, cap)` when writing `frameCount × channels` frames in
|
||||||
|
/// this format would overflow the container's addressable size, or `nil` when
|
||||||
|
/// the write fits (or the container is 64-bit — see ``supportsLargeFiles``).
|
||||||
|
///
|
||||||
|
/// The single decision point behind both the `LyrebirdBuffer.write` and
|
||||||
|
/// `NRTDriver` large-file guards, so the guard reads off the format rather
|
||||||
|
/// than a hardcoded case list.
|
||||||
|
func riffOverflow(frameCount: Int, channels: Int) -> (projected: Int, cap: Int)? {
|
||||||
|
guard !supportsLargeFiles else { return nil }
|
||||||
|
let projected: Int = projectedByteCount(frameCount: frameCount, channels: channels)
|
||||||
|
return projected > lyrebirdMaxRIFFBytes ? (projected, lyrebirdMaxRIFFBytes) : nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - ASBD factories (module-internal)
|
||||||
|
|
||||||
|
/// Number of bits in a byte — names the `/ 8` in bytes-per-sample derivations.
|
||||||
|
private let bitsPerByte: UInt32 = 8
|
||||||
|
|
||||||
|
/// Encoder packet geometry (samples per packet) for the compressed codecs.
|
||||||
|
private let aacFramesPerPacket: UInt32 = 1024
|
||||||
|
private let alacFramesPerPacket: UInt32 = 4096
|
||||||
|
|
||||||
|
/// AAC target bitrates (bits/second) for the two quality tiers.
|
||||||
|
private let aacHighBitrate: Int = 256_000
|
||||||
|
private let aacMediumBitrate: Int = 128_000
|
||||||
|
|
||||||
|
extension AudioFileFormat {
|
||||||
|
|
||||||
|
/// Build the *file* `AudioStreamBasicDescription` for this format: linear PCM
|
||||||
|
/// with the case's bit depth, encoding flags, and endianness, interleaved
|
||||||
|
/// across `channels`.
|
||||||
|
///
|
||||||
|
/// This is the descriptor handed to `ExtAudioFileCreateWithURL`. Pair it with
|
||||||
|
/// `makeClientASBD(sampleRate:channels:)` as the client format so
|
||||||
|
/// `ExtAudioFile` performs any Float32 → integer / endian conversion.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - sampleRate: Sample rate embedded in the file header, in Hz.
|
||||||
|
/// - channels: Interleaved channel count. Must be ≥ 1.
|
||||||
|
func makeFileASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription {
|
||||||
|
// Compressed codecs (AAC / ALAC): the encoder fills in the packet geometry.
|
||||||
|
// We supply the format ID, channel count, sample rate, and frames-per-packet;
|
||||||
|
// `AudioConverter` (behind `ExtAudioFile`) computes the rest.
|
||||||
|
if isCompressed {
|
||||||
|
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||||
|
asbd.mSampleRate = sampleRate
|
||||||
|
asbd.mChannelsPerFrame = UInt32(channels)
|
||||||
|
// AAC vs ALAC: the AAC tiers carry a bitrate, ALAC does not. Deriving the
|
||||||
|
// codec from `aacBitrate` avoids a `switch self` with an unreachable
|
||||||
|
// default that could silently leave `mFormatID == 0` for a future case.
|
||||||
|
if aacBitrate != nil {
|
||||||
|
asbd.mFormatID = kAudioFormatMPEG4AAC
|
||||||
|
asbd.mFramesPerPacket = aacFramesPerPacket
|
||||||
|
} else {
|
||||||
|
asbd.mFormatID = kAudioFormatAppleLossless
|
||||||
|
asbd.mFramesPerPacket = alacFramesPerPacket
|
||||||
|
asbd.mFormatFlags = kAppleLosslessFormatFlag_24BitSourceData
|
||||||
|
}
|
||||||
|
return asbd
|
||||||
|
}
|
||||||
|
|
||||||
|
let bytesPerSample: UInt32 = fileBitsPerChannel / bitsPerByte
|
||||||
|
let bytesPerFrame: UInt32 = bytesPerSample * UInt32(channels)
|
||||||
|
|
||||||
|
var flags: AudioFormatFlags = kAudioFormatFlagIsPacked
|
||||||
|
flags |= isFloatEncoding ? kAudioFormatFlagIsFloat : kAudioFormatFlagIsSignedInteger
|
||||||
|
if isBigEndian { flags |= kAudioFormatFlagIsBigEndian }
|
||||||
|
|
||||||
|
return AudioStreamBasicDescription(
|
||||||
|
mSampleRate: sampleRate,
|
||||||
|
mFormatID: kAudioFormatLinearPCM,
|
||||||
|
mFormatFlags: flags,
|
||||||
|
mBytesPerPacket: bytesPerFrame,
|
||||||
|
mFramesPerPacket: 1,
|
||||||
|
mBytesPerFrame: bytesPerFrame,
|
||||||
|
mChannelsPerFrame: UInt32(channels),
|
||||||
|
mBitsPerChannel: fileBitsPerChannel,
|
||||||
|
mReserved: 0
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build the *client* `AudioStreamBasicDescription`: always native-endian
|
||||||
|
/// Float32 interleaved across `channels`, independent of the file encoding.
|
||||||
|
///
|
||||||
|
/// Every Lyrebird writer feeds `ExtAudioFile` Float32 samples; the file format
|
||||||
|
/// (from `makeFileASBD(sampleRate:channels:)`) drives the conversion.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - sampleRate: Sample rate, in Hz. Should match the file ASBD.
|
||||||
|
/// - channels: Interleaved channel count. Must be ≥ 1.
|
||||||
|
func makeClientASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription {
|
||||||
|
let bytesPerFrame: UInt32 = lyrebirdBytesPerSample * UInt32(channels)
|
||||||
|
return AudioStreamBasicDescription(
|
||||||
|
mSampleRate: sampleRate,
|
||||||
|
mFormatID: kAudioFormatLinearPCM,
|
||||||
|
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||||
|
mBytesPerPacket: bytesPerFrame,
|
||||||
|
mFramesPerPacket: 1,
|
||||||
|
mBytesPerFrame: bytesPerFrame,
|
||||||
|
mChannelsPerFrame: UInt32(channels),
|
||||||
|
mBitsPerChannel: lyrebirdBitsPerSample,
|
||||||
|
mReserved: 0
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Compressed encoder configuration
|
||||||
|
|
||||||
|
extension AudioFileFormat {
|
||||||
|
|
||||||
|
/// After an `ExtAudioFile` for a compressed format has been created and its client
|
||||||
|
/// (Float32) format set, push the target AAC bitrate into the underlying
|
||||||
|
/// `AudioConverter`. No-op for non-AAC formats (ALAC has no bitrate; PCM has none).
|
||||||
|
///
|
||||||
|
/// Returns `noErr` on success (or when nothing needed doing), else the failing
|
||||||
|
/// `OSStatus`. Call from a non-RT thread, before the first `ExtAudioFileWrite`.
|
||||||
|
func applyEncoderConfig(to fileRef: ExtAudioFileRef) -> OSStatus {
|
||||||
|
guard let bitrate: Int = aacBitrate else { return noErr }
|
||||||
|
|
||||||
|
var converter: AudioConverterRef?
|
||||||
|
var converterSize: UInt32 = UInt32(MemoryLayout<AudioConverterRef?>.size)
|
||||||
|
let getStatus: OSStatus = ExtAudioFileGetProperty(
|
||||||
|
fileRef, kExtAudioFileProperty_AudioConverter, &converterSize, &converter
|
||||||
|
)
|
||||||
|
guard getStatus == noErr, let converter: AudioConverterRef else { return getStatus }
|
||||||
|
|
||||||
|
var rate: UInt32 = UInt32(bitrate)
|
||||||
|
let setStatus: OSStatus = AudioConverterSetProperty(
|
||||||
|
converter, kAudioConverterEncodeBitRate, UInt32(MemoryLayout<UInt32>.size), &rate
|
||||||
|
)
|
||||||
|
guard setStatus == noErr else { return setStatus }
|
||||||
|
|
||||||
|
// Notify ExtAudioFile that the converter config changed so it re-reads it.
|
||||||
|
// The property value is a `CFPropertyList?` = NULL; pass a pointer to a nil
|
||||||
|
// variable (NOT a null data pointer — CoreAudio dereferences the pointer).
|
||||||
|
var config: CFPropertyList? = nil
|
||||||
|
return withUnsafePointer(to: &config) { ptr in
|
||||||
|
ExtAudioFileSetProperty(
|
||||||
|
fileRef, kExtAudioFileProperty_ConverterConfig,
|
||||||
|
UInt32(MemoryLayout<CFPropertyList?>.size), ptr
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,44 +7,6 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import AudioToolbox
|
import AudioToolbox
|
||||||
|
|
||||||
// MARK: - AudioFileFormat
|
|
||||||
|
|
||||||
/// Container format for `LyrebirdBuffer.write(to:format:sampleRate:)`.
|
|
||||||
public enum AudioFileFormat {
|
|
||||||
/// AIFF-C container (`.aiff`) — lossless Float32, big-endian. Common on macOS.
|
|
||||||
///
|
|
||||||
/// Uses `kAudioFileAIFCType` (AIFF-C), not classic `kAudioFileAIFFType`. Classic AIFF
|
|
||||||
/// supports only integer PCM; AIFF-C adds float and other sample types while retaining
|
|
||||||
/// the same `.aiff` file extension and broad macOS/iOS compatibility.
|
|
||||||
///
|
|
||||||
/// Note: AIFF-C has practical interoperability limits beyond 2 channels. For
|
|
||||||
/// multichannel (3–8 ch) output, prefer `.caf` or `.wav`.
|
|
||||||
case aiff
|
|
||||||
/// WAV container (`.wav`) — lossless Float32, little-endian. Cross-platform standard.
|
|
||||||
/// Supports up to `lyrebirdMaxFileChannelCount` channels via WAVE_FORMAT_EXTENSIBLE.
|
|
||||||
case wav
|
|
||||||
/// Core Audio Format (`.caf`) — Apple's flexible container; supports any sample rate
|
|
||||||
/// and any channel count up to `lyrebirdMaxFileChannelCount`. Default for writes.
|
|
||||||
case caf
|
|
||||||
|
|
||||||
fileprivate var audioFileTypeID: AudioFileTypeID {
|
|
||||||
switch self {
|
|
||||||
case .aiff: return kAudioFileAIFCType // AIFF-C: supports Float32 (classic AIFF does not)
|
|
||||||
case .wav: return kAudioFileWAVEType
|
|
||||||
case .caf: return kAudioFileCAFType
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the container requires big-endian sample data in the file format descriptor.
|
|
||||||
/// AIFF-C is big-endian by spec; WAV and CAF use native/little-endian.
|
|
||||||
fileprivate var requiresBigEndian: Bool {
|
|
||||||
switch self {
|
|
||||||
case .aiff: return true
|
|
||||||
case .wav, .caf: return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - LyrebirdBufferIOError
|
// MARK: - LyrebirdBufferIOError
|
||||||
|
|
||||||
/// Errors thrown by `LyrebirdBuffer` file I/O methods.
|
/// Errors thrown by `LyrebirdBuffer` file I/O methods.
|
||||||
@@ -70,6 +32,11 @@ public enum LyrebirdBufferIOError: Error, Equatable {
|
|||||||
case cannotSetOutputFormat(OSStatus)
|
case cannotSetOutputFormat(OSStatus)
|
||||||
/// `ExtAudioFileWrite` returned a non-zero status.
|
/// `ExtAudioFileWrite` returned a non-zero status.
|
||||||
case writeFailed(OSStatus)
|
case writeFailed(OSStatus)
|
||||||
|
/// The requested WAV/AIFF write is projected to exceed the container's 4 GB
|
||||||
|
/// (32-bit size field) limit. `projectedBytes` is the estimated audio-data
|
||||||
|
/// size; `cap` is `lyrebirdMaxRIFFBytes`. Re-issue the write with `.cafFloat32`
|
||||||
|
/// (64-bit sizes, uncapped), shorten the buffer, or split it.
|
||||||
|
case fileTooLargeForContainer(projectedBytes: Int, cap: Int)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Constants
|
// MARK: - Constants
|
||||||
@@ -251,18 +218,27 @@ public extension LyrebirdBuffer {
|
|||||||
|
|
||||||
/// Write the buffer's contents to an audio file.
|
/// Write the buffer's contents to an audio file.
|
||||||
///
|
///
|
||||||
/// Supports any `channelCount` in `[1, lyrebirdMaxFileChannelCount]`. The file will
|
/// Supports any `channelCount` in `[1, lyrebirdMaxFileChannelCount]` and any
|
||||||
/// contain interleaved Float32 samples at the specified sample rate. For multichannel
|
/// ``AudioFileFormat`` case. The buffer's `Double` samples are handed to the
|
||||||
/// buffers, `.caf` or `.wav` are recommended; `.aiff` (AIFF-C) is best limited to
|
/// writer as native Float32; the container's on-disk encoding (Float32, or
|
||||||
/// stereo for maximum compatibility with external readers.
|
/// signed-integer 16/24-bit for the WAV cases) is produced by its conversion.
|
||||||
///
|
/// Most formats go through `ExtAudioFile`; the RF64 cases (`.rf64Float32` /
|
||||||
/// Converts `Double` (Double) samples to Float32 on the way out.
|
/// `.rf64Int24`) are written by ``RF64Writer`` instead, since `ExtAudioFile`
|
||||||
|
/// cannot emit RF64. For multichannel buffers, `.cafFloat32` or `.wavFloat32` are
|
||||||
|
/// recommended; `.aiffFloat32` (AIFF-C) is best limited to stereo for maximum
|
||||||
|
/// compatibility with external readers. `.wavFloat32` / `.wavInt16` / `.wavInt24`
|
||||||
|
/// / `.aiffFloat32` throw ``LyrebirdBufferIOError/fileTooLargeForContainer(projectedBytes:cap:)``
|
||||||
|
/// past 4 GB — use `.rf64*` or `.cafFloat32` for larger files.
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - url: Destination file. Any existing file at this path is overwritten.
|
/// - url: Destination file. Any existing file at this path is overwritten.
|
||||||
/// - format: Container format. Defaults to `.caf`.
|
/// - format: Container and PCM encoding. Defaults to `.cafFloat32`.
|
||||||
/// - sampleRate: Sample rate embedded in the file header. Defaults to 44100.
|
/// - sampleRate: Sample rate embedded in the file header. Defaults to 44100.
|
||||||
///
|
///
|
||||||
|
/// - Throws: ``LyrebirdBufferIOError`` (`.fileTooLargeForContainer` when a
|
||||||
|
/// WAV/AIFF write is projected past 4 GB, or the create/write cases on I/O
|
||||||
|
/// failure). For the `.rf64*` formats, a ``RF64WriterError`` may surface instead.
|
||||||
|
///
|
||||||
/// **Not RT-safe.** Must be called from a non-RT thread (main thread or background queue).
|
/// **Not RT-safe.** Must be called from a non-RT thread (main thread or background queue).
|
||||||
///
|
///
|
||||||
/// For session-end dumps from a ``LyrebirdEventList`` teardown, see the
|
/// For session-end dumps from a ``LyrebirdEventList`` teardown, see the
|
||||||
@@ -282,39 +258,50 @@ public extension LyrebirdBuffer {
|
|||||||
+ "lyrebirdMaxFileChannelCount (\(lyrebirdMaxFileChannelCount))"
|
+ "lyrebirdMaxFileChannelCount (\(lyrebirdMaxFileChannelCount))"
|
||||||
)
|
)
|
||||||
|
|
||||||
let bytesPerSample: UInt32 = lyrebirdFileIOBitsPerSample / 8 // 4 bytes for Float32
|
// Large-file guard: WAV/AIFF are 4 GB-capped (32-bit size fields). Reject a
|
||||||
let bytesPerFrame: UInt32 = bytesPerSample * UInt32(channelCount)
|
// write that would overflow rather than emit a truncated/corrupt file. CAF
|
||||||
|
// is 64-bit and exempt (riffOverflow returns nil).
|
||||||
|
if let overflow: (projected: Int, cap: Int) =
|
||||||
|
format.riffOverflow(frameCount: count, channels: channelCount) {
|
||||||
|
throw LyrebirdBufferIOError.fileTooLargeForContainer(
|
||||||
|
projectedBytes: overflow.projected, cap: overflow.cap
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// File format: big-endian flags for AIFF-C; native-endian for WAV/CAF.
|
// RF64 / BW64 is not an ExtAudioFile-writable container — hand it to RF64Writer.
|
||||||
let fileFlags: AudioFormatFlags = format.requiresBigEndian
|
// Client samples are native Float32 interleaved, same as the ExtAudioFile path.
|
||||||
? kAudioFormatFlagIsFloat | kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsPacked
|
if format.usesRF64Writer {
|
||||||
: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked
|
let writer: RF64Writer = try RF64Writer(
|
||||||
|
url: url, format: format, sampleRate: sampleRate, channels: channelCount
|
||||||
|
)
|
||||||
|
let samplesPerChunk: Int = lyrebirdFileIOChunkFrames * channelCount
|
||||||
|
var chunkBuf: [Float] = [Float](repeating: 0, count: samplesPerChunk)
|
||||||
|
try withStorage { storage, frameCount, nch in
|
||||||
|
var frameOffset: Int = 0
|
||||||
|
while frameOffset < frameCount {
|
||||||
|
let framesThisChunk: Int = min(lyrebirdFileIOChunkFrames, frameCount - frameOffset)
|
||||||
|
let samplesThisChunk: Int = framesThisChunk * nch
|
||||||
|
for i: Int in 0..<samplesThisChunk {
|
||||||
|
chunkBuf[i] = Float(storage[frameOffset * nch + i])
|
||||||
|
}
|
||||||
|
try chunkBuf.withUnsafeBufferPointer { ptr in
|
||||||
|
try writer.writeFloat32Interleaved(ptr, frames: framesThisChunk)
|
||||||
|
}
|
||||||
|
frameOffset += framesThisChunk
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try writer.close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var fileFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
// File format: container/encoding/endianness per `format`.
|
||||||
mSampleRate: sampleRate,
|
var fileFormat: AudioStreamBasicDescription =
|
||||||
mFormatID: kAudioFormatLinearPCM,
|
format.makeFileASBD(sampleRate: sampleRate, channels: channelCount)
|
||||||
mFormatFlags: fileFlags,
|
|
||||||
mBytesPerPacket: bytesPerFrame,
|
|
||||||
mFramesPerPacket: 1,
|
|
||||||
mBytesPerFrame: bytesPerFrame,
|
|
||||||
mChannelsPerFrame: UInt32(channelCount),
|
|
||||||
mBitsPerChannel: lyrebirdFileIOBitsPerSample,
|
|
||||||
mReserved: 0
|
|
||||||
)
|
|
||||||
|
|
||||||
// Client format: always native-endian Float32 interleaved.
|
// Client format: always native-endian Float32 interleaved.
|
||||||
// ExtAudioFile converts byte order to match the file format automatically.
|
// ExtAudioFile converts byte order / encoding to match the file format automatically.
|
||||||
var clientFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
var clientFormat: AudioStreamBasicDescription =
|
||||||
mSampleRate: sampleRate,
|
format.makeClientASBD(sampleRate: sampleRate, channels: channelCount)
|
||||||
mFormatID: kAudioFormatLinearPCM,
|
|
||||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
|
||||||
mBytesPerPacket: bytesPerFrame,
|
|
||||||
mFramesPerPacket: 1,
|
|
||||||
mBytesPerFrame: bytesPerFrame,
|
|
||||||
mChannelsPerFrame: UInt32(channelCount),
|
|
||||||
mBitsPerChannel: lyrebirdFileIOBitsPerSample,
|
|
||||||
mReserved: 0
|
|
||||||
)
|
|
||||||
|
|
||||||
var fileRef: ExtAudioFileRef?
|
var fileRef: ExtAudioFileRef?
|
||||||
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
|
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
|
||||||
@@ -340,6 +327,12 @@ public extension LyrebirdBuffer {
|
|||||||
throw LyrebirdBufferIOError.cannotSetOutputFormat(setStatus)
|
throw LyrebirdBufferIOError.cannotSetOutputFormat(setStatus)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Compressed (AAC) formats: push the target bitrate into the encoder.
|
||||||
|
let encoderStatus: OSStatus = format.applyEncoderConfig(to: fileRef)
|
||||||
|
guard encoderStatus == noErr else {
|
||||||
|
throw LyrebirdBufferIOError.cannotSetOutputFormat(encoderStatus)
|
||||||
|
}
|
||||||
|
|
||||||
// Write in chunks, converting Double (Double) → Float32 as we go.
|
// Write in chunks, converting Double (Double) → Float32 as we go.
|
||||||
// The storage is interleaved so sequential reads produce correctly-ordered output
|
// The storage is interleaved so sequential reads produce correctly-ordered output
|
||||||
// for any channel count.
|
// for any channel count.
|
||||||
|
|||||||
@@ -0,0 +1,259 @@
|
|||||||
|
// RF64Writer.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Streaming writer for **RF64 / BW64** WAV files — the 64-bit-sized variant of RIFF
|
||||||
|
/// WAVE (EBU Tech 3306) that lifts the classic 4 GB container limit.
|
||||||
|
///
|
||||||
|
/// `ExtAudioFile` can *read* RF64 but has no RF64 *writer*, so this type emits the
|
||||||
|
/// container by hand via `FileHandle`: a fixed 104-byte header (`RF64` + `ds64` +
|
||||||
|
/// `WAVE_FORMAT_EXTENSIBLE` `fmt ` + `data`) followed by little-endian PCM. The
|
||||||
|
/// `RIFF` and `data` chunk sizes are written as the `0xFFFF_FFFF` sentinel; the true
|
||||||
|
/// 64-bit sizes live in the `ds64` chunk and are patched in on ``close()``.
|
||||||
|
///
|
||||||
|
/// The caller always feeds native **Float32** interleaved samples (matching the other
|
||||||
|
/// Lyrebird writers' client format); this type converts to the file encoding
|
||||||
|
/// (Float32 passthrough, or signed 24-bit packed for `.rf64Int24`).
|
||||||
|
///
|
||||||
|
/// **Not RT-safe.** Construct, write, and close from a non-RT thread (offline render,
|
||||||
|
/// buffer dump, or a `DiskOut` background drain).
|
||||||
|
public final class RF64Writer {
|
||||||
|
|
||||||
|
// MARK: - Format constants
|
||||||
|
|
||||||
|
/// Value written into the 32-bit `RIFF` and `data` size fields; the real 64-bit
|
||||||
|
/// sizes live in the `ds64` chunk. `0xFFFF_FFFF` is the RF64 "see ds64" sentinel.
|
||||||
|
private static let sizeFieldSentinel: UInt32 = 0xFFFF_FFFF
|
||||||
|
|
||||||
|
private static let ds64ChunkBodySize: UInt32 = 28 // riffSize(8) + dataSize(8) + sampleCount(8) + tableLen(4)
|
||||||
|
private static let fmtChunkBodySize: UInt32 = 40 // WAVE_FORMAT_EXTENSIBLE
|
||||||
|
private static let waveFormatExtensible: UInt16 = 0xFFFE
|
||||||
|
private static let fmtExtensionSize: UInt16 = 22 // cbSize for EXTENSIBLE
|
||||||
|
private static let bitsPerByte: Int = 8
|
||||||
|
|
||||||
|
/// Absolute byte offset of the first `ds64` size field (`riffSize`). The three
|
||||||
|
/// 64-bit sizes are contiguous from here (`riffSize`, `dataSize`, `sampleCount`),
|
||||||
|
/// patched in on ``close()``. Fixed by the header layout built in `buildHeader`.
|
||||||
|
private static let ds64RiffSizeOffset: UInt64 = 20
|
||||||
|
|
||||||
|
/// Total header size in bytes; PCM data begins here.
|
||||||
|
static let headerByteCount: Int = 104
|
||||||
|
|
||||||
|
// KSDATAFORMAT_SUBTYPE GUIDs (16 bytes, as laid out in the file).
|
||||||
|
private static let subFormatIEEEFloat: [UInt8] =
|
||||||
|
[0x03, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]
|
||||||
|
private static let subFormatPCM: [UInt8] =
|
||||||
|
[0x01, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]
|
||||||
|
|
||||||
|
/// Full-scale amplitude for signed 24-bit PCM (`2^23 − 1`).
|
||||||
|
private static let int24FullScale: Float = 8_388_607.0
|
||||||
|
|
||||||
|
// MARK: - State (all non-RT, single-writer)
|
||||||
|
|
||||||
|
private let format: AudioFileFormat
|
||||||
|
private let channels: Int
|
||||||
|
private let bytesPerSample: Int
|
||||||
|
private let blockAlign: Int
|
||||||
|
private let fileHandle: FileHandle
|
||||||
|
|
||||||
|
private var dataBytesWritten: Int = 0
|
||||||
|
private(set) public var framesWritten: Int = 0
|
||||||
|
private var closed: Bool = false
|
||||||
|
|
||||||
|
/// Reusable little-endian conversion scratch (int24 path). Grows only.
|
||||||
|
private var scratch: [UInt8] = []
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Create the file and write the RF64 header with placeholder (`ds64`) sizes.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - url: Destination file. Any existing file is truncated.
|
||||||
|
/// - format: Must be `.rf64Float32` or `.rf64Int24`.
|
||||||
|
/// - sampleRate: Sample rate in Hz written into the `fmt ` chunk.
|
||||||
|
/// - channels: Interleaved channel count (≥ 1).
|
||||||
|
public init(
|
||||||
|
url: URL,
|
||||||
|
format: AudioFileFormat,
|
||||||
|
sampleRate: Double,
|
||||||
|
channels: Int
|
||||||
|
) throws {
|
||||||
|
guard format == .rf64Float32 || format == .rf64Int24 else {
|
||||||
|
throw RF64WriterError.unsupportedFormat(format)
|
||||||
|
}
|
||||||
|
precondition(channels >= 1, "RF64Writer requires channels >= 1, got \(channels)")
|
||||||
|
self.format = format
|
||||||
|
self.channels = channels
|
||||||
|
let bytes: Int = Int(format.fileBitsPerChannel) / RF64Writer.bitsPerByte
|
||||||
|
self.bytesPerSample = bytes
|
||||||
|
self.blockAlign = channels * bytes
|
||||||
|
|
||||||
|
// Create (truncate) the file, then open a handle for writing.
|
||||||
|
guard FileManager.default.createFile(atPath: url.path, contents: nil) else {
|
||||||
|
throw RF64WriterError.cannotCreateFile(url)
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
self.fileHandle = try FileHandle(forWritingTo: url)
|
||||||
|
} catch {
|
||||||
|
throw RF64WriterError.cannotCreateFile(url)
|
||||||
|
}
|
||||||
|
|
||||||
|
let header: [UInt8] = RF64Writer.buildHeader(
|
||||||
|
format: format, sampleRate: sampleRate, channels: channels,
|
||||||
|
blockAlign: blockAlign, bitsPerChannel: Int(format.fileBitsPerChannel)
|
||||||
|
)
|
||||||
|
do {
|
||||||
|
try fileHandle.write(contentsOf: Data(header))
|
||||||
|
} catch {
|
||||||
|
try? fileHandle.close()
|
||||||
|
throw RF64WriterError.writeFailed(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Header construction
|
||||||
|
|
||||||
|
/// Build the fixed 104-byte header by appending chunks in order, so no absolute
|
||||||
|
/// byte offsets appear here. `close()` later patches the three `ds64` sizes at
|
||||||
|
/// `ds64RiffSizeOffset` — which is fixed precisely because this layout is fixed.
|
||||||
|
private static func buildHeader(
|
||||||
|
format: AudioFileFormat,
|
||||||
|
sampleRate: Double,
|
||||||
|
channels: Int,
|
||||||
|
blockAlign: Int,
|
||||||
|
bitsPerChannel: Int
|
||||||
|
) -> [UInt8] {
|
||||||
|
var h: [UInt8] = []
|
||||||
|
h.reserveCapacity(headerByteCount)
|
||||||
|
|
||||||
|
func fourCC(_ s: String) { h.append(contentsOf: Array(s.utf8)) }
|
||||||
|
func u16(_ v: UInt16) {
|
||||||
|
h.append(UInt8(truncatingIfNeeded: v))
|
||||||
|
h.append(UInt8(truncatingIfNeeded: v >> 8))
|
||||||
|
}
|
||||||
|
func u32(_ v: UInt32) {
|
||||||
|
for i: Int in 0..<4 { h.append(UInt8(truncatingIfNeeded: v >> (8 * i))) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// RF64 / RIFF-size sentinel / WAVE
|
||||||
|
fourCC("RF64"); u32(sizeFieldSentinel); fourCC("WAVE")
|
||||||
|
|
||||||
|
// ds64 chunk — 64-bit sizes zero for now; patched on close().
|
||||||
|
fourCC("ds64"); u32(ds64ChunkBodySize)
|
||||||
|
u32(0); u32(0) // riffSize (8)
|
||||||
|
u32(0); u32(0) // dataSize (8)
|
||||||
|
u32(0); u32(0) // sampleCount (8)
|
||||||
|
u32(0) // tableLength
|
||||||
|
|
||||||
|
// fmt chunk — WAVE_FORMAT_EXTENSIBLE
|
||||||
|
fourCC("fmt "); u32(fmtChunkBodySize)
|
||||||
|
let avgBytesPerSec: UInt32 = UInt32(sampleRate.rounded()) * UInt32(blockAlign)
|
||||||
|
u16(waveFormatExtensible) // wFormatTag
|
||||||
|
u16(UInt16(channels)) // nChannels
|
||||||
|
u32(UInt32(sampleRate.rounded())) // nSamplesPerSec
|
||||||
|
u32(avgBytesPerSec) // nAvgBytesPerSec
|
||||||
|
u16(UInt16(blockAlign)) // nBlockAlign
|
||||||
|
u16(UInt16(bitsPerChannel)) // wBitsPerSample
|
||||||
|
u16(fmtExtensionSize) // cbSize
|
||||||
|
u16(UInt16(bitsPerChannel)) // wValidBitsPerSample
|
||||||
|
u32(0) // dwChannelMask
|
||||||
|
let guid: [UInt8] = format.isFloatEncoding ? subFormatIEEEFloat : subFormatPCM
|
||||||
|
h.append(contentsOf: guid) // SubFormat GUID (16)
|
||||||
|
|
||||||
|
// data chunk — size sentinel; real size in ds64.
|
||||||
|
fourCC("data"); u32(sizeFieldSentinel)
|
||||||
|
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Write
|
||||||
|
|
||||||
|
/// Append `frames` interleaved frames of native Float32 samples, converting to the
|
||||||
|
/// file encoding. `samples` must contain at least `frames * channels` values.
|
||||||
|
public func writeFloat32Interleaved(_ samples: UnsafeBufferPointer<Float>, frames: Int) throws {
|
||||||
|
guard frames > 0 else { return }
|
||||||
|
let sampleCount: Int = frames * channels
|
||||||
|
|
||||||
|
let payload: Data
|
||||||
|
if format.isFloatEncoding {
|
||||||
|
// Float32 little-endian passthrough (Apple platforms are little-endian).
|
||||||
|
guard let base: UnsafePointer<Float> = samples.baseAddress else { return }
|
||||||
|
payload = Data(buffer: UnsafeBufferPointer(start: base, count: sampleCount))
|
||||||
|
} else {
|
||||||
|
// Signed 24-bit packed little-endian. Round to nearest (matches ExtAudioFile).
|
||||||
|
let byteCount: Int = sampleCount * bytesPerSample
|
||||||
|
if scratch.count < byteCount { scratch = [UInt8](repeating: 0, count: byteCount) }
|
||||||
|
for i: Int in 0..<sampleCount {
|
||||||
|
let clamped: Float = max(-1.0, min(1.0, samples[i]))
|
||||||
|
let s: Int32 = Int32((clamped * RF64Writer.int24FullScale).rounded())
|
||||||
|
scratch[i * 3] = UInt8(truncatingIfNeeded: s)
|
||||||
|
scratch[i * 3 + 1] = UInt8(truncatingIfNeeded: s >> 8)
|
||||||
|
scratch[i * 3 + 2] = UInt8(truncatingIfNeeded: s >> 16)
|
||||||
|
}
|
||||||
|
payload = Data(scratch[0..<byteCount])
|
||||||
|
}
|
||||||
|
|
||||||
|
do {
|
||||||
|
try fileHandle.write(contentsOf: payload)
|
||||||
|
} catch {
|
||||||
|
throw RF64WriterError.writeFailed(error)
|
||||||
|
}
|
||||||
|
dataBytesWritten += sampleCount * bytesPerSample
|
||||||
|
framesWritten += frames
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Close
|
||||||
|
|
||||||
|
/// Finalise the file: write a RIFF word-alignment pad byte if the `data` payload is
|
||||||
|
/// odd-length, patch the true 64-bit `ds64` sizes, and close the handle. Idempotent.
|
||||||
|
///
|
||||||
|
/// The `FileHandle` is closed unconditionally (even if patching throws) so a failed
|
||||||
|
/// finalise never leaks the descriptor.
|
||||||
|
public func close() throws {
|
||||||
|
guard !closed else { return }
|
||||||
|
closed = true
|
||||||
|
defer { try? fileHandle.close() }
|
||||||
|
|
||||||
|
// RIFF requires a trailing pad byte after an odd-length chunk. The pad is part
|
||||||
|
// of the file (counted in riffSize) but not in the chunk's own dataSize. If the
|
||||||
|
// pad write fails, still patch the ds64 sizes below so the file reports its real
|
||||||
|
// data (not the initialized zero); surface the pad error afterwards.
|
||||||
|
var padWritten: Int = 0
|
||||||
|
var padError: Error? = nil
|
||||||
|
if dataBytesWritten % 2 == 1 {
|
||||||
|
do { try fileHandle.write(contentsOf: Data([0])); padWritten = 1 }
|
||||||
|
catch { padError = error }
|
||||||
|
}
|
||||||
|
|
||||||
|
let dataSize: UInt64 = UInt64(dataBytesWritten)
|
||||||
|
let riffSize: UInt64 = UInt64(RF64Writer.headerByteCount - 8) + dataSize + UInt64(padWritten)
|
||||||
|
let sampleCount: UInt64 = blockAlign > 0 ? dataSize / UInt64(blockAlign) : 0
|
||||||
|
|
||||||
|
func u64LE(_ v: UInt64) -> Data {
|
||||||
|
var bytes: [UInt8] = [UInt8](repeating: 0, count: 8)
|
||||||
|
for i: Int in 0..<8 { bytes[i] = UInt8(truncatingIfNeeded: v >> (8 * i)) }
|
||||||
|
return Data(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
do {
|
||||||
|
try fileHandle.seek(toOffset: RF64Writer.ds64RiffSizeOffset)
|
||||||
|
try fileHandle.write(contentsOf: u64LE(riffSize)) // ds64.riffSize
|
||||||
|
try fileHandle.write(contentsOf: u64LE(dataSize)) // ds64.dataSize
|
||||||
|
try fileHandle.write(contentsOf: u64LE(sampleCount)) // ds64.sampleCount
|
||||||
|
} catch {
|
||||||
|
throw RF64WriterError.seekFailed(error)
|
||||||
|
}
|
||||||
|
if let padError: Error = padError {
|
||||||
|
throw RF64WriterError.writeFailed(padError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
// Best-effort: if the owner forgot to close(), still patch sizes so the file
|
||||||
|
// is readable. Errors are unrecoverable here and deliberately swallowed.
|
||||||
|
if !closed { try? close() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// RF64WriterError.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Errors thrown by ``RF64Writer``.
|
||||||
|
public enum RF64WriterError: Error {
|
||||||
|
/// The output file could not be created at the given URL.
|
||||||
|
case cannotCreateFile(URL)
|
||||||
|
/// A `FileHandle` write failed; carries the underlying error.
|
||||||
|
case writeFailed(Error)
|
||||||
|
/// Seeking back to patch the `ds64` sizes on ``RF64Writer/close()`` failed.
|
||||||
|
case seekFailed(Error)
|
||||||
|
/// The format passed to ``RF64Writer/init(url:format:sampleRate:channels:)`` is not
|
||||||
|
/// an RF64 case. Only `.rf64Float32` / `.rf64Int24` are supported.
|
||||||
|
case unsupportedFormat(AudioFileFormat)
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
// DistributionKindSampling.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
extension DistributionKind {
|
||||||
|
|
||||||
|
/// Draw one sample from this distribution, advancing `rng` (a xorshift64
|
||||||
|
/// state). This is the canonical mapping from a ``DistributionKind`` case to
|
||||||
|
/// its sampler — the same mapping ``TemporalTendency`` and
|
||||||
|
/// ``DemandTemporalTendency`` use — exposed for one-shot scalar draws.
|
||||||
|
///
|
||||||
|
/// The `parX` / `parY` / `parA` / `parB` roles are per-distribution; see the
|
||||||
|
/// parameter table on ``DistributionKind``. `parA` / `parB` are optional and
|
||||||
|
/// fall back to each distribution's own default (beta shapes default to `2`;
|
||||||
|
/// Cauchy's positive-only flag defaults off).
|
||||||
|
///
|
||||||
|
/// RT-safe: pure arithmetic, no allocation. For an ergonomic seedable wrapper
|
||||||
|
/// with named per-distribution methods, use ``LyrebirdRandom``.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - parX: First parameter (e.g. `lo`, density, dispersion, dev — per the table).
|
||||||
|
/// - parY: Second parameter (e.g. `hi`, mean — per the table). Ignored by
|
||||||
|
/// single-parameter distributions. Defaults to `1` (matching
|
||||||
|
/// ``TemporalTendency`` / ``DemandTemporalTendency``), so an omitted
|
||||||
|
/// `parY` on a range distribution gives `[lo, 1]` rather than a
|
||||||
|
/// degenerate `[lo, 0]` — but supply it explicitly for a real range.
|
||||||
|
/// - parA: Third parameter (beta `alpha`, Cauchy positive-only flag).
|
||||||
|
/// `nil` uses the distribution's default.
|
||||||
|
/// - parB: Fourth parameter (beta `beta`). `nil` uses the default.
|
||||||
|
/// - rng: xorshift64 state, advanced in place.
|
||||||
|
/// - Returns: One sample.
|
||||||
|
public func sample(
|
||||||
|
parX: Double,
|
||||||
|
parY: Double = 1,
|
||||||
|
parA: Double? = nil,
|
||||||
|
parB: Double? = nil,
|
||||||
|
using rng: inout UInt64
|
||||||
|
) -> Double {
|
||||||
|
let betaDefaultAlpha: Double = 2.0
|
||||||
|
let betaDefaultBeta: Double = 2.0
|
||||||
|
switch self {
|
||||||
|
case .uniform:
|
||||||
|
return _sampleUniform(lo: parX, hi: parY, rng: &rng)
|
||||||
|
case .lpRand:
|
||||||
|
return _sampleLpRand(lo: parX, hi: parY, rng: &rng)
|
||||||
|
case .hpRand:
|
||||||
|
return _sampleHpRand(lo: parX, hi: parY, rng: &rng)
|
||||||
|
case .meanRand:
|
||||||
|
return _sampleMeanRand(lo: parX, hi: parY, rng: &rng)
|
||||||
|
case .expRand:
|
||||||
|
return _sampleExpRand(lo: parX, hi: parY, rng: &rng)
|
||||||
|
case .exponential:
|
||||||
|
return _sampleExponential(density: parX, rng: &rng)
|
||||||
|
case .gamma:
|
||||||
|
return _sampleGamma(shape: parX, rng: &rng)
|
||||||
|
case .laplace:
|
||||||
|
return _sampleLaplace(dispersion: parX, rng: &rng)
|
||||||
|
case .alaplace:
|
||||||
|
return _sampleALaplace(dispersion: parX, rng: &rng)
|
||||||
|
case .hcos:
|
||||||
|
return _sampleHcos(dispersion: parX, rng: &rng)
|
||||||
|
case .logistic:
|
||||||
|
return _sampleLogistic(dispersion: parX, rng: &rng)
|
||||||
|
case .poisson:
|
||||||
|
return _samplePoisson(mean: parX, rng: &rng)
|
||||||
|
case .arcsin:
|
||||||
|
return _sampleArcsin(dispersion: parX, rng: &rng)
|
||||||
|
case .betaRand:
|
||||||
|
return _sampleBetaRand(
|
||||||
|
lo: parX,
|
||||||
|
hi: parY,
|
||||||
|
alpha: parA ?? betaDefaultAlpha,
|
||||||
|
beta: parB ?? betaDefaultBeta,
|
||||||
|
rng: &rng
|
||||||
|
)
|
||||||
|
case .cauchy:
|
||||||
|
return _sampleCauchy(mean: parX, spread: parY, posOnly: (parA ?? 0) > 0, rng: &rng)
|
||||||
|
case .gauss:
|
||||||
|
return _sampleGauss(dev: parX, mean: parY, rng: &rng)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
// LyrebirdRandom.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
/// A seedable scalar random source over Lyrebird's distribution family.
|
||||||
|
///
|
||||||
|
/// Where ``TemporalStream`` / ``Pattern`` produce *sequences* and the noise
|
||||||
|
/// generators produce *signals*, `LyrebirdRandom` answers the "give me one
|
||||||
|
/// value" case: a single draw from a uniform range, a Gaussian, a Laplace, and
|
||||||
|
/// so on. It owns a xorshift64 state, so a given `seed` produces a fully
|
||||||
|
/// reproducible stream of draws — which is what musical use wants.
|
||||||
|
///
|
||||||
|
/// ```swift
|
||||||
|
/// var r = LyrebirdRandom(seed: 42)
|
||||||
|
/// let freq: Double = r.exponentialRange(low: 200, high: 2000) // Hz, log-uniform
|
||||||
|
/// let dur: Double = r.uniform(low: 0.1, high: 0.5) // seconds
|
||||||
|
/// let jitter: Double = r.gauss(mean: 0, dev: 0.02) // ± around 0
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Each draw method maps to a ``DistributionKind`` case; the generic
|
||||||
|
/// ``value(_:parX:parY:parA:parB:)`` reaches any distribution by kind. For
|
||||||
|
/// throwaway draws with no seed bookkeeping, use ``shared``.
|
||||||
|
///
|
||||||
|
/// Value semantics: copying a `LyrebirdRandom` forks its stream. Not
|
||||||
|
/// thread-safe — give each thread its own instance (or use ``shared``, which is
|
||||||
|
/// synchronized).
|
||||||
|
public struct LyrebirdRandom: Sendable {
|
||||||
|
|
||||||
|
/// The live xorshift64 state. Exposed so callers can snapshot/restore a
|
||||||
|
/// draw position; mutated by every draw.
|
||||||
|
public var state: UInt64
|
||||||
|
|
||||||
|
/// Create a reproducible source from an explicit seed.
|
||||||
|
/// - Parameter seed: Any `UInt64`; normalised to a non-zero xorshift state.
|
||||||
|
public init(seed: UInt64) {
|
||||||
|
self.state = lyrebirdSeedXorshift64(from: seed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a source seeded from system entropy (uptime nanoseconds) — draws
|
||||||
|
/// are not reproducible across runs. Prefer ``init(seed:)`` when you need
|
||||||
|
/// repeatability.
|
||||||
|
public init() {
|
||||||
|
self.state = lyrebirdSeedXorshift64(from: nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Generic
|
||||||
|
|
||||||
|
/// Draw one sample from `kind`, advancing this source's state.
|
||||||
|
/// - Parameters:
|
||||||
|
/// - kind: The distribution to sample.
|
||||||
|
/// - parX: First parameter (per ``DistributionKind``'s table).
|
||||||
|
/// - parY: Second parameter. Ignored by single-parameter distributions.
|
||||||
|
/// - parA: Third parameter (beta `alpha` / Cauchy positive-only). `nil` = default.
|
||||||
|
/// - parB: Fourth parameter (beta `beta`). `nil` = default.
|
||||||
|
/// - Returns: One sample.
|
||||||
|
public mutating func value(
|
||||||
|
_ kind: DistributionKind,
|
||||||
|
parX: Double,
|
||||||
|
parY: Double = 1,
|
||||||
|
parA: Double? = nil,
|
||||||
|
parB: Double? = nil
|
||||||
|
) -> Double {
|
||||||
|
kind.sample(parX: parX, parY: parY, parA: parA, parB: parB, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Uniform family
|
||||||
|
|
||||||
|
/// A uniform sample in `[0, 1]`.
|
||||||
|
public mutating func unit() -> Double {
|
||||||
|
DistributionKind.uniform.sample(parX: 0, parY: 1, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Uniform (flat) sample in `[low, high]`.
|
||||||
|
public mutating func uniform(low: Double, high: Double) -> Double {
|
||||||
|
DistributionKind.uniform.sample(parX: low, parY: high, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sample in `[low, high]` biased toward `low` (squared uniform).
|
||||||
|
public mutating func lowBiased(low: Double, high: Double) -> Double {
|
||||||
|
DistributionKind.lpRand.sample(parX: low, parY: high, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sample in `[low, high]` biased toward `high` (mirrored squared uniform).
|
||||||
|
public mutating func highBiased(low: Double, high: Double) -> Double {
|
||||||
|
DistributionKind.hpRand.sample(parX: low, parY: high, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sample in `[low, high]` biased toward the midpoint (mean of two uniforms).
|
||||||
|
public mutating func meanBiased(low: Double, high: Double) -> Double {
|
||||||
|
DistributionKind.meanRand.sample(parX: low, parY: high, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Log-uniform sample in `[low, high]`; both bounds must be `> 0`.
|
||||||
|
public mutating func exponentialRange(low: Double, high: Double) -> Double {
|
||||||
|
DistributionKind.expRand.sample(parX: low, parY: high, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Single-parameter families
|
||||||
|
|
||||||
|
/// Standard exponential; `density` is the rate λ (`> 0`). Output `≥ 0`.
|
||||||
|
public mutating func exponential(density: Double) -> Double {
|
||||||
|
DistributionKind.exponential.sample(parX: density, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gamma distribution; `shape` is `k` (`> 0`). `k = 1` is exponential.
|
||||||
|
public mutating func gamma(shape: Double) -> Double {
|
||||||
|
DistributionKind.gamma.sample(parX: shape, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Laplace (double-exponential), symmetric about 0; `scale` is dispersion `b`.
|
||||||
|
public mutating func laplace(scale: Double = 1) -> Double {
|
||||||
|
DistributionKind.laplace.sample(parX: scale, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asymmetric Laplace (right tail heavier, p = 0.7); `scale` is dispersion `b`.
|
||||||
|
public mutating func asymmetricLaplace(scale: Double = 1) -> Double {
|
||||||
|
DistributionKind.alaplace.sample(parX: scale, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Half-cosine bell centred at 0; output ≈ `[−d/π, d/π]`.
|
||||||
|
public mutating func halfCosine(dispersion: Double = 1) -> Double {
|
||||||
|
DistributionKind.hcos.sample(parX: dispersion, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logistic distribution centred at 0 (heavier tails than Gaussian); `scale` is `s`.
|
||||||
|
public mutating func logistic(scale: Double = 1) -> Double {
|
||||||
|
DistributionKind.logistic.sample(parX: scale, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Poisson counts; `mean` is λ (clamped to `[0.001, 30]`). Integer-valued.
|
||||||
|
public mutating func poisson(mean: Double) -> Double {
|
||||||
|
DistributionKind.poisson.sample(parX: mean, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// U-shaped arcsin distribution; output in `[−dispersion, dispersion]`.
|
||||||
|
public mutating func arcsin(dispersion: Double = 1) -> Double {
|
||||||
|
DistributionKind.arcsin.sample(parX: dispersion, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Multi-parameter families
|
||||||
|
|
||||||
|
/// Beta distribution mapped to `[low, high]`. `alpha`/`beta` shape it
|
||||||
|
/// (`alpha == beta` symmetric; both `< 1` bimodal; `1, 1` uniform).
|
||||||
|
public mutating func beta(
|
||||||
|
low: Double,
|
||||||
|
high: Double,
|
||||||
|
alpha: Double = 2,
|
||||||
|
beta: Double = 2
|
||||||
|
) -> Double {
|
||||||
|
DistributionKind.betaRand.sample(parX: low, parY: high, parA: alpha, parB: beta, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cauchy distribution; heavy-tailed. `positiveOnly` folds onto the positive axis.
|
||||||
|
public mutating func cauchy(
|
||||||
|
mean: Double = 0,
|
||||||
|
spread: Double = 1,
|
||||||
|
positiveOnly: Bool = false
|
||||||
|
) -> Double {
|
||||||
|
DistributionKind.cauchy.sample(parX: mean, parY: spread, parA: positiveOnly ? 1 : 0, using: &state)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gaussian (normal) distribution; `dev` is the standard deviation σ.
|
||||||
|
public mutating func gauss(mean: Double = 0, dev: Double = 1) -> Double {
|
||||||
|
DistributionKind.gauss.sample(parX: dev, parY: mean, using: &state)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
// SharedRandom.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Process-wide, thread-safe scalar random source for throwaway draws where you
|
||||||
|
/// don't want to thread a ``LyrebirdRandom`` through your code. Reached via
|
||||||
|
/// ``LyrebirdRandom/shared``.
|
||||||
|
///
|
||||||
|
/// ```swift
|
||||||
|
/// let x: Double = LyrebirdRandom.shared.uniform(low: 0, high: 1)
|
||||||
|
/// let g: Double = LyrebirdRandom.shared.gauss(mean: 0, dev: 1)
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// System-seeded, so its stream is **not reproducible** across runs, and its
|
||||||
|
/// interleaving across threads is non-deterministic — every draw locks a shared
|
||||||
|
/// state. When you need repeatable draws (e.g. a rendered score), use an owned
|
||||||
|
/// `LyrebirdRandom(seed:)` instead. Call ``reseed(_:)`` to pin the shared stream
|
||||||
|
/// for a test.
|
||||||
|
public final class SharedRandom: @unchecked Sendable {
|
||||||
|
|
||||||
|
private var gen: LyrebirdRandom
|
||||||
|
private let lock: NSLock = NSLock()
|
||||||
|
|
||||||
|
init() {
|
||||||
|
self.gen = LyrebirdRandom()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replace the shared state with one seeded from `seed`. Mainly for tests
|
||||||
|
/// that need the shared source to be reproducible.
|
||||||
|
public func reseed(_ seed: UInt64) {
|
||||||
|
lock.lock(); defer { lock.unlock() }
|
||||||
|
gen = LyrebirdRandom(seed: seed)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func locked(_ body: (inout LyrebirdRandom) -> Double) -> Double {
|
||||||
|
lock.lock(); defer { lock.unlock() }
|
||||||
|
return body(&gen)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/value(_:parX:parY:parA:parB:)``.
|
||||||
|
public func value(
|
||||||
|
_ kind: DistributionKind,
|
||||||
|
parX: Double,
|
||||||
|
parY: Double = 1,
|
||||||
|
parA: Double? = nil,
|
||||||
|
parB: Double? = nil
|
||||||
|
) -> Double {
|
||||||
|
locked { $0.value(kind, parX: parX, parY: parY, parA: parA, parB: parB) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/unit()``.
|
||||||
|
public func unit() -> Double { locked { $0.unit() } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/uniform(low:high:)``.
|
||||||
|
public func uniform(low: Double, high: Double) -> Double { locked { $0.uniform(low: low, high: high) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/lowBiased(low:high:)``.
|
||||||
|
public func lowBiased(low: Double, high: Double) -> Double { locked { $0.lowBiased(low: low, high: high) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/highBiased(low:high:)``.
|
||||||
|
public func highBiased(low: Double, high: Double) -> Double { locked { $0.highBiased(low: low, high: high) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/meanBiased(low:high:)``.
|
||||||
|
public func meanBiased(low: Double, high: Double) -> Double { locked { $0.meanBiased(low: low, high: high) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/exponentialRange(low:high:)``.
|
||||||
|
public func exponentialRange(low: Double, high: Double) -> Double { locked { $0.exponentialRange(low: low, high: high) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/exponential(density:)``.
|
||||||
|
public func exponential(density: Double) -> Double { locked { $0.exponential(density: density) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/gamma(shape:)``.
|
||||||
|
public func gamma(shape: Double) -> Double { locked { $0.gamma(shape: shape) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/laplace(scale:)``.
|
||||||
|
public func laplace(scale: Double = 1) -> Double { locked { $0.laplace(scale: scale) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/asymmetricLaplace(scale:)``.
|
||||||
|
public func asymmetricLaplace(scale: Double = 1) -> Double { locked { $0.asymmetricLaplace(scale: scale) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/halfCosine(dispersion:)``.
|
||||||
|
public func halfCosine(dispersion: Double = 1) -> Double { locked { $0.halfCosine(dispersion: dispersion) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/logistic(scale:)``.
|
||||||
|
public func logistic(scale: Double = 1) -> Double { locked { $0.logistic(scale: scale) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/poisson(mean:)``.
|
||||||
|
public func poisson(mean: Double) -> Double { locked { $0.poisson(mean: mean) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/arcsin(dispersion:)``.
|
||||||
|
public func arcsin(dispersion: Double = 1) -> Double { locked { $0.arcsin(dispersion: dispersion) } }
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/beta(low:high:alpha:beta:)``.
|
||||||
|
public func beta(
|
||||||
|
low: Double,
|
||||||
|
high: Double,
|
||||||
|
alpha: Double = 2,
|
||||||
|
beta: Double = 2
|
||||||
|
) -> Double {
|
||||||
|
locked { $0.beta(low: low, high: high, alpha: alpha, beta: beta) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/cauchy(mean:spread:positiveOnly:)``.
|
||||||
|
public func cauchy(
|
||||||
|
mean: Double = 0,
|
||||||
|
spread: Double = 1,
|
||||||
|
positiveOnly: Bool = false
|
||||||
|
) -> Double {
|
||||||
|
locked { $0.cauchy(mean: mean, spread: spread, positiveOnly: positiveOnly) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// See ``LyrebirdRandom/gauss(mean:dev:)``.
|
||||||
|
public func gauss(mean: Double = 0, dev: Double = 1) -> Double {
|
||||||
|
locked { $0.gauss(mean: mean, dev: dev) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension LyrebirdRandom {
|
||||||
|
/// Process-wide thread-safe source for quick, non-reproducible draws.
|
||||||
|
/// See ``SharedRandom``.
|
||||||
|
public static let shared: SharedRandom = SharedRandom()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Global shorthand for the process-wide shared random source
|
||||||
|
/// (``LyrebirdRandom/shared``) — the common non-seeded case.
|
||||||
|
///
|
||||||
|
/// ```swift
|
||||||
|
/// let pan: Double = Random.uniform(low: -1, high: 1)
|
||||||
|
/// let freq: Double = Random.exponentialRange(low: 200, high: 2000)
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Draws are **not reproducible** across runs; for a repeatable seeded stream use
|
||||||
|
/// `LyrebirdRandom(seed:)`. Capitalized to avoid shadowing C's `rand()`.
|
||||||
|
public let Random: SharedRandom = LyrebirdRandom.shared
|
||||||