diff --git a/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj b/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj new file mode 100644 index 0000000..8317f7b --- /dev/null +++ b/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj @@ -0,0 +1,379 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + C3B1000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B100000000000000000007 /* main.swift */; }; + C3B1000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B100000000000000000008 /* AppDelegate.swift */; }; + C3B100000000000000000020 /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = C3B10000000000000000001E /* LyrebirdShoeGaze */; }; + C3B100000000000000000021 /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B10000000000000000001F /* LyrebirdShoeGazeUI */; }; + C3B100000000000000000022 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3B100000000000000000023 /* Lyrebird */; }; + C3B100000000000000000024 /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B100000000000000000025 /* LyrebirdUI */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + C3B100000000000000000004 /* ShoeGazeBuilder.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ShoeGazeBuilder.app; sourceTree = BUILT_PRODUCTS_DIR; }; + C3B100000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + C3B100000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; }; + C3B100000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + C3B100000000000000000012 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C3B100000000000000000020 /* LyrebirdShoeGaze in Frameworks */, + C3B100000000000000000021 /* LyrebirdShoeGazeUI in Frameworks */, + C3B100000000000000000022 /* Lyrebird in Frameworks */, + C3B100000000000000000024 /* LyrebirdUI in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + C3B100000000000000000002 = { + isa = PBXGroup; + children = ( + C3B100000000000000000005 /* ShoeGazeBuilder */, + C3B100000000000000000003 /* Products */, + ); + sourceTree = ""; + }; + C3B100000000000000000003 /* Products */ = { + isa = PBXGroup; + children = ( + C3B100000000000000000004 /* ShoeGazeBuilder.app */, + ); + name = Products; + sourceTree = ""; + }; + C3B100000000000000000005 /* ShoeGazeBuilder */ = { + isa = PBXGroup; + children = ( + C3B100000000000000000007 /* main.swift */, + C3B100000000000000000008 /* AppDelegate.swift */, + C3B100000000000000000006 /* Info.plist */, + ); + path = ShoeGazeBuilder; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + C3B100000000000000000014 /* ShoeGazeBuilder */ = { + isa = PBXNativeTarget; + buildConfigurationList = C3B100000000000000000015 /* Build configuration list for PBXNativeTarget "ShoeGazeBuilder" */; + buildPhases = ( + C3B100000000000000000011 /* Sources */, + C3B100000000000000000012 /* Frameworks */, + C3B100000000000000000013 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = ShoeGazeBuilder; + packageProductDependencies = ( + C3B10000000000000000001E /* LyrebirdShoeGaze */, + C3B10000000000000000001F /* LyrebirdShoeGazeUI */, + C3B100000000000000000023 /* Lyrebird */, + C3B100000000000000000025 /* LyrebirdUI */, + ); + productName = ShoeGazeBuilder; + productReference = C3B100000000000000000004 /* ShoeGazeBuilder.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + C3B100000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 2620; + TargetAttributes = { + C3B100000000000000000014 = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = C3B100000000000000000018 /* Build configuration list for PBXProject "ShoeGazeBuilder" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = C3B100000000000000000002; + packageReferences = ( + C3B10000000000000000001B /* XCLocalSwiftPackageReference ".." */, + C3B10000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */, + ); + productRefGroup = C3B100000000000000000003 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + C3B100000000000000000014 /* ShoeGazeBuilder */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + C3B100000000000000000013 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + C3B100000000000000000011 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C3B1000000000000000000C /* main.swift in Sources */, + C3B1000000000000000000D /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + C3B100000000000000000016 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CODE_SIGNING_REQUIRED = NO; + COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + DEVELOPMENT_TEAM = ""; + ENABLE_HARDENED_RUNTIME = YES; + INFOPLIST_FILE = ShoeGazeBuilder/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 15.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + C3B100000000000000000017 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CODE_SIGNING_REQUIRED = NO; + COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; + DEVELOPMENT_TEAM = ""; + ENABLE_HARDENED_RUNTIME = YES; + INFOPLIST_FILE = ShoeGazeBuilder/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 15.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + C3B100000000000000000019 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + C3B10000000000000000001A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + C3B100000000000000000015 /* Build configuration list for PBXNativeTarget "ShoeGazeBuilder" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C3B100000000000000000016 /* Debug */, + C3B100000000000000000017 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C3B100000000000000000018 /* Build configuration list for PBXProject "ShoeGazeBuilder" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C3B100000000000000000019 /* Debug */, + C3B10000000000000000001A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + C3B10000000000000000001B /* XCLocalSwiftPackageReference ".." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCRemoteSwiftPackageReference section */ + C3B10000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 1.2.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + C3B10000000000000000001E /* LyrebirdShoeGaze */ = { + isa = XCSwiftPackageProductDependency; + package = C3B10000000000000000001B /* XCLocalSwiftPackageReference ".." */; + productName = LyrebirdShoeGaze; + }; + C3B10000000000000000001F /* LyrebirdShoeGazeUI */ = { + isa = XCSwiftPackageProductDependency; + package = C3B10000000000000000001B /* XCLocalSwiftPackageReference ".." */; + productName = LyrebirdShoeGazeUI; + }; + C3B100000000000000000023 /* Lyrebird */ = { + isa = XCSwiftPackageProductDependency; + package = C3B10000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */; + productName = Lyrebird; + }; + C3B100000000000000000025 /* LyrebirdUI */ = { + isa = XCSwiftPackageProductDependency; + package = C3B10000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */; + productName = LyrebirdUI; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = C3B100000000000000000001 /* Project object */; +} diff --git a/Demo/ShoeGazeBuilder.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demo/ShoeGazeBuilder.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..82a587c --- /dev/null +++ b/Demo/ShoeGazeBuilder.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,33 @@ +{ + "originHash" : "cfdd71f4b32d744c862bbe26a8265d75aa9e906275b0fb1b63575b7d68be1b6a", + "pins" : [ + { + "identity" : "linenoise-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/andybest/linenoise-swift", + "state" : { + "revision" : "afc897c02b030af7333105c4fedcd843a8339238", + "version" : "0.0.3" + } + }, + { + "identity" : "lyrebird", + "kind" : "remoteSourceControl", + "location" : "https://realizedsound.mooo.com/josh/Lyrebird", + "state" : { + "revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c", + "version" : "1.2.0" + } + }, + { + "identity" : "nimble", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Quick/Nimble.git", + "state" : { + "revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0", + "version" : "7.3.4" + } + } + ], + "version" : 3 +} diff --git a/Demo/ShoeGazeBuilder.xcodeproj/xcshareddata/xcschemes/ShoeGazeBuilder.xcscheme b/Demo/ShoeGazeBuilder.xcodeproj/xcshareddata/xcschemes/ShoeGazeBuilder.xcscheme new file mode 100644 index 0000000..411f737 --- /dev/null +++ b/Demo/ShoeGazeBuilder.xcodeproj/xcshareddata/xcschemes/ShoeGazeBuilder.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demo/ShoeGazeBuilder/AppDelegate.swift b/Demo/ShoeGazeBuilder/AppDelegate.swift new file mode 100644 index 0000000..0df0109 --- /dev/null +++ b/Demo/ShoeGazeBuilder/AppDelegate.swift @@ -0,0 +1,158 @@ +// AppDelegate.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if os(macOS) +import AppKit +import LyrebirdSynth +import LyrebirdUI +import LyrebirdShoeGaze +import LyrebirdShoeGazeUI + +/// Application delegate for the ShoeGaze Builder. +/// +/// Creates a `SynthesisEngine` and a `ShoeGaze` session seeded with one empty board, then opens a +/// `LyrebirdWindow` hosting ``ShoeGazeBuilderView`` — the interactive palette + board builder. +/// +/// The engine is **not** started automatically; the user clicks Start in the builder's toolbar. +/// On termination the engine is stopped to release Core Audio resources cleanly. +@MainActor +final class AppDelegate: NSObject, NSApplicationDelegate { + + // MARK: - Engine configuration constants + + private static let blockSize: Int = 512 + private static let sampleRate: Double = 48_000.0 + private static let outputChannels: Int = 2 + private static let inputChannels: Int = 2 + private static let numAudioBuses: Int = 256 + + // MARK: - Window geometry constants + + private static let windowWidth: CGFloat = 1_400 + private static let windowHeight: CGFloat = 860 + + /// Margin from the left edge of the screen's visible area, in points. + private static let leftMargin: CGFloat = 100 + /// Margin reserved at the right edge so the window never runs off-screen. + private static let rightMargin: CGFloat = 40 + /// Fraction of the visible screen height the window should occupy. + private static let heightFraction: CGFloat = 0.88 + + /// The default pedal the seed board comes up with, so audio is audible immediately on Start. + private static let seedPedalType: String = "Overdrive" + + // MARK: - Owned objects + + private let engine: SynthesisEngine + private let shoeGaze: ShoeGaze + private let window: LyrebirdWindow + + // MARK: - Init + + override init() { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: AppDelegate.blockSize, + sampleRate: AppDelegate.sampleRate, + numOutputChannels: AppDelegate.outputChannels, + numInputChannels: AppDelegate.inputChannels, + numAudioBuses: AppDelegate.numAudioBuses, + driver: CoreAudioDriver() + ) + self.engine = engine + self.shoeGaze = ShoeGaze(engine: engine) + self.window = LyrebirdWindow( + title: "ShoeGaze Builder — Lyrebird Pedalboard", + width: AppDelegate.windowWidth, + height: AppDelegate.windowHeight + ) + super.init() + + seedInitialBoard() + } + + /// Seeds one board with a single pedal so the builder opens with an audible starting point. + private func seedInitialBoard() { + var created: PedalBoard? + do { + let board: PedalBoard = try shoeGaze.addBoard() + created = board + try shoeGaze.appendPedal(type: AppDelegate.seedPedalType, to: board) + } catch { + if let board: PedalBoard = created { shoeGaze.removeBoard(board) } + print("[ShoeGazeBuilder] seed board failed: \(error)") + } + } + + // MARK: - NSApplicationDelegate + + func applicationDidFinishLaunching(_ notification: Notification) { + installMainMenu() + let session: ShoeGaze = shoeGaze + window.open { + ShoeGazeBuilderView(shoeGaze: session) + } + anchorWindowLeft() + } + + /// Anchors the window `leftMargin` points from the left of the visible screen and sizes it to + /// most of the visible height, so it presents large and left-aligned rather than centered. + private func anchorWindowLeft() { + guard let nsWindow: NSWindow = window.nsWindow, + let screen: NSScreen = nsWindow.screen ?? NSScreen.main else { return } + let visible: NSRect = screen.visibleFrame + let height: CGFloat = visible.height * AppDelegate.heightFraction + let maxWidth: CGFloat = visible.width - AppDelegate.leftMargin - AppDelegate.rightMargin + let width: CGFloat = min(AppDelegate.windowWidth, maxWidth) + let originX: CGFloat = visible.minX + AppDelegate.leftMargin + // Top-align: place the window's top near the top of the visible area. + let originY: CGFloat = visible.maxY - height + nsWindow.setFrame( + NSRect(x: originX, y: originY, width: width, height: height), + display: true + ) + } + + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + true + } + + func applicationWillTerminate(_ notification: Notification) { + engine.stop() + } + + // MARK: - Main menu + + /// Builds a minimal menu bar: an application menu with About / Hide / Quit (⌘Q). + private func installMainMenu() { + let appName: String = ProcessInfo.processInfo.processName + let mainMenu: NSMenu = NSMenu() + + let appMenuItem: NSMenuItem = NSMenuItem() + mainMenu.addItem(appMenuItem) + let appMenu: NSMenu = NSMenu() + appMenuItem.submenu = appMenu + appMenu.addItem( + withTitle: "About \(appName)", + action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)), + keyEquivalent: "" + ) + appMenu.addItem(NSMenuItem.separator()) + appMenu.addItem( + withTitle: "Hide \(appName)", + action: #selector(NSApplication.hide(_:)), + keyEquivalent: "h" + ) + appMenu.addItem(NSMenuItem.separator()) + appMenu.addItem( + withTitle: "Quit \(appName)", + action: #selector(NSApplication.terminate(_:)), + keyEquivalent: "q" + ) + + NSApplication.shared.mainMenu = mainMenu + } +} +#endif diff --git a/Demo/ShoeGazeBuilder/Info.plist b/Demo/ShoeGazeBuilder/Info.plist new file mode 100644 index 0000000..6734627 --- /dev/null +++ b/Demo/ShoeGazeBuilder/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSApplicationCategoryType + public.app-category.music + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHighResolutionCapable + + NSHumanReadableCopyright + Copyright © 2026 Realized Sound. All rights reserved. + NSMicrophoneUsageDescription + ShoeGaze Builder can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode. + NSPrincipalClass + NSApplication + + diff --git a/Demo/ShoeGazeBuilder/main.swift b/Demo/ShoeGazeBuilder/main.swift new file mode 100644 index 0000000..a67108b --- /dev/null +++ b/Demo/ShoeGazeBuilder/main.swift @@ -0,0 +1,23 @@ +// main.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if os(macOS) +import AppKit + +// Program entry runs on the main thread; assert main-actor isolation for the AppKit bootstrap +// rather than hopping asynchronously. `AppDelegate.init` builds `@MainActor` synthesizers and UI. +MainActor.assumeIsolated { + let app: NSApplication = NSApplication.shared + let delegate: AppDelegate = AppDelegate() + app.setActivationPolicy(.regular) + app.delegate = delegate + app.activate(ignoringOtherApps: true) + app.run() +} +#else +// The ShoeGaze Builder is a macOS AppKit application and has no iOS entry point here. +print("ShoeGazeBuilder runs on macOS only.") +#endif diff --git a/Demo/ShoeGazeBuilderiOS.xcodeproj/project.pbxproj b/Demo/ShoeGazeBuilderiOS.xcodeproj/project.pbxproj new file mode 100644 index 0000000..9784552 --- /dev/null +++ b/Demo/ShoeGazeBuilderiOS.xcodeproj/project.pbxproj @@ -0,0 +1,379 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + C3C100000000000000000009 /* ShoeGazeBuilderiOSApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C100000000000000000007 /* ShoeGazeBuilderiOSApp.swift */; }; + C3C10000000000000000000A /* ShoeGazeBuilderiOSAppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C100000000000000000008 /* ShoeGazeBuilderiOSAppModel.swift */; }; + C3C10000000000000000000B /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = C3C10000000000000000001A /* LyrebirdShoeGaze */; }; + C3C10000000000000000000C /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3C10000000000000000001B /* LyrebirdShoeGazeUI */; }; + C3C10000000000000000000D /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3C10000000000000000001C /* LyrebirdUI */; }; + C3C10000000000000000001D /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3C10000000000000000001E /* Lyrebird */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + C3C100000000000000000004 /* ShoeGazeBuilderiOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ShoeGazeBuilderiOS.app; sourceTree = BUILT_PRODUCTS_DIR; }; + C3C100000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + C3C100000000000000000007 /* ShoeGazeBuilderiOSApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeBuilderiOSApp.swift; sourceTree = ""; }; + C3C100000000000000000008 /* ShoeGazeBuilderiOSAppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeBuilderiOSAppModel.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + C3C10000000000000000000F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C3C10000000000000000000B /* LyrebirdShoeGaze in Frameworks */, + C3C10000000000000000000C /* LyrebirdShoeGazeUI in Frameworks */, + C3C10000000000000000000D /* LyrebirdUI in Frameworks */, + C3C10000000000000000001D /* Lyrebird in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + C3C100000000000000000002 = { + isa = PBXGroup; + children = ( + C3C100000000000000000005 /* ShoeGazeBuilderiOS */, + C3C100000000000000000003 /* Products */, + ); + sourceTree = ""; + }; + C3C100000000000000000003 /* Products */ = { + isa = PBXGroup; + children = ( + C3C100000000000000000004 /* ShoeGazeBuilderiOS.app */, + ); + name = Products; + sourceTree = ""; + }; + C3C100000000000000000005 /* ShoeGazeBuilderiOS */ = { + isa = PBXGroup; + children = ( + C3C100000000000000000007 /* ShoeGazeBuilderiOSApp.swift */, + C3C100000000000000000008 /* ShoeGazeBuilderiOSAppModel.swift */, + C3C100000000000000000006 /* Info.plist */, + ); + path = ShoeGazeBuilderiOS; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + C3C100000000000000000011 /* ShoeGazeBuilderiOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = C3C100000000000000000012 /* Build configuration list for PBXNativeTarget "ShoeGazeBuilderiOS" */; + buildPhases = ( + C3C10000000000000000000E /* Sources */, + C3C10000000000000000000F /* Frameworks */, + C3C100000000000000000010 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = ShoeGazeBuilderiOS; + packageProductDependencies = ( + C3C10000000000000000001A /* LyrebirdShoeGaze */, + C3C10000000000000000001B /* LyrebirdShoeGazeUI */, + C3C10000000000000000001C /* LyrebirdUI */, + C3C10000000000000000001E /* Lyrebird */, + ); + productName = ShoeGazeBuilderiOS; + productReference = C3C100000000000000000004 /* ShoeGazeBuilderiOS.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + C3C100000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 2620; + TargetAttributes = { + C3C100000000000000000011 = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = C3C100000000000000000015 /* Build configuration list for PBXProject "ShoeGazeBuilderiOS" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = C3C100000000000000000002; + packageReferences = ( + C3C100000000000000000018 /* XCLocalSwiftPackageReference ".." */, + C3C100000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */, + ); + productRefGroup = C3C100000000000000000003 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + C3C100000000000000000011 /* ShoeGazeBuilderiOS */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + C3C100000000000000000010 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + C3C10000000000000000000E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C3C100000000000000000009 /* ShoeGazeBuilderiOSApp.swift in Sources */, + C3C10000000000000000000A /* ShoeGazeBuilderiOSAppModel.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + C3C100000000000000000013 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CODE_SIGNING_REQUIRED = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + DEVELOPMENT_TEAM = ""; + INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + C3C100000000000000000014 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CODE_SIGNING_REQUIRED = NO; + DEVELOPMENT_TEAM = ""; + INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + C3C100000000000000000016 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + C3C100000000000000000017 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + C3C100000000000000000012 /* Build configuration list for PBXNativeTarget "ShoeGazeBuilderiOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C3C100000000000000000013 /* Debug */, + C3C100000000000000000014 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C3C100000000000000000015 /* Build configuration list for PBXProject "ShoeGazeBuilderiOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C3C100000000000000000016 /* Debug */, + C3C100000000000000000017 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + C3C100000000000000000018 /* XCLocalSwiftPackageReference ".." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCRemoteSwiftPackageReference section */ + C3C100000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 1.2.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + C3C10000000000000000001A /* LyrebirdShoeGaze */ = { + isa = XCSwiftPackageProductDependency; + package = C3C100000000000000000018 /* XCLocalSwiftPackageReference ".." */; + productName = LyrebirdShoeGaze; + }; + C3C10000000000000000001B /* LyrebirdShoeGazeUI */ = { + isa = XCSwiftPackageProductDependency; + package = C3C100000000000000000018 /* XCLocalSwiftPackageReference ".." */; + productName = LyrebirdShoeGazeUI; + }; + C3C10000000000000000001C /* LyrebirdUI */ = { + isa = XCSwiftPackageProductDependency; + package = C3C100000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */; + productName = LyrebirdUI; + }; + C3C10000000000000000001E /* Lyrebird */ = { + isa = XCSwiftPackageProductDependency; + package = C3C100000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */; + productName = Lyrebird; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = C3C100000000000000000001 /* Project object */; +} diff --git a/Demo/ShoeGazeBuilderiOS.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demo/ShoeGazeBuilderiOS.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..82a587c --- /dev/null +++ b/Demo/ShoeGazeBuilderiOS.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,33 @@ +{ + "originHash" : "cfdd71f4b32d744c862bbe26a8265d75aa9e906275b0fb1b63575b7d68be1b6a", + "pins" : [ + { + "identity" : "linenoise-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/andybest/linenoise-swift", + "state" : { + "revision" : "afc897c02b030af7333105c4fedcd843a8339238", + "version" : "0.0.3" + } + }, + { + "identity" : "lyrebird", + "kind" : "remoteSourceControl", + "location" : "https://realizedsound.mooo.com/josh/Lyrebird", + "state" : { + "revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c", + "version" : "1.2.0" + } + }, + { + "identity" : "nimble", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Quick/Nimble.git", + "state" : { + "revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0", + "version" : "7.3.4" + } + } + ], + "version" : 3 +} diff --git a/Demo/ShoeGazeBuilderiOS.xcodeproj/xcshareddata/xcschemes/ShoeGazeBuilderiOS.xcscheme b/Demo/ShoeGazeBuilderiOS.xcodeproj/xcshareddata/xcschemes/ShoeGazeBuilderiOS.xcscheme new file mode 100644 index 0000000..3fb8344 --- /dev/null +++ b/Demo/ShoeGazeBuilderiOS.xcodeproj/xcshareddata/xcschemes/ShoeGazeBuilderiOS.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demo/ShoeGazeBuilderiOS/Info.plist b/Demo/ShoeGazeBuilderiOS/Info.plist new file mode 100644 index 0000000..6a23071 --- /dev/null +++ b/Demo/ShoeGazeBuilderiOS/Info.plist @@ -0,0 +1,46 @@ + + + + + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + NSHumanReadableCopyright + Copyright © 2026 Realized Sound. All rights reserved. + NSMicrophoneUsageDescription + ShoeGaze Builder can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode. + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + + UILaunchScreen + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift new file mode 100644 index 0000000..78f4d3a --- /dev/null +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift @@ -0,0 +1,33 @@ +// ShoeGazeBuilderiOSApp.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdShoeGazeUI + +/// iOS entry point for the ShoeGaze Builder. +/// +/// Holds the `ShoeGazeBuilderiOSAppModel` as `@State` so it is created once and owned for the +/// lifetime of the app. The audio engine is **not** started automatically — the user presses +/// Start in ``ShoeGazeBuilderView``. The engine is stopped when the view disappears. +/// +/// ``ShoeGazeBuilderView`` manages its own scroll regions (palette + builder), so it is hosted +/// directly rather than wrapped in an outer `ScrollView`. +@main +struct ShoeGazeBuilderiOSApp: App { + + @State private var model: ShoeGazeBuilderiOSAppModel = ShoeGazeBuilderiOSAppModel() + + var body: some Scene { + WindowGroup { + NavigationStack { + ShoeGazeBuilderView(shoeGaze: model.shoeGaze) + .navigationTitle("ShoeGaze Builder") + .navigationBarTitleDisplayMode(.inline) + } + .onDisappear { model.stop() } + } + } +} diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift new file mode 100644 index 0000000..bf5a257 --- /dev/null +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift @@ -0,0 +1,79 @@ +// ShoeGazeBuilderiOSAppModel.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import AVFoundation +import Observation +import LyrebirdSynth +import LyrebirdShoeGaze + +/// Observable model owning the `SynthesisEngine` and `ShoeGaze` session for the iOS builder. +/// +/// `AVAudioSession` is activated at init so the hardware sample rate is known before the engine +/// is constructed (iOS devices typically lock to 48 000 Hz). The session is seeded with one board +/// holding a single pedal so the builder opens with an audible starting point; the user adds / +/// removes / reorders pedals from the palette. Input defaults to `.testLoop`, so no microphone +/// permission is required to start. +@Observable +@MainActor +final class ShoeGazeBuilderiOSAppModel { + + // MARK: - Engine configuration constants + + private static let blockSize: Int = 512 + private static let outputChannels: Int = 2 + private static let numAudioBuses: Int = 256 + private static let seedPedalType: String = "Overdrive" + + // MARK: - Owned objects + + /// The active ShoeGaze builder session. + private(set) var shoeGaze: ShoeGaze + + private let engine: SynthesisEngine + + // MARK: - Init + + init() { + let session: AVAudioSession = AVAudioSession.sharedInstance() + do { + try session.setCategory(.playAndRecord, + mode: .default, + options: [.defaultToSpeaker, .allowBluetoothHFP]) + try session.setActive(true) + } catch { + // Surface the failure: the engine is built from `session.sampleRate` below, which may + // report a stale/default rate if activation failed. + print("[ShoeGazeBuilderiOS] AVAudioSession setup failed: \(error)") + } + let sampleRate: Double = session.sampleRate + + let eng: SynthesisEngine = SynthesisEngine( + blockSize: ShoeGazeBuilderiOSAppModel.blockSize, + sampleRate: sampleRate, + numOutputChannels: ShoeGazeBuilderiOSAppModel.outputChannels, + numInputChannels: 0, + numAudioBuses: ShoeGazeBuilderiOSAppModel.numAudioBuses, + driver: iOSAudioDriver() + ) + self.engine = eng + self.shoeGaze = ShoeGaze(engine: eng) + + do { + let board: PedalBoard = try shoeGaze.addBoard() + board.label = "Board 1" + try shoeGaze.appendPedal(type: ShoeGazeBuilderiOSAppModel.seedPedalType, to: board) + } catch { + print("[ShoeGazeBuilderiOS] seed board failed: \(error)") + } + } + + // MARK: - Transport + + /// Stops the audio engine. Call from `.onDisappear`. + func stop() { + engine.stop() + } +} diff --git a/ShoeGaze.xcworkspace/contents.xcworkspacedata b/ShoeGaze.xcworkspace/contents.xcworkspacedata index c7c9596..0770dba 100644 --- a/ShoeGaze.xcworkspace/contents.xcworkspacedata +++ b/ShoeGaze.xcworkspace/contents.xcworkspacedata @@ -10,4 +10,10 @@ + + + + diff --git a/Sources/LyrebirdShoeGaze/BoardSegment.swift b/Sources/LyrebirdShoeGaze/BoardSegment.swift index 7e011a7..b6eb0a4 100644 --- a/Sources/LyrebirdShoeGaze/BoardSegment.swift +++ b/Sources/LyrebirdShoeGaze/BoardSegment.swift @@ -10,7 +10,12 @@ /// `PedalBoard` records these as pedals and split regions are added, so a board can be /// serialized and rebuilt faithfully rather than as a flat pedal list. Branch pedals live /// inside their section objects, not as separate segments. -enum BoardSegment { +/// +/// Public so a UI can walk a board's live structure in signal-flow order (each element carries +/// the live `Pedal` / section object). The index of a segment within `PedalBoard.orderedSegments` +/// matches its index in `captureState().segments`, which is the region index used by the +/// lane-addressed edit API (see ``PedalLane``). +public enum BoardSegment { /// A single linear pedal in the main chain. case pedal(Pedal) diff --git a/Sources/LyrebirdShoeGaze/Input/InputSource.swift b/Sources/LyrebirdShoeGaze/Input/InputSource.swift index 4bedcb9..e5feded 100644 --- a/Sources/LyrebirdShoeGaze/Input/InputSource.swift +++ b/Sources/LyrebirdShoeGaze/Input/InputSource.swift @@ -14,7 +14,7 @@ import LyrebirdSynth /// the zero-based hardware input channel index (`0` = first input). It maps to engine /// audio-bus index `numOutputChannels + channel` (hardware input buses follow the /// output buses). Requires the engine to be created with `numInputChannels > channel`. -public enum InputSource { +public enum InputSource: Equatable { /// Synthesized test signal — no hardware required. case testLoop /// Live hardware input from the given zero-based input channel. The engine must be diff --git a/Sources/LyrebirdShoeGaze/PedalBoard.swift b/Sources/LyrebirdShoeGaze/PedalBoard.swift index ae3e3af..dad6cf5 100644 --- a/Sources/LyrebirdShoeGaze/PedalBoard.swift +++ b/Sources/LyrebirdShoeGaze/PedalBoard.swift @@ -122,8 +122,10 @@ public final class PedalBoard { private var branchChains: [BranchChain] = [] /// Ordered signal-chain segments (pedals + split regions) in signal-flow order. Used to - /// capture full board topology for serialization. Maintained by `add`/`split`/`splitStereo`. - private(set) var orderedSegments: [BoardSegment] = [] + /// capture full board topology for serialization and to drive signal-flow UIs. Maintained by + /// `add`/`split`/`splitStereo`. A segment's index here matches its index in + /// `captureState().segments` — the region index used by the lane-addressed edit API. + public private(set) var orderedSegments: [BoardSegment] = [] // MARK: - Init diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalLane.swift b/Sources/LyrebirdShoeGaze/Presets/PedalLane.swift new file mode 100644 index 0000000..ffecbe2 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/PedalLane.swift @@ -0,0 +1,37 @@ +// PedalLane.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Addresses where a linear pedal edit applies: the board's main chain, or one branch of a +/// split region (stereo split or parallel section). +/// +/// `region` is the index of the region's segment within the board's top-level segment list +/// (`board.captureState().segments`). For a `.stereoSplit` segment, `.left`/`.right` map to its +/// left/right branches; for a `.parallel` segment they map to branch A/B. +public enum PedalLane: Equatable, Sendable { + + /// The board's top-level linear chain (the `.pedal` segments). + case main + + /// The left branch (stereo) / branch A (parallel) of the region segment at `region`. + case left(region: Int) + + /// The right branch (stereo) / branch B (parallel) of the region segment at `region`. + case right(region: Int) + + /// The region segment index this lane targets, or `nil` for ``main``. + public var regionIndex: Int? { + switch self { + case .main: return nil + case .left(let region), .right(let region): return region + } + } + + /// `true` for the left / A branch; `false` for the right / B branch. `false` for ``main``. + public var isLeftBranch: Bool { + if case .left = self { return true } + return false + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift new file mode 100644 index 0000000..4c956ef --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift @@ -0,0 +1,302 @@ +// ShoeGaze+Edit.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +extension ShoeGaze { + + // MARK: - Linear pedal editing + + /// Appends a pedal of the given type to the end of a lane. + /// + /// The pedal is created at its constructor defaults (empty saved parameters) and the board is + /// rebuilt via ``rebuildBoard(_:from:)``. For ``PedalLane/main`` the pedal joins the top-level + /// linear chain (after the last `.pedal` segment), preserving any branch regions; for a branch + /// lane it is appended to that branch of the addressed region segment. + /// + /// - Important: Editing rebuilds the board through the same path as preset load; safe on a + /// running engine with at most one block of glitch (see ``rebuildBoard(_:from:)``). + /// + /// - Parameters: + /// - type: The pedal's `displayName`, e.g. `"Overdrive"`. Must be a key in `PedalRegistry.builtIn`. + /// - board: The board to edit. Must have been returned by `addBoard()` on this instance. + /// - lane: Where to append. Defaults to ``PedalLane/main``. + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.unknownPedalType`, `.notABranchRegion`, `.pedalIndexOutOfRange`, or + /// any error from ``rebuildBoard(_:from:)``. + @discardableResult + public func appendPedal( + type: String, + to board: PedalBoard, + lane: PedalLane = .main + ) throws -> PedalBoard { + guard PedalRegistry.builtIn[type] != nil else { + throw ShoeGazeError.unknownPedalType(type) + } + let newState: PedalState = PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0) + + var segments: [BoardSegmentState] = board.captureState().segments + switch lane { + case .main: + // Insert after the last linear pedal so the new pedal joins the linear chain rather + // than landing after a trailing split region; append to the end if there are none. + let pedalPositions: [Int] = linearPedalSegmentIndices(segments) + if let lastPedalIndex: Int = pedalPositions.last { + segments.insert(.pedal(newState), at: lastPedalIndex + 1) + } else { + segments.append(.pedal(newState)) + } + case .left, .right: + try mutateBranch(&segments, lane: lane) { branch in + branch.append(newState) + } + } + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + /// Removes the pedal at `index` within a lane. + /// + /// `index` addresses the lane's own pedal order (`board.pedals` for ``PedalLane/main``; the + /// branch's pedal list for a branch lane). The board is rebuilt, preserving everything else. + /// + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.pedalIndexOutOfRange`, `.notABranchRegion`, or any rebuild error. + @discardableResult + public func removePedal( + at index: Int, + from board: PedalBoard, + lane: PedalLane = .main + ) throws -> PedalBoard { + var segments: [BoardSegmentState] = board.captureState().segments + switch lane { + case .main: + let pedalPositions: [Int] = linearPedalSegmentIndices(segments) + guard index >= 0 && index < pedalPositions.count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: pedalPositions.count) + } + segments.remove(at: pedalPositions[index]) + case .left, .right: + try mutateBranch(&segments, lane: lane) { branch in + guard index >= 0 && index < branch.count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: branch.count) + } + branch.remove(at: index) + } + } + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + /// Moves the pedal at `sourceIndex` to `destinationIndex` within a lane. + /// + /// Indices address the lane's own pedal order. `destinationIndex` follows SwiftUI + /// `List.onMove` semantics (insert-before index in the original coordinate space). + /// + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.pedalIndexOutOfRange`, `.notABranchRegion`, or any rebuild error. + @discardableResult + public func movePedal( + from sourceIndex: Int, + to destinationIndex: Int, + in board: PedalBoard, + lane: PedalLane = .main + ) throws -> PedalBoard { + var segments: [BoardSegmentState] = board.captureState().segments + switch lane { + case .main: + try moveMainPedal(&segments, from: sourceIndex, to: destinationIndex) + case .left, .right: + try mutateBranch(&segments, lane: lane) { branch in + try Self.moveWithinArray(&branch, from: sourceIndex, to: destinationIndex) + } + } + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + // MARK: - Branch regions + + /// Appends an empty stereo split region (two independently authored L/R lanes) to the board. + /// + /// Requires the board's tail to be mono — a stereo split fans a mono signal into two branches + /// (see `PedalBoard.splitStereo()`). Add pedals to each lane with `appendPedal(... lane:)`. + /// + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.cannotSplitStereoChain` when the tail is already stereo; any + /// rebuild error. + @discardableResult + public func appendStereoSplit(to board: PedalBoard) throws -> PedalBoard { + guard board.width == 1 else { throw ShoeGazeError.cannotSplitStereoChain } + var segments: [BoardSegmentState] = board.captureState().segments + segments.append(.stereoSplit(StereoSplitState(left: [], right: [], route: .stereo))) + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + /// Appends an empty parallel section (two A/B branches summed back to one signal) to the board. + /// + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: Any error from ``rebuildBoard(_:from:)``. + @discardableResult + public func appendParallelSplit(to board: PedalBoard) throws -> PedalBoard { + var segments: [BoardSegmentState] = board.captureState().segments + segments.append(.parallel(ParallelSectionState(branchA: [], branchB: [], mode: .both))) + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + /// Appends a merge-to-mono node, collapsing a stereo tail back to mono. + /// + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.cannotMergeMonoChain` when the tail is already mono; any rebuild error. + @discardableResult + public func appendMergeToMono(to board: PedalBoard) throws -> PedalBoard { + guard board.width == 2 else { throw ShoeGazeError.cannotMergeMonoChain } + var segments: [BoardSegmentState] = board.captureState().segments + segments.append(.mergeToMono) + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + /// Removes the top-level segment (a linear pedal, a split region, or a merge node) at + /// `topLevelIndex` — its index within `board.captureState().segments`. + /// + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.pedalIndexOutOfRange` when the index is invalid; any rebuild error. + @discardableResult + public func removeSegment(at topLevelIndex: Int, from board: PedalBoard) throws -> PedalBoard { + var segments: [BoardSegmentState] = board.captureState().segments + guard topLevelIndex >= 0 && topLevelIndex < segments.count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: topLevelIndex, count: segments.count) + } + segments.remove(at: topLevelIndex) + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + // MARK: - Input source switching + + /// Changes the input source while preserving the current rig. + /// + /// `addBoard()` wires the input source (test loop or hardware pass-through) into each board at + /// creation time, so switching the source means recreating that wiring. This captures the full + /// rig, tears it down, sets `inputSource`, and rebuilds every board from the snapshot — + /// preserving labels, pedals, and split-region topology. No-op when the source is unchanged. + /// + /// - Important: Call with the engine **stopped** (the same teardown/rebuild caveat as + /// ``loadRig(from:)``). Switching to `.liveInput` requires enough engine input channels. + /// Reconstruction is atomic: on any failure the rig is torn down and the error rethrown. + /// + /// - Parameter newSource: The input source to switch to. + /// - Throws: `ShoeGazeError.liveInputRequiresInputChannels` / `inputChannelOutOfRange`, + /// `BusAllocatorError.noFreeBus`, or `EngineAddError` from board reconstruction. + public func setInputSource(_ newSource: InputSource) throws { + if newSource == inputSource { return } + + let snapshot: ShoeGazeState = captureState() + teardown() + inputSource = newSource + try rebuildAllBoards(from: snapshot) + } + + // MARK: - Helpers + + /// Returns the absolute indices, within `segments`, of the `.pedal` segments in order. The + /// position of an entry in the returned array is its linear pedal index (`board.pedals` order). + private func linearPedalSegmentIndices(_ segments: [BoardSegmentState]) -> [Int] { + var indices: [Int] = [] + for (absoluteIndex, segment) in segments.enumerated() { + if case .pedal = segment { indices.append(absoluteIndex) } + } + return indices + } + + /// Mutates the branch pedal list addressed by `lane` in place, rebuilding the region's enum + /// case. Throws `notABranchRegion` if the addressed segment is not a split/parallel region. + private func mutateBranch( + _ segments: inout [BoardSegmentState], + lane: PedalLane, + _ transform: (inout [PedalState]) throws -> Void + ) throws { + // Callers only reach this for `.left`/`.right`; `.main` has no region and is handled + // separately. Treat a `.main` lane here as a programming error rather than a silent no-op. + guard let region: Int = lane.regionIndex else { + assertionFailure("mutateBranch called with the .main lane") + return + } + guard region >= 0 && region < segments.count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: region, count: segments.count) + } + let isLeft: Bool = lane.isLeftBranch + switch segments[region] { + case .stereoSplit(let state): + var left: [PedalState] = state.left + var right: [PedalState] = state.right + if isLeft { try transform(&left) } else { try transform(&right) } + segments[region] = .stereoSplit(StereoSplitState(left: left, right: right, route: state.route)) + case .parallel(let state): + var branchA: [PedalState] = state.branchA + var branchB: [PedalState] = state.branchB + if isLeft { try transform(&branchA) } else { try transform(&branchB) } + segments[region] = .parallel( + ParallelSectionState(branchA: branchA, branchB: branchB, mode: state.mode) + ) + default: + throw ShoeGazeError.notABranchRegion(index: region) + } + } + + /// Moves a `.pedal` within the top-level chain, preserving interleaved branch regions. + private func moveMainPedal( + _ segments: inout [BoardSegmentState], + from sourceIndex: Int, + to destinationIndex: Int + ) throws { + let pedalPositions: [Int] = linearPedalSegmentIndices(segments) + let pedalCount: Int = pedalPositions.count + guard sourceIndex >= 0 && sourceIndex < pedalCount else { + throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: pedalCount) + } + guard destinationIndex >= 0 && destinationIndex <= pedalCount else { + throw ShoeGazeError.pedalIndexOutOfRange(index: destinationIndex, count: pedalCount) + } + + let movedSegment: BoardSegmentState = segments.remove(at: pedalPositions[sourceIndex]) + let remainingPositions: [Int] = linearPedalSegmentIndices(segments) + // SwiftUI `toOffset` is an insert-before index in the original space; after removing the + // source, slots above it shift down by one. + let adjustedDestination: Int = destinationIndex > sourceIndex + ? destinationIndex - 1 + : destinationIndex + let insertionAbsolute: Int + if adjustedDestination < remainingPositions.count { + insertionAbsolute = remainingPositions[adjustedDestination] + } else if let lastPedalAbsolute: Int = remainingPositions.last { + // Moving to the end of the linear chain: land immediately after the last linear pedal, + // BEFORE any trailing routing nodes (a stereo split or mergeToMono), so a pedal never + // jumps past a width-conversion node. Mirrors `appendPedal`'s insert-after-last rule. + insertionAbsolute = lastPedalAbsolute + 1 + } else { + insertionAbsolute = segments.count + } + segments.insert(movedSegment, at: insertionAbsolute) + } + + /// Moves an element within a contiguous array using SwiftUI `List.onMove` (`toOffset`) semantics. + private static func moveWithinArray( + _ array: inout [T], + from sourceIndex: Int, + to destinationIndex: Int + ) throws { + let count: Int = array.count + guard sourceIndex >= 0 && sourceIndex < count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: count) + } + guard destinationIndex >= 0 && destinationIndex <= count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: destinationIndex, count: count) + } + // Manual move with SwiftUI `toOffset` semantics (insert-before in the original space): + // remove the source, then insert at the destination shifted down by one when it was past + // the source. Avoids depending on SwiftUI's `move(fromOffsets:toOffset:)` in the core module. + let element: T = array.remove(at: sourceIndex) + let insertionIndex: Int = destinationIndex > sourceIndex ? destinationIndex - 1 : destinationIndex + array.insert(element, at: insertionIndex) + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift index 3229518..cc25a0f 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift @@ -31,10 +31,65 @@ extension ShoeGaze { /// - Parameter url: Destination file URL. The directory must already exist. /// - Throws: Any error from `JSONEncoder` or `Data.write(to:options:)`. public func saveRig(to url: URL) throws { + try rigData().write(to: url, options: .atomic) + } + + /// Encodes the current rig to pretty-printed JSON `Data`. + /// + /// Same payload `saveRig(to:)` writes to disk; exposed for callers that need the bytes + /// directly (e.g. a SwiftUI `fileExporter` `FileDocument` on iOS). + /// + /// - Returns: The encoded `ShoeGazeState` JSON. + /// - Throws: Any error from `JSONEncoder`. + public func rigData() throws -> Data { let encoder: JSONEncoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] - let data: Data = try encoder.encode(captureState()) - try data.write(to: url, options: .atomic) + return try encoder.encode(captureState()) + } + + /// Loads a rig from in-memory JSON `Data` and rebuilds the engine graph. + /// + /// Identical to ``loadRig(from:)`` but reads from `Data` rather than a file URL — convenient + /// for a SwiftUI `fileImporter` that has already read the document, or for tests. + /// + /// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``. + /// - Parameter data: JSON produced by ``rigData()`` / ``saveRig(to:)``. + /// - Throws: `JSONDecoder` errors, `PresetError.unsupportedVersion`, or any board-build error. + public func loadRig(from data: Data) throws { + let decoder: JSONDecoder = JSONDecoder() + let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data) + guard state.version <= presetFormatVersion else { + throw PresetError.unsupportedVersion(state.version) + } + + teardown() + try rebuildAllBoards(from: state) + } + + /// Rebuilds every board from a snapshot with all-or-nothing semantics. + /// + /// The caller is responsible for tearing down any existing rig first. On any failure while + /// reconstructing a board, the partially-built rig is torn down and the error rethrown, so + /// callers never observe a half-built rig — a board that fails on iteration N does not leave + /// boards `0..=` the board's linear pedal count. `index` is the offending index; `count` + /// is the number of linear pedals on the board. + case pedalIndexOutOfRange(index: Int, count: Int) + + /// Thrown by `appendStereoSplit(to:)` when the board's tail is already stereo (width 2). A + /// stereo split fans a mono tail into two branches; narrow the chain with a `Merge to Mono` + /// first. (See `PedalBoard.splitStereo()`.) + case cannotSplitStereoChain + + /// Thrown by `appendMergeToMono(to:)` when the board's tail is already mono (width 1) — there + /// is no stereo signal to collapse. + case cannotMergeMonoChain + + /// Thrown by the lane-addressed edit API when the segment at the given top-level index is not a + /// branch region (stereo split or parallel section). `index` is the offending segment index. + case notABranchRegion(index: Int) + // MARK: - LocalizedError public var errorDescription: String? { @@ -64,6 +86,16 @@ public enum ShoeGazeError: Error, LocalizedError, Equatable, Sendable { return "ShoeGaze: could not open recording file '\(url.lastPathComponent)'." case .stereoWidthExceeded: return "PedalBoard: chain is already stereo (width 2); cannot add another widener. Use mergeToMono() first." + case .unknownPedalType(let type): + return "ShoeGaze: '\(type)' is not a known pedal type; cannot add it to the board." + case .pedalIndexOutOfRange(let index, let count): + return "ShoeGaze: pedal index \(index) is out of range; the board has \(count) linear pedal(s)." + case .cannotSplitStereoChain: + return "ShoeGaze: cannot add a stereo split; the chain is already stereo. Merge to mono first." + case .cannotMergeMonoChain: + return "ShoeGaze: the chain is already mono; there is no stereo signal to merge." + case .notABranchRegion(let index): + return "ShoeGaze: segment \(index) is not a branch region (stereo split or parallel section)." } } } diff --git a/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift b/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift new file mode 100644 index 0000000..0a316b4 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift @@ -0,0 +1,434 @@ +// BoardFlowView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +/// A left→right signal-flow view of one `PedalBoard`: live pedal cards joined by connector lines, +/// with split regions shown as two stacked lanes you can fill independently. +/// +/// Binds to `ShoeGaze` (`@Observable`) and reads the live board via `shoeGaze.boards[boardIndex]`. +/// All edits go through the lane-addressed API (`appendPedal`/`removePedal`/`movePedal`, +/// `appendStereoSplit`/`appendParallelSplit`/`appendMergeToMono`/`removeSegment`), which rebuild +/// the board in place — so the index is the stable anchor and the `PedalBoard` reference is never +/// cached. Region segments are addressed by their index in `board.orderedSegments`. +/// +/// Interaction: +/// - Drag a palette pedal (`"add:"`) onto a lane to append it there; tap a palette pedal to +/// append to the main chain. +/// - Drag a card onto another card in the same lane to reorder; the corner trash removes it. +/// - Connector lines render mono (single) or stereo (double) based on the running channel width. +/// +/// - Parameters: +/// - shoeGaze: The `ShoeGaze` manager that owns the board. +/// - boardIndex: Index into `shoeGaze.boards`. Renders a placeholder when out of range. +public struct BoardFlowView: View { + + // MARK: - Constants + + private static let placeholderOpacity: Double = 0.55 + private static let stageSpacing: CGFloat = 0 + private static let connectorWidth: CGFloat = 26 + private static let connectorThickness: CGFloat = 2 + private static let stereoLineGap: CGFloat = 6 + private static let laneSpacing: CGFloat = 10 + private static let laneMinWidth: CGFloat = 240 + private static let laneLabelWidth: CGFloat = 22 + private static let regionPadding: CGFloat = 10 + private static let regionCornerRadius: CGFloat = 12 + private static let regionBrightness: Double = 0.09 + private static let regionBorderOpacity: Double = 0.35 + private static let trashPadding: CGFloat = 6 + private static let trashOpacity: Double = 0.8 + private static let badgeFontSize: CGFloat = 11 + private static let badgeOpacity: Double = 0.6 + private static let dropHighlightWidth: CGFloat = 2 + private static let emptyLaneOpacity: Double = 0.4 + + /// Signal-path accent (the pink/magenta connector colour). + private static let flowColor: Color = Color(red: 0.92, green: 0.32, blue: 0.70) + + // MARK: - Properties + + private let shoeGaze: ShoeGaze + private let boardIndex: Int + + /// Identifier of the lane/card currently hovered as a drop target, for highlight. + @State private var dropTarget: String? + + public init(shoeGaze: ShoeGaze, boardIndex: Int) { + self.shoeGaze = shoeGaze + self.boardIndex = boardIndex + } + + // MARK: - Body + + public var body: some View { + if boardIndex < 0 || boardIndex >= shoeGaze.boards.count { + Text("No board at index \(boardIndex).") + .foregroundStyle(Color.secondary.opacity(BoardFlowView.placeholderOpacity)) + } else { + let board: PedalBoard = shoeGaze.boards[boardIndex] + flow(board: board) + } + } + + private func flow(board: PedalBoard) -> some View { + let stages: [StageModel] = stageModels(board: board) + return ScrollView([.horizontal, .vertical], showsIndicators: true) { + HStack(alignment: .center, spacing: BoardFlowView.stageSpacing) { + endpoint("IN") + ForEach(stages) { stage in + connector(stereo: stage.stereoIn) + stageView(stage) + } + connector(stereo: board.width == 2) + endpoint(board.width == 2 ? "OUT ⇒" : "OUT") + } + .padding(.vertical, BoardFlowView.regionPadding) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + // MARK: - Stage model + + /// View-model for one top-level segment: its index (the lane region index), the live segment, + /// the main-chain linear index for `.pedal`, and the channel width entering the stage. + private struct StageModel: Identifiable { + let id: Int + let segmentIndex: Int + let segment: BoardSegment + let linearIndex: Int? + let stereoIn: Bool + } + + /// Walks `board.orderedSegments`, tagging each with a linear pedal index and the running width. + private func stageModels(board: PedalBoard) -> [StageModel] { + var models: [StageModel] = [] + var linearCounter: Int = 0 + var stereo: Bool = false + for (index, segment) in board.orderedSegments.enumerated() { + let stereoIn: Bool = stereo + var linearIndex: Int? + switch segment { + case .pedal(let pedal): + linearIndex = linearCounter + linearCounter += 1 + if pedal.channelKind != .mono { stereo = true } + case .stereoSplit: + stereo = true + case .parallel: + break + case .mergeToMono: + stereo = false + } + models.append( + StageModel( + id: index, + segmentIndex: index, + segment: segment, + linearIndex: linearIndex, + stereoIn: stereoIn + ) + ) + } + return models + } + + // MARK: - Stage dispatch + + @ViewBuilder + private func stageView(_ stage: StageModel) -> some View { + switch stage.segment { + case .pedal(let pedal): + mainPedalCard(pedal: pedal, linearIndex: stage.linearIndex ?? 0) + case .stereoSplit(let section): + regionNode( + title: "STEREO SPLIT", + segmentIndex: stage.segmentIndex, + leftLabel: "L", + rightLabel: "R", + leftPedals: section.left.pedals, + rightPedals: section.right.pedals, + control: AnyView(StereoRouteControlView(section: section)) + ) + case .parallel(let section): + regionNode( + title: "PARALLEL", + segmentIndex: stage.segmentIndex, + leftLabel: "A", + rightLabel: "B", + leftPedals: section.branchA.pedals, + rightPedals: section.branchB.pedals, + control: AnyView(SplitterView(splitter: section.splitter)) + ) + case .mergeToMono: + mergeNode(segmentIndex: stage.segmentIndex) + } + } + + // MARK: - Connectors + + private func connector(stereo: Bool) -> some View { + ZStack { + if stereo { + VStack(spacing: BoardFlowView.stereoLineGap) { + line + line + } + } else { + line + } + } + .frame(width: BoardFlowView.connectorWidth) + } + + private var line: some View { + Capsule() + .fill(BoardFlowView.flowColor) + .frame(height: BoardFlowView.connectorThickness) + } + + private func endpoint(_ text: String) -> some View { + Text(text) + .font(.system(size: BoardFlowView.badgeFontSize, weight: .semibold).monospaced()) + .foregroundStyle(BoardFlowView.flowColor) + } + + // MARK: - Main pedal card + + private func mainPedalCard(pedal: Pedal, linearIndex: Int) -> some View { + let payload: String = "movemain:\(linearIndex)" + return PedalView(pedal: pedal) + .overlay(alignment: .topTrailing) { trashButton { deleteSegment(forLinear: linearIndex) } } + .overlay { dropOutline(active: dropTarget == payload) } + .draggable(payload) + .dropDestination(for: String.self) { items, _ in + handleMainDrop(items, ontoLinear: linearIndex) + } isTargeted: { hovering in + dropTarget = hovering ? payload : (dropTarget == payload ? nil : dropTarget) + } + } + + // MARK: - Region node (stereo split / parallel) + + private func regionNode( + title: String, + segmentIndex: Int, + leftLabel: String, + rightLabel: String, + leftPedals: [Pedal], + rightPedals: [Pedal], + control: AnyView + ) -> some View { + VStack(alignment: .leading, spacing: BoardFlowView.laneSpacing) { + HStack(spacing: 8) { + Text(title) + .font(.system(size: BoardFlowView.badgeFontSize, weight: .semibold)) + .foregroundStyle(BoardFlowView.flowColor) + Spacer() + control + trashButton { removeSegment(at: segmentIndex) } + } + laneRow(label: leftLabel, pedals: leftPedals, lane: .left(region: segmentIndex)) + laneRow(label: rightLabel, pedals: rightPedals, lane: .right(region: segmentIndex)) + } + .padding(BoardFlowView.regionPadding) + .background( + RoundedRectangle(cornerRadius: BoardFlowView.regionCornerRadius) + .fill(Color(white: BoardFlowView.regionBrightness)) + .overlay( + RoundedRectangle(cornerRadius: BoardFlowView.regionCornerRadius) + .stroke(BoardFlowView.flowColor.opacity(BoardFlowView.regionBorderOpacity), lineWidth: 1) + ) + ) + } + + private func laneRow(label: String, pedals: [Pedal], lane: PedalLane) -> some View { + let laneID: String = "lane:\(lane.regionIndex ?? -1):\(lane.isLeftBranch ? "L" : "R")" + return HStack(alignment: .center, spacing: BoardFlowView.stageSpacing) { + Text(label) + .font(.system(size: BoardFlowView.badgeFontSize, weight: .bold).monospaced()) + .foregroundStyle(Color.white.opacity(BoardFlowView.badgeOpacity)) + .frame(width: BoardFlowView.laneLabelWidth) + if pedals.isEmpty { + Text("drop a pedal here") + .font(.caption) + .foregroundStyle(Color.white.opacity(BoardFlowView.emptyLaneOpacity)) + .frame(minWidth: BoardFlowView.laneMinWidth, alignment: .leading) + .padding(.vertical, BoardFlowView.regionPadding) + } else { + ForEach(Array(pedals.enumerated()), id: \.offset) { pair in + connector(stereo: false) + branchPedalCard(pedal: pair.element, lane: lane, index: pair.offset) + } + } + } + .frame(minWidth: BoardFlowView.laneMinWidth, alignment: .leading) + .overlay { dropOutline(active: dropTarget == laneID) } + .dropDestination(for: String.self) { items, _ in + handleLaneDrop(items, lane: lane) + } isTargeted: { hovering in + dropTarget = hovering ? laneID : (dropTarget == laneID ? nil : dropTarget) + } + } + + private func branchPedalCard(pedal: Pedal, lane: PedalLane, index: Int) -> some View { + let payload: String = "movebranch:\(lane.regionIndex ?? -1):\(lane.isLeftBranch ? "L" : "R"):\(index)" + return PedalView(pedal: pedal) + .overlay(alignment: .topTrailing) { + trashButton { removePedal(at: index, lane: lane) } + } + .overlay { dropOutline(active: dropTarget == payload) } + .draggable(payload) + .dropDestination(for: String.self) { items, _ in + handleBranchCardDrop(items, lane: lane, ontoIndex: index) + } isTargeted: { hovering in + dropTarget = hovering ? payload : (dropTarget == payload ? nil : dropTarget) + } + } + + private func mergeNode(segmentIndex: Int) -> some View { + VStack(spacing: 4) { + Text("⇒ MONO") + .font(.system(size: BoardFlowView.badgeFontSize, weight: .semibold)) + .foregroundStyle(BoardFlowView.flowColor) + trashButton { removeSegment(at: segmentIndex) } + } + .padding(BoardFlowView.regionPadding) + .background( + RoundedRectangle(cornerRadius: BoardFlowView.regionCornerRadius) + .stroke(BoardFlowView.flowColor.opacity(BoardFlowView.regionBorderOpacity), lineWidth: 1) + ) + } + + // MARK: - Shared bits + + private func trashButton(_ action: @escaping () -> Void) -> some View { + Button(role: .destructive, action: action) { + Image(systemName: "trash.circle.fill") + .foregroundStyle(Color.white.opacity(BoardFlowView.trashOpacity)) + } + .buttonStyle(.plain) + .padding(BoardFlowView.trashPadding) + } + + @ViewBuilder + private func dropOutline(active: Bool) -> some View { + if active { + RoundedRectangle(cornerRadius: 8) + .stroke(BoardFlowView.flowColor, lineWidth: BoardFlowView.dropHighlightWidth) + } + } + + // MARK: - Drop handling + + private func parse(_ items: [String]) -> String? { items.first } + + private func handleMainDrop(_ items: [String], ontoLinear: Int) -> Bool { + dropTarget = nil + guard let payload: String = parse(items) else { return false } + if let type: String = payload.afterPrefix("add:") { + append(type: type, lane: .main) + return true + } + if let src: Int = payload.afterPrefix("movemain:").flatMap(Int.init) { + reorderMain(from: src, onto: ontoLinear) + return true + } + return false + } + + private func handleLaneDrop(_ items: [String], lane: PedalLane) -> Bool { + dropTarget = nil + guard let payload: String = parse(items), let type: String = payload.afterPrefix("add:") else { + return false + } + append(type: type, lane: lane) + return true + } + + private func handleBranchCardDrop(_ items: [String], lane: PedalLane, ontoIndex: Int) -> Bool { + dropTarget = nil + guard let payload: String = parse(items) else { return false } + // Guard against a payload minted before a rebuild changed the segment layout: the encoded + // region index must still point at a live region segment. + if let region: Int = lane.regionIndex, + let liveBoard: PedalBoard = board, + region >= liveBoard.orderedSegments.count { + return false + } + if let type: String = payload.afterPrefix("add:") { + append(type: type, lane: lane) + return true + } + // Reorder within the same lane only: "movebranch:::". + let parts: [Substring] = payload.split(separator: ":") + if parts.count == 4, parts[0] == "movebranch", + Int(parts[1]) == lane.regionIndex, + (parts[2] == "L") == lane.isLeftBranch, + let src: Int = Int(parts[3]) { + reorderBranch(from: src, onto: ontoIndex, lane: lane) + return true + } + return false + } + + // MARK: - Edit actions + + private var board: PedalBoard? { + guard boardIndex >= 0, boardIndex < shoeGaze.boards.count else { return nil } + return shoeGaze.boards[boardIndex] + } + + private func append(type: String, lane: PedalLane) { + guard let board: PedalBoard = board else { return } + do { _ = try shoeGaze.appendPedal(type: type, to: board, lane: lane) } + catch { print("[BoardFlowView] appendPedal failed: \(error)") } + } + + private func reorderMain(from source: Int, onto target: Int) { + guard source != target, let board: PedalBoard = board else { return } + // Convert "dropped ONTO the card at `target`" into movePedal's insert-before `toOffset`: + // a forward move lands after the target (target + 1); a backward move lands before it. + let destination: Int = source < target ? target + 1 : target + do { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: .main) } + catch { print("[BoardFlowView] movePedal(main) failed: \(error)") } + } + + private func reorderBranch(from source: Int, onto target: Int, lane: PedalLane) { + guard source != target, let board: PedalBoard = board else { return } + let destination: Int = source < target ? target + 1 : target + do { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: lane) } + catch { print("[BoardFlowView] movePedal(branch) failed: \(error)") } + } + + private func removePedal(at index: Int, lane: PedalLane) { + guard let board: PedalBoard = board else { return } + do { _ = try shoeGaze.removePedal(at: index, from: board, lane: lane) } + catch { print("[BoardFlowView] removePedal failed: \(error)") } + } + + private func deleteSegment(forLinear linearIndex: Int) { + // A main-chain pedal: remove by its lane index (preserves regions). + removePedal(at: linearIndex, lane: .main) + } + + private func removeSegment(at segmentIndex: Int) { + guard let board: PedalBoard = board else { return } + do { _ = try shoeGaze.removeSegment(at: segmentIndex, from: board) } + catch { print("[BoardFlowView] removeSegment failed: \(error)") } + } +} + +private extension String { + /// Returns the remainder after `prefix`, or `nil` if the string doesn't start with it. + func afterPrefix(_ prefix: String) -> String? { + guard hasPrefix(prefix) else { return nil } + return String(dropFirst(prefix.count)) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift new file mode 100644 index 0000000..ede1782 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift @@ -0,0 +1,184 @@ +// PedalPaletteView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdShoeGaze + +/// A vertical catalog of every available pedal plus a reference list of the routing/branching +/// options, sized to sit in a narrow left sidebar. +/// +/// The pedal rows are tappable: selecting one invokes `onAdd(type)` with the pedal's +/// `displayName`, which the host wires to `ShoeGaze.appendPedal(type:to:)`. The routing cards +/// (Parallel split, Stereo split, Chain router, Merge to mono) are informational only — they +/// describe the topologies the engine supports, which are built programmatically rather than via +/// linear add (see ``BoardBuilderView`` for the read-only display of existing branches). +/// +/// ## Usage +/// +/// ```swift +/// PedalPaletteView { type in +/// try? shoeGaze.appendPedal(type: type, to: board) +/// } +/// ``` +public struct PedalPaletteView: View { + + // MARK: - Layout constants + + private static let sectionSpacing: CGFloat = 14 + private static let rowSpacing: CGFloat = 6 + private static let titleFontSize: CGFloat = 12 + private static let titleOpacity: Double = 0.7 + private static let cardCornerRadius: CGFloat = 7 + private static let cardPaddingH: CGFloat = 10 + private static let cardPaddingV: CGFloat = 7 + private static let cardBorderOpacity: Double = 0.4 + private static let cardBorderWidth: CGFloat = 1 + private static let pedalCardBrightness: Double = 0.18 + private static let routingCardBrightness: Double = 0.1 + private static let routingCaptionOpacity: Double = 0.5 + private static let routingCaptionFontSize: CGFloat = 10 + private static let addGlyphOpacity: Double = 0.4 + + /// Preferred display order for the built-in pedals. Any registered pedal not listed here is + /// appended afterwards (sorted) so the palette never silently drops a newly added pedal. + private static let preferredOrder: [String] = [ + "Overdrive", "Compressor", "Fuzz", "Tremolo", "Phaser", "Modulation", + "Auto-Wah", "Mu-Tron", "Bass Octaver", "Octave Splitter", + "Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverb", + ] + + /// Routing/branching topologies the user can insert into the board. + private static let routingOptions: [(title: String, caption: String, action: RoutingAction)] = [ + ("Stereo Split", "L/R independent lanes", .stereoSplit), + ("Parallel Split", "A/B branches, mixed", .parallelSplit), + ("Merge to Mono", "Collapse stereo → mono", .mergeToMono), + ] + + /// Routing actions a host can perform from the palette. + public enum RoutingAction: Equatable, Sendable { + case stereoSplit + case parallelSplit + case mergeToMono + case chainRouter + } + + // MARK: - Properties + + private let onAdd: (String) -> Void + private let onRouting: (RoutingAction) -> Void + + // MARK: - Init + + /// Creates a pedal palette. + /// + /// - Parameters: + /// - onAdd: Invoked with a pedal's `displayName` when its row is tapped (append to main chain). + /// Rows are also `.draggable` carrying `"add:"` for drop-onto-lane targeting. + /// - onRouting: Invoked when a routing row is tapped. Defaults to a no-op. + public init( + onAdd: @escaping (String) -> Void, + onRouting: @escaping (RoutingAction) -> Void = { _ in } + ) { + self.onAdd = onAdd + self.onRouting = onRouting + } + + /// Registered pedal names in preferred order, with any unlisted registered pedals appended. + private var orderedPedalNames: [String] { + let registered: Set = Set(PedalRegistry.builtIn.keys) + let ordered: [String] = PedalPaletteView.preferredOrder.filter { registered.contains($0) } + let extras: [String] = registered + .subtracting(ordered) + .sorted() + return ordered + extras + } + + // MARK: - Body + + public var body: some View { + VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) { + VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) { + sectionTitle("PEDALS") + ForEach(orderedPedalNames, id: \.self) { name in + pedalRow(name) + } + } + + VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) { + sectionTitle("ROUTING") + ForEach(PedalPaletteView.routingOptions, id: \.title) { option in + routingCard(title: option.title, caption: option.caption, action: option.action) + } + } + } + } + + // MARK: - Subviews + + private func sectionTitle(_ text: String) -> some View { + Text(text) + .font(.system(size: PedalPaletteView.titleFontSize, weight: .semibold)) + .foregroundStyle(Color.white.opacity(PedalPaletteView.titleOpacity)) + } + + /// A full-width pedal row: tap appends to the main chain; drag carries `"add:"` so it can + /// be dropped onto a stereo/parallel lane. + private func pedalRow(_ name: String) -> some View { + Button { + onAdd(name) + } label: { + HStack(spacing: 4) { + Text(name) + .font(.callout) + .foregroundStyle(Color.white) + .lineLimit(1) + Spacer(minLength: 0) + Image(systemName: "plus") + .font(.caption2) + .foregroundStyle(Color.white.opacity(PedalPaletteView.addGlyphOpacity)) + } + .padding(.horizontal, PedalPaletteView.cardPaddingH) + .padding(.vertical, PedalPaletteView.cardPaddingV) + .frame(maxWidth: .infinity, alignment: .leading) + .background(cardBackground(brightness: PedalPaletteView.pedalCardBrightness)) + } + .buttonStyle(.plain) + .draggable("add:\(name)") + } + + /// A tappable routing row that inserts a region/node into the board. + private func routingCard(title: String, caption: String, action: RoutingAction) -> some View { + Button { + onRouting(action) + } label: { + VStack(alignment: .leading, spacing: 2) { + Text(title) + .font(.callout) + .foregroundStyle(Color.white) + Text(caption) + .font(.system(size: PedalPaletteView.routingCaptionFontSize)) + .foregroundStyle(Color.white.opacity(PedalPaletteView.routingCaptionOpacity)) + } + .padding(.horizontal, PedalPaletteView.cardPaddingH) + .padding(.vertical, PedalPaletteView.cardPaddingV) + .frame(maxWidth: .infinity, alignment: .leading) + .background(cardBackground(brightness: PedalPaletteView.routingCardBrightness)) + } + .buttonStyle(.plain) + } + + private func cardBackground(brightness: Double) -> some View { + RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius) + .fill(Color(white: brightness)) + .overlay( + RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius) + .stroke( + Color.white.opacity(PedalPaletteView.cardBorderOpacity), + lineWidth: PedalPaletteView.cardBorderWidth + ) + ) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/RigFileDocument.swift b/Sources/LyrebirdShoeGazeUI/RigFileDocument.swift new file mode 100644 index 0000000..2f65de8 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/RigFileDocument.swift @@ -0,0 +1,37 @@ +// RigFileDocument.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import UniformTypeIdentifiers + +/// A minimal JSON `FileDocument` wrapping a ShoeGaze rig's encoded bytes. +/// +/// Used by ``ShoeGazeBuilderView``'s iOS `.fileExporter` to write the result of +/// `ShoeGaze.rigData()` to a user-chosen location. macOS uses an `NSSavePanel` directly and does +/// not need this type. +struct RigFileDocument: FileDocument { + + /// The rig presets are plain JSON. + static var readableContentTypes: [UTType] { [.json] } + + /// Encoded rig JSON. + let data: Data + + /// Creates a document from already-encoded rig JSON. + init(data: Data) { + self.data = data + } + + /// Decodes an existing document's bytes (required by `FileDocument`, unused by the exporter). + init(configuration: ReadConfiguration) throws { + self.data = configuration.file.regularFileContents ?? Data() + } + + /// Writes the rig JSON into a file wrapper for export. + func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { + FileWrapper(regularFileWithContents: data) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift new file mode 100644 index 0000000..b8104a6 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -0,0 +1,359 @@ +// ShoeGazeBuilderView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if canImport(AppKit) +import AppKit +#endif +import SwiftUI +import UniformTypeIdentifiers +import LyrebirdSynth +import LyrebirdUI +import LyrebirdShoeGaze + +/// A self-contained pedalboard builder: browse all pedals, build a board by adding / removing / +/// reordering pedals, tweak live controls, choose the input source, start the chain, and save or +/// load a board setup. +/// +/// This view ties together ``PedalPaletteView`` (the catalog) and ``BoardBuilderView`` (the +/// editable chain) with a transport bar, an input-source picker, a board selector, and save/load. +/// It is the shared screen hosted by both the macOS and iOS builder app shells. +/// +/// Save/load uses an `NSSavePanel`/`NSOpenPanel` on macOS and `.fileExporter`/`.fileImporter` on +/// iOS, both reading/writing the JSON produced by `ShoeGaze.rigData()` / consumed by +/// `loadRig(from:)`. Loading and input-source changes stop the engine first (they rebuild the +/// graph) and restart it if it was running. +/// +/// ## Usage +/// +/// ```swift +/// ShoeGazeBuilderView(shoeGaze: shoeGaze) +/// ``` +public struct ShoeGazeBuilderView: View { + + // MARK: - Layout constants + + private static let outerPadding: CGFloat = 16 + private static let sectionSpacing: CGFloat = 12 + private static let rowSpacing: CGFloat = 10 + private static let dividerOpacity: Double = 0.12 + private static let labelOpacity: Double = 0.65 + private static let minWidth: CGFloat = 720 + private static let minHeight: CGFloat = 460 + private static let sidebarWidth: CGFloat = 168 + private static let columnSpacing: CGFloat = 14 + private static let backgroundRed: Double = 0.08 + private static let backgroundGreen: Double = 0.07 + private static let backgroundBlue: Double = 0.06 + private static let testLoopTag: Int = -1 + private static let defaultRigFileName: String = "ShoeGazeRig" + + // MARK: - Properties + + private let shoeGaze: ShoeGaze + + /// Index of the board currently being edited. + @State private var selectedBoardIndex: Int = 0 + + /// Bumped on transport/edit actions to force a re-read of `engine.isRunning`. + @State private var transportTick: Bool = false + + /// iOS file-dialog presentation flags + the document to export. + @State private var showImporter: Bool = false + @State private var showExporter: Bool = false + @State private var exportDocument: RigFileDocument = RigFileDocument(data: Data()) + + // MARK: - Init + + /// Creates a builder view. + /// + /// - Parameter shoeGaze: The `ShoeGaze` manager whose boards and engine are edited. The + /// caller should create at least one board before presenting this view. + public init(shoeGaze: ShoeGaze) { + self.shoeGaze = shoeGaze + } + + // MARK: - Body + + public var body: some View { + VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) { + transportRow + ioRow + Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) + HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) { + paletteSidebar + Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) + boardArea + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + LyrebirdStatusView(engine: shoeGaze.engine) + } + .padding(ShoeGazeBuilderView.outerPadding) + .frame(minWidth: ShoeGazeBuilderView.minWidth, minHeight: ShoeGazeBuilderView.minHeight) + .background( + Color( + red: ShoeGazeBuilderView.backgroundRed, + green: ShoeGazeBuilderView.backgroundGreen, + blue: ShoeGazeBuilderView.backgroundBlue + ) + ) + #if !os(macOS) + .fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in + handleImport(result) + } + .fileExporter( + isPresented: $showExporter, + document: exportDocument, + contentType: .json, + defaultFilename: ShoeGazeBuilderView.defaultRigFileName + ) { result in + if case .failure(let error) = result { + print("[ShoeGazeBuilderView] export failed: \(error)") + } + } + #endif + } + + // MARK: - Transport row + + private var transportRow: some View { + _ = transportTick + let isRunning: Bool = shoeGaze.engine.isRunning + return HStack(spacing: ShoeGazeBuilderView.rowSpacing) { + Text("ShoeGaze Builder") + .font(.title2).bold() + .foregroundStyle(Color.white) + Spacer() + Button("Start") { + do { try shoeGaze.engine.start() } + catch { print("[ShoeGazeBuilderView] engine.start() failed: \(error)") } + transportTick.toggle() + } + .buttonStyle(.borderedProminent).tint(.green).disabled(isRunning) + + Button("Stop") { + shoeGaze.engine.stop() + transportTick.toggle() + } + .buttonStyle(.bordered).tint(.red).disabled(!isRunning) + } + } + + // MARK: - Input + board + save/load row + + private var ioRow: some View { + HStack(spacing: ShoeGazeBuilderView.rowSpacing) { + Text("Input:") + .font(.subheadline) + .foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity)) + Picker("Input", selection: inputBinding) { + Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag) + ForEach(0.. { + Binding( + get: { + switch shoeGaze.inputSource { + case .testLoop: return ShoeGazeBuilderView.testLoopTag + case .liveInput(let channel): return channel + } + }, + set: { newValue in + let source: InputSource = newValue == ShoeGazeBuilderView.testLoopTag + ? .testLoop + : .liveInput(channel: newValue) + switchInput(to: source) + } + ) + } + + // MARK: - Actions + + private func addPedal(type: String) { + guard !shoeGaze.boards.isEmpty else { return } + let board: PedalBoard = shoeGaze.boards[clampedBoardIndex] + do { + _ = try shoeGaze.appendPedal(type: type, to: board) + } catch { + print("[ShoeGazeBuilderView] appendPedal failed: \(error)") + } + } + + private func addBoard() { + var created: PedalBoard? + do { + let board: PedalBoard = try shoeGaze.addBoard() + created = board + try shoeGaze.finalizeBoard(board) + selectedBoardIndex = shoeGaze.boards.count - 1 + } catch { + if let board: PedalBoard = created { shoeGaze.removeBoard(board) } + print("[ShoeGazeBuilderView] addBoard failed: \(error)") + } + } + + /// Switches input source, stopping/restarting the engine around the graph rebuild. + private func switchInput(to source: InputSource) { + let wasRunning: Bool = shoeGaze.engine.isRunning + if wasRunning { shoeGaze.engine.stop() } + do { + try shoeGaze.setInputSource(source) + } catch { + print("[ShoeGazeBuilderView] setInputSource failed: \(error)") + } + if wasRunning { + try? shoeGaze.engine.start() + } + transportTick.toggle() + } + + // MARK: - Save / Load + + private func saveAction() { + #if os(macOS) + let panel: NSSavePanel = NSSavePanel() + panel.allowedContentTypes = [.json] + panel.nameFieldStringValue = "\(ShoeGazeBuilderView.defaultRigFileName).json" + panel.canCreateDirectories = true + panel.begin { response in + guard response == .OK, let url: URL = panel.url else { return } + do { try shoeGaze.saveRig(to: url) } + catch { print("[ShoeGazeBuilderView] saveRig failed: \(error)") } + } + #else + do { + exportDocument = RigFileDocument(data: try shoeGaze.rigData()) + showExporter = true + } catch { + print("[ShoeGazeBuilderView] rigData failed: \(error)") + } + #endif + } + + private func loadAction() { + #if os(macOS) + let panel: NSOpenPanel = NSOpenPanel() + panel.allowedContentTypes = [.json] + panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + panel.begin { response in + guard response == .OK, let url: URL = panel.url else { return } + loadRig(from: url) + } + #else + showImporter = true + #endif + } + + /// Loads a rig from a URL, stopping/restarting the engine around the rebuild and resetting the + /// board selection to a valid index (load replaces all boards). + private func loadRig(from url: URL) { + let wasRunning: Bool = shoeGaze.engine.isRunning + if wasRunning { shoeGaze.engine.stop() } + do { + try shoeGaze.loadRig(from: url) + selectedBoardIndex = 0 + } catch { + print("[ShoeGazeBuilderView] loadRig failed: \(error)") + } + if wasRunning { try? shoeGaze.engine.start() } + transportTick.toggle() + } + + #if !os(macOS) + private func handleImport(_ result: Result) { + switch result { + case .success(let url): + // A `.fileImporter` URL is security-scoped on iOS; access must be started to read it. + let scoped: Bool = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + loadRig(from: url) + case .failure(let error): + print("[ShoeGazeBuilderView] import failed: \(error)") + } + } + #endif +} diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeUI.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeUI.swift index 6d1ecbe..0181e0f 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeUI.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeUI.swift @@ -10,3 +10,7 @@ // ShoeGazeView.swift — top-level session view with transport // FlowLayout.swift — wrap-to-fit Layout (left-to-right, row-wrapping) // BoardEditorView.swift — per-board editor with FlowLayout pedal area + version store +// PedalPaletteView.swift — vertical palette: all pedals (tap/drag) + routing actions +// BoardFlowView.swift — left→right signal-flow board: cards, connectors, stereo/parallel lanes +// ShoeGazeBuilderView.swift — top-level builder: sidebar palette + flow board + transport + save/load +// RigFileDocument.swift — JSON FileDocument for the iOS save (.fileExporter) diff --git a/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift b/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift new file mode 100644 index 0000000..dd3ca30 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift @@ -0,0 +1,442 @@ +// BoardEditAPITests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("Board edit API") +struct BoardEditAPITests { + + /// Builds an NRT-backed `ShoeGaze` with a single finalized board of the given pedal types. + private func makeRig( + pedals: [String], + numAudioBuses: Int = 128 + ) throws -> (ShoeGaze, SynthesisEngine, URL, PedalBoard) { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( + duration: 0.1, + numAudioBuses: numAudioBuses + ) + let sg: ShoeGaze = ShoeGaze(engine: engine) + let board: PedalBoard = try sg.addBoard() + for type: String in pedals { + guard let pedal: Pedal = PedalRegistry.makePedal(type: type) else { continue } + try board.add(pedal) + } + try sg.finalizeBoard(board) + return (sg, engine, url, board) + } + + /// Starts the engine (NRT render to file) and returns the rendered stereo samples. + private func render(_ engine: SynthesisEngine, _ url: URL) throws -> [Float] { + try engine.start() + return readStereoCAF(url: url) + } + + private func names(_ board: PedalBoard) -> [String] { + board.pedals.map { $0.displayName } + } + + // MARK: - Append + + @Test func appendAddsPedalAtEndAndRenders() throws { + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + let edited: PedalBoard = try sg.appendPedal(type: "Reverb", to: board) + #expect(names(edited) == ["Overdrive", "Delay", "Reverb"]) + #expect(sg.boards.count == 1, "append should not change board count") + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "edited board should still render audio") + } + + @Test func appendUnknownTypeThrows() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + #expect(throws: ShoeGazeError.unknownPedalType("Nope")) { + try sg.appendPedal(type: "Nope", to: board) + } + } + + // MARK: - Remove + + @Test func removeDeletesLinearPedalAndRenders() throws { + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay", "Reverb"]) + defer { try? FileManager.default.removeItem(at: url) } + + let edited: PedalBoard = try sg.removePedal(at: 1, from: board) + #expect(names(edited) == ["Overdrive", "Reverb"]) + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "board should still render after removal") + } + + @Test func removeOutOfRangeThrows() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + #expect(throws: ShoeGazeError.pedalIndexOutOfRange(index: 5, count: 1)) { + try sg.removePedal(at: 5, from: board) + } + } + + // MARK: - Move + + @Test func moveReordersLinearPedalsAndRenders() throws { + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay", "Reverb"]) + defer { try? FileManager.default.removeItem(at: url) } + + // SwiftUI List.onMove convention: move row 0 to offset 2 in [OD, Delay, Reverb] + // → [Delay, Overdrive, Reverb]. + let edited: PedalBoard = try sg.movePedal(from: 0, to: 2, in: board) + #expect(names(edited) == ["Delay", "Overdrive", "Reverb"]) + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "board should still render after reorder") + } + + @Test func moveOutOfRangeThrows() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + #expect(throws: ShoeGazeError.pedalIndexOutOfRange(index: 5, count: 2)) { + try sg.movePedal(from: 5, to: 0, in: board) + } + } + + // MARK: - Branch preservation + + @Test func editingLinearPedalPreservesStereoSplitRegion() throws { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128) + defer { try? FileManager.default.removeItem(at: url) } + + let sg: ShoeGaze = ShoeGaze(engine: engine) + let board: PedalBoard = try sg.addBoard() + try board.add(OverdrivePedal()) + let section: StereoSplitSection = try board.splitStereo() + try section.left.add(DelayPedal()) + try section.right.add(PingPongDelayPedal()) + try board.collectStereo(section) + section.route = .rightOnly + try sg.finalizeBoard(board) + + // Append a linear pedal; the stereo split region must survive untouched. + let edited: PedalBoard = try sg.appendPedal(type: "Fuzz", to: board) + #expect(names(edited).contains("Fuzz"), "appended linear pedal should be present") + + let after: BoardState = edited.captureState() + guard case .stereoSplit(let stereoState)? = after.segments.first(where: { + if case .stereoSplit = $0 { return true } else { return false } + }) else { + Issue.record("Stereo split segment lost after a linear edit") + return + } + #expect(stereoState.route == .rightOnly, "route should be preserved across the edit") + #expect(stereoState.left.first?.type == "Delay", "left branch pedal preserved") + #expect(stereoState.right.first?.type == "Ping-Pong", "right branch pedal preserved") + #expect(edited.width == 2, "board should remain stereo") + } + + // MARK: - Input source switching + + @Test func setInputSourcePreservesRigAndRewiresInput() throws { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( + duration: 0.1, + numInputChannels: 2, + numAudioBuses: 128 + ) + defer { try? FileManager.default.removeItem(at: url) } + + let sg: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop) + let board: PedalBoard = try sg.addBoard() + try board.add(OverdrivePedal()) + try board.add(DelayPedal()) + try sg.finalizeBoard(board) + + try sg.setInputSource(.liveInput(channel: 0)) + + #expect(sg.inputSource == .liveInput(channel: 0), "input source should be updated") + #expect(sg.boards.count == 1, "rig board count preserved") + #expect(names(sg.boards[0]) == ["Overdrive", "Delay"], "pedals preserved across switch") + } + + @Test func setInputSourceToSameValueIsNoOp() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + let boardBefore: PedalBoard = sg.boards[0] + try sg.setInputSource(.testLoop) // already .testLoop + #expect(sg.boards[0] === boardBefore, "no-op switch should not rebuild the board") + _ = board + } + + @Test func setInputSourceToLiveWithoutInputChannelsThrowsAndLeavesEmptyRig() throws { + // Engine created with no input channels: switching to .liveInput must throw and, because + // reconstruction is atomic, leave no partially-rebuilt rig behind. + let (sg, _, url, _): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) // makeNRTEngine defaults to 0 inputs + defer { try? FileManager.default.removeItem(at: url) } + + #expect(throws: ShoeGazeError.liveInputRequiresInputChannels) { + try sg.setInputSource(.liveInput(channel: 0)) + } + #expect(sg.boards.isEmpty, "failed input switch should leave an empty rig, not a partial one") + } + + // MARK: - Branch regions (stereo split / parallel) via lane addressing + + private func stereoState(_ board: PedalBoard) -> StereoSplitState? { + for segment: BoardSegmentState in board.captureState().segments { + if case .stereoSplit(let state) = segment { return state } + } + return nil + } + + @Test func appendStereoSplitThenFillLanesIndependently() throws { + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendStereoSplit(to: board) + // The split region is the second top-level segment (after the Overdrive pedal). + let region: Int = 1 + live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: region)) + live = try sg.appendPedal(type: "Reverb", to: live, lane: .right(region: region)) + + guard let state: StereoSplitState = stereoState(live) else { + Issue.record("No stereo split segment after building one") + return + } + #expect(state.left.map { $0.type } == ["Delay"], "left lane should hold Delay") + #expect(state.right.map { $0.type } == ["Reverb"], "right lane should hold Reverb") + #expect(live.width == 2, "board should be stereo after a collected split") + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "stereo-split board should render audio") + } + + @Test func removePedalFromBranchLane() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendStereoSplit(to: board) + live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1)) + live = try sg.appendPedal(type: "Fuzz", to: live, lane: .left(region: 1)) + live = try sg.removePedal(at: 0, from: live, lane: .left(region: 1)) + + #expect(stereoState(live)?.left.map { $0.type } == ["Fuzz"], "left lane should drop Delay") + } + + @Test func appendStereoSplitOnStereoChainThrows() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + // Octave Splitter is a widener → board becomes stereo; a second split is then invalid. + let live: PedalBoard = try sg.appendPedal(type: "Octave Splitter", to: board) + #expect(live.width == 2, "widener should make the board stereo") + #expect(throws: ShoeGazeError.cannotSplitStereoChain) { + try sg.appendStereoSplit(to: live) + } + } + + @Test func removeSegmentDropsRegion() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendStereoSplit(to: board) + live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1)) + #expect(stereoState(live) != nil, "split region present before removal") + + live = try sg.removeSegment(at: 1, from: live) + #expect(stereoState(live) == nil, "split region removed") + #expect(live.width == 1, "board back to mono after removing the split") + #expect(names(live) == ["Overdrive"], "linear chain intact") + } + + @Test func appendMergeToMonoOnMonoChainThrows() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + #expect(throws: ShoeGazeError.cannotMergeMonoChain) { + try sg.appendMergeToMono(to: board) + } + } + + @Test func moveMainPedalToEndLandsBeforeTrailingRegion() throws { + // Board: [Overdrive, Delay, ]. Moving Overdrive to the end of the linear + // chain must land it after Delay but BEFORE the split region — not after it. + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendStereoSplit(to: board) // segment index 2 + // Linear pedals are [Overdrive, Delay]; move index 0 to the end (offset 2). + live = try sg.movePedal(from: 0, to: 2, in: live, lane: .main) + + #expect(names(live) == ["Delay", "Overdrive"], "Overdrive should follow Delay in the chain") + // The split region must remain the LAST top-level segment. + guard case .stereoSplit = live.captureState().segments.last else { + Issue.record("Stereo split should remain the trailing segment; pedal jumped past it") + return + } + } + + @Test func parallelSplitBranchEditing() throws { + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendParallelSplit(to: board) + live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1)) + live = try sg.appendPedal(type: "Fuzz", to: live, lane: .right(region: 1)) + + var foundParallel: Bool = false + for segment: BoardSegmentState in live.captureState().segments { + if case .parallel(let p) = segment { + foundParallel = true + #expect(p.branchA.map { $0.type } == ["Delay"]) + #expect(p.branchB.map { $0.type } == ["Fuzz"]) + } + } + #expect(foundParallel, "parallel region should exist") + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "parallel board should render audio") + } + + // MARK: - Save / load round-trip on an edited board + + @Test func overdriveDriveEightPersistsAcrossSaveAndReload() throws { + // The user's exact scenario: set Overdrive Drive to 8, save the board, reload it (into + // the SAME manager — what the builder's Load… button does), expect Drive == 8. + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + guard let overdrive: OverdrivePedal = board.pedals.first as? OverdrivePedal else { + Issue.record("Expected an Overdrive") + return + } + overdrive.drive = 8.0 + + let preset: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".json") + defer { try? FileManager.default.removeItem(at: preset) } + try sg.saveRig(to: preset) + + // Reload into the same instance (mirrors ShoeGazeBuilderView.loadAction). + try sg.loadRig(from: preset) + + guard let reloaded: OverdrivePedal = sg.boards.first?.pedals.first as? OverdrivePedal else { + Issue.record("Overdrive not present after reload") + return + } + #expect(abs(reloaded.drive - 8.0) < 1e-9, "Drive should reload as 8, got \(reloaded.drive)") + } + + @Test func knobAndBypassEditsPersistThroughSaveLoad() throws { + // Mimic the builder UI path: edits go through the knob's UIParamNode (node.update), + // not the @UIParam stored property. Then save to a file and load into a fresh manager. + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + let pedal: Pedal = board.pedals[0] + let driveValue: Double = 9.0 + pedal.knobs[0].node.update(driveValue) // "Drive" via the node, as a UI knob would + pedal.bypass = 1.0 + + let preset: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".json") + defer { try? FileManager.default.removeItem(at: preset) } + try sg.saveRig(to: preset) + + let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128) + defer { try? FileManager.default.removeItem(at: url2) } + let sg2: ShoeGaze = ShoeGaze(engine: engine2) + try sg2.loadRig(from: preset) + + let restored: Pedal = sg2.boards[0].pedals[0] + #expect(abs(restored.knobs[0].node.value - driveValue) < 1e-9, "drive should persist") + #expect(restored.bypass == 1.0, "bypass should persist") + } + + @Test func branchPedalKnobValuesPersistThroughSaveLoad() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendStereoSplit(to: board) + live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1)) + + // Edit the branch pedal's first knob via the node path. + guard let stereo: StereoSplitSection = live.stereoSplitSections.first, + let delay: Pedal = stereo.left.pedals.first else { + Issue.record("No branch Delay pedal") + return + } + let knobValue: Double = 0.42 + delay.knobs[0].node.update(knobValue) + + let preset: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".json") + defer { try? FileManager.default.removeItem(at: preset) } + try sg.saveRig(to: preset) + + let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128) + defer { try? FileManager.default.removeItem(at: url2) } + let sg2: ShoeGaze = ShoeGaze(engine: engine2) + try sg2.loadRig(from: preset) + + guard let stereo2: StereoSplitSection = sg2.boards[0].stereoSplitSections.first, + let delay2: Pedal = stereo2.left.pedals.first else { + Issue.record("Branch Delay not restored") + return + } + #expect(abs(delay2.knobs[0].node.value - knobValue) < 1e-9, "branch knob should persist") + } + + @Test func editedBoardRoundTripsThroughFile() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + try sg.appendPedal(type: "Reverb", to: board) + try sg.removePedal(at: 0, from: sg.boards[0]) // drop Overdrive → [Delay, Reverb] + + let preset: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".json") + defer { try? FileManager.default.removeItem(at: preset) } + try sg.saveRig(to: preset) + + // Fresh manager + engine; load and verify the edited chain restored and renders. + let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128) + defer { try? FileManager.default.removeItem(at: url2) } + let sg2: ShoeGaze = ShoeGaze(engine: engine2) + try sg2.loadRig(from: preset) + + #expect(sg2.boards.count == 1) + #expect(names(sg2.boards[0]) == ["Delay", "Reverb"], "edited chain should round-trip") + + let samples: [Float] = try render(engine2, url2) + #expect(hasNonSilentOutput(samples), "loaded edited rig should render audio") + } +}