Files
Lyrebird/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchMenuController.swift
T
josh 62b2f5dbec v1.5.0 release: LyrebirdRandom + Live Scratch editor
LyrebirdRandom scalar distribution sampling (seedable value type + shared
Random) with DistributionKind.sample dispatcher. Live Scratch editor: rename to
LyrebirdScratch, App Support artifact staging, Format Code (⌥⌘F), Render to File
(⌥⌘R offline CAF), line-number gutter, manual completion, Foundation in snippets,
scroll-jump fix, scheduling/NRT docs.
2026-07-22 07:53:12 -07:00

429 lines
18 KiB
Swift

// LyrebirdScratchMenuController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import AppKit
import UniformTypeIdentifiers
import LyrebirdSynth
import LyrebirdLiveCompile
/// Builds and installs the macOS application menu bar for a live-coding host
/// driven by a `LyrebirdScratchModel`. Owns the action targets so menu items
/// stay wired for the lifetime of the controller.
///
/// Conforms to `NSMenuItemValidation` so the Run / Run Additive commands
/// disable when the buffer cannot be evaluated — i.e. while a compile is in
/// flight or the buffer is empty (``ReevalState/canEvaluate``).
@MainActor
public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation {
public let model: LyrebirdScratchModel
public init(model: LyrebirdScratchModel) {
self.model = model
}
/// Construct the full menu bar (App / File / Edit / Run / View / Window /
/// Help) and assign it to `NSApplication.shared.mainMenu`.
public func installMainMenu(appName: String = "LyrebirdScratch") {
let mainMenu: NSMenu = NSMenu()
mainMenu.addItem(appMenuItem(appName: appName))
mainMenu.addItem(fileMenuItem())
mainMenu.addItem(editMenuItem())
mainMenu.addItem(runMenuItem())
mainMenu.addItem(viewMenuItem())
mainMenu.addItem(windowMenuItem())
NSApplication.shared.mainMenu = mainMenu
}
// MARK: App menu
private func appMenuItem(appName: String) -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: appName)
menu.addItem(NSMenuItem(title: "About \(appName)",
action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)),
keyEquivalent: ""))
menu.addItem(NSMenuItem.separator())
let services: NSMenuItem = NSMenuItem(title: "Services", action: nil, keyEquivalent: "")
let servicesMenu: NSMenu = NSMenu(title: "Services")
services.submenu = servicesMenu
NSApplication.shared.servicesMenu = servicesMenu
menu.addItem(services)
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Hide \(appName)",
action: #selector(NSApplication.hide(_:)),
keyEquivalent: "h"))
let hideOthers: NSMenuItem = NSMenuItem(title: "Hide Others",
action: #selector(NSApplication.hideOtherApplications(_:)),
keyEquivalent: "h")
hideOthers.keyEquivalentModifierMask = [.command, .option]
menu.addItem(hideOthers)
menu.addItem(NSMenuItem(title: "Show All",
action: #selector(NSApplication.unhideAllApplications(_:)),
keyEquivalent: ""))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit \(appName)",
action: #selector(NSApplication.terminate(_:)),
keyEquivalent: "q"))
item.submenu = menu
return item
}
// MARK: File menu
private func fileMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "File")
menu.addItem(target(NSMenuItem(title: "New",
action: #selector(newSnippet(_:)),
keyEquivalent: "n")))
menu.addItem(target(NSMenuItem(title: "Open…",
action: #selector(openSnippet(_:)),
keyEquivalent: "o")))
menu.addItem(NSMenuItem.separator())
menu.addItem(target(NSMenuItem(title: "Save",
action: #selector(saveSnippet(_:)),
keyEquivalent: "s")))
let saveAs: NSMenuItem = NSMenuItem(title: "Save As…",
action: #selector(saveSnippetAs(_:)),
keyEquivalent: "s")
saveAs.keyEquivalentModifierMask = [.command, .shift]
menu.addItem(target(saveAs))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Close",
action: #selector(NSWindow.performClose(_:)),
keyEquivalent: "w"))
item.submenu = menu
return item
}
// MARK: Edit menu — wires to the first responder so NSTextView gets it
private func editMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "Edit")
menu.addItem(NSMenuItem(title: "Undo",
action: Selector(("undo:")),
keyEquivalent: "z"))
let redo: NSMenuItem = NSMenuItem(title: "Redo",
action: Selector(("redo:")),
keyEquivalent: "z")
redo.keyEquivalentModifierMask = [.command, .shift]
menu.addItem(redo)
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Cut",
action: #selector(NSText.cut(_:)),
keyEquivalent: "x"))
menu.addItem(NSMenuItem(title: "Copy",
action: #selector(NSText.copy(_:)),
keyEquivalent: "c"))
menu.addItem(NSMenuItem(title: "Paste",
action: #selector(NSText.paste(_:)),
keyEquivalent: "v"))
menu.addItem(NSMenuItem(title: "Select All",
action: #selector(NSText.selectAll(_:)),
keyEquivalent: "a"))
menu.addItem(NSMenuItem.separator())
let find: NSMenuItem = NSMenuItem(title: "Find…",
action: #selector(NSTextView.performFindPanelAction(_:)),
keyEquivalent: "f")
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
menu.addItem(find)
menu.addItem(NSMenuItem.separator())
let format: NSMenuItem = target(NSMenuItem(title: "Format Code",
action: #selector(formatCode(_:)),
keyEquivalent: "f"))
format.keyEquivalentModifierMask = [.command, .option]
menu.addItem(format)
item.submenu = menu
return item
}
// MARK: Run menu
private func runMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "Run")
menu.addItem(target(NSMenuItem(title: "Run",
action: #selector(runSnippet(_:)),
keyEquivalent: "\r")))
let runAdd: NSMenuItem = NSMenuItem(title: "Run Additive",
action: #selector(runSnippetAdditive(_:)),
keyEquivalent: "\r")
runAdd.keyEquivalentModifierMask = [.command, .shift]
menu.addItem(target(runAdd))
menu.addItem(target(NSMenuItem(title: "Run Selection",
action: #selector(runSelection(_:)),
keyEquivalent: "e")))
menu.addItem(NSMenuItem.separator())
let render: NSMenuItem = target(NSMenuItem(title: "Render to File…",
action: #selector(renderToFile(_:)),
keyEquivalent: "r"))
render.keyEquivalentModifierMask = [.command, .option]
menu.addItem(render)
menu.addItem(NSMenuItem.separator())
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
action: #selector(clearSynths(_:)),
keyEquivalent: "k")))
menu.addItem(NSMenuItem.separator())
menu.addItem(target(NSMenuItem(title: "Reset Session",
action: #selector(resetSession(_:)),
keyEquivalent: "")))
menu.addItem(target(NSMenuItem(title: "Restart to Reclaim Memory…",
action: #selector(restartApp(_:)),
keyEquivalent: "")))
item.submenu = menu
return item
}
// MARK: View menu
private func viewMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "View")
let wrap: NSMenuItem = target(NSMenuItem(title: "Wrap Lines",
action: #selector(toggleWrap(_:)),
keyEquivalent: "l"))
wrap.keyEquivalentModifierMask = [.command, .option]
menu.addItem(wrap)
menu.addItem(NSMenuItem.separator())
let inc: NSMenuItem = target(NSMenuItem(title: "Increase Font Size",
action: #selector(increaseFontSize(_:)),
keyEquivalent: "+"))
menu.addItem(inc)
menu.addItem(target(NSMenuItem(title: "Decrease Font Size",
action: #selector(decreaseFontSize(_:)),
keyEquivalent: "-")))
menu.addItem(target(NSMenuItem(title: "Reset Font Size",
action: #selector(resetFontSize(_:)),
keyEquivalent: "0")))
item.submenu = menu
return item
}
// MARK: Window menu
private func windowMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "Window")
menu.addItem(NSMenuItem(title: "Minimize",
action: #selector(NSWindow.performMiniaturize(_:)),
keyEquivalent: "m"))
menu.addItem(NSMenuItem(title: "Zoom",
action: #selector(NSWindow.performZoom(_:)),
keyEquivalent: ""))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Bring All to Front",
action: #selector(NSApplication.arrangeInFront(_:)),
keyEquivalent: ""))
item.submenu = menu
NSApplication.shared.windowsMenu = menu
return item
}
// MARK: - Menu validation
/// Disable the Run / Run Additive commands whenever the buffer cannot be
/// evaluated (a compile is in flight, or the buffer is empty). All other
/// items stay enabled. AppKit calls this automatically for items whose
/// target is this controller.
public func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
switch menuItem.action {
case #selector(runSnippet(_:)), #selector(runSnippetAdditive(_:)):
return model.reevalState.canEvaluate
case #selector(runSelection(_:)):
// Needs a selection to run and an evaluator that isn't mid-compile.
return model.hasSelection && model.reevalState.canEvaluate
case #selector(resetSession(_:)):
// Don't tear the session down mid-compile.
return !model.isCompiling
case #selector(formatCode(_:)):
// Not mid-compile; the model's formatter no-ops on a blank buffer.
return !model.isCompiling
case #selector(renderToFile(_:)):
// Needs an evaluatable buffer and no compile/render in flight.
return model.reevalState.canEvaluate
default:
return true
}
}
// MARK: - Action targets
private func target(_ item: NSMenuItem) -> NSMenuItem {
item.target = self
return item
}
@objc private func newSnippet(_ sender: Any?) {
model.text = LyrebirdScratchModel.defaultPlaceholder
}
@objc private func openSnippet(_ sender: Any?) {
let panel: NSOpenPanel = NSOpenPanel()
panel.allowedContentTypes = [.swiftSource]
panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
panel.message = "Open a Lyrebird snippet"
if panel.runModal() == .OK, let url: URL = panel.url {
do {
try model.load(from: url)
} catch {
model.reportLoadError(url: url, error: error)
}
}
}
@objc private func saveSnippet(_ sender: Any?) {
if let url: URL = model.documentURL {
do {
try model.save(to: url)
} catch {
model.reportSaveError(url: url, error: error)
}
return
}
saveSnippetAs(sender)
}
@objc private func saveSnippetAs(_ sender: Any?) {
let panel: NSSavePanel = NSSavePanel()
panel.allowedContentTypes = [.swiftSource]
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
panel.message = "Save Lyrebird snippet"
if panel.runModal() == .OK, let url: URL = panel.url {
do {
try model.save(to: url)
} catch {
model.reportSaveError(url: url, error: error)
}
}
}
@objc private func runSnippet(_ sender: Any?) {
Task { @MainActor in _ = await model.run(additive: false) }
}
@objc private func runSnippetAdditive(_ sender: Any?) {
Task { @MainActor in _ = await model.run(additive: true) }
}
@objc private func runSelection(_ sender: Any?) {
Task { @MainActor in _ = await model.runSelection() }
}
@objc private func formatCode(_ sender: Any?) {
Task { @MainActor in await model.formatBuffer() }
}
@objc private func renderToFile(_ sender: Any?) {
// 1. Output path.
let panel: NSSavePanel = NSSavePanel()
if let caf: UTType = UTType(filenameExtension: "caf") {
panel.allowedContentTypes = [caf]
}
panel.nameFieldStringValue = "render.caf"
panel.message = "Render the snippet (or selection) to a CAF audio file"
guard panel.runModal() == .OK, let url: URL = panel.url else { return }
// 2. Duration.
let alert: NSAlert = NSAlert()
alert.messageText = "Render duration"
alert.informativeText = "Length to render, in seconds:"
let durationFieldWidth: CGFloat = 200
let durationFieldHeight: CGFloat = 24
let field: NSTextField = NSTextField(frame: NSRect(x: 0, y: 0, width: durationFieldWidth, height: durationFieldHeight))
field.stringValue = "5.0"
alert.accessoryView = field
alert.addButton(withTitle: "Render")
alert.addButton(withTitle: "Cancel")
guard alert.runModal() == .alertFirstButtonReturn else { return } // cancelled
guard let duration: Double = Double(field.stringValue.trimmingCharacters(in: .whitespaces)),
duration > 0 else {
let invalid: NSAlert = NSAlert()
invalid.messageText = "Invalid duration"
invalid.informativeText = "Enter a positive number of seconds (e.g. 5.0)."
invalid.runModal()
return
}
Task { @MainActor in
let ok: Bool = await model.renderToFile(url: url, duration: duration)
if ok { NSWorkspace.shared.activateFileViewerSelecting([url]) }
}
}
@objc private func resetSession(_ sender: Any?) {
model.resetSession()
}
@objc private func restartApp(_ sender: Any?) {
let alert: NSAlert = NSAlert()
alert.messageText = "Restart to reclaim memory?"
alert.informativeText =
"Relaunches the app to free the \(model.loadedSnippetCount) mapped snippet "
+ "dylibs (compiled snippets can't be unloaded any other way). Unsaved changes "
+ "in the buffer will be lost."
alert.addButton(withTitle: "Restart")
alert.addButton(withTitle: "Cancel")
guard alert.runModal() == .alertFirstButtonReturn else { return }
LyrebirdScratchMenuController.relaunchApp()
}
/// Relaunch the host `.app`: open a fresh instance, then terminate this one
/// once it is confirmed on its way. The new process starts with zero mapped
/// snippet dylibs — the only way to reclaim that memory. On a launch failure
/// the current process is **kept** (and the user informed) rather than
/// terminated into oblivion.
private static func relaunchApp() {
let url: URL = Bundle.main.bundleURL
let config: NSWorkspace.OpenConfiguration = NSWorkspace.OpenConfiguration()
config.createsNewApplicationInstance = true
NSWorkspace.shared.openApplication(at: url, configuration: config) { app, error in
DispatchQueue.main.async {
if let error: Error = error {
let alert: NSAlert = NSAlert()
alert.messageText = "Restart failed"
alert.informativeText =
"Could not relaunch the app (\(error.localizedDescription)). "
+ "The current session is unchanged."
alert.runModal()
} else if app != nil {
NSApp.terminate(nil)
}
}
}
}
@objc private func clearSynths(_ sender: Any?) {
model.clearTracked()
}
@objc private func toggleWrap(_ sender: Any?) {
model.toggleWrapsLines()
if let item: NSMenuItem = sender as? NSMenuItem {
item.state = model.wrapsLines ? .on : .off
}
}
@objc private func increaseFontSize(_ sender: Any?) {
model.bumpFontSize(by: 1)
}
@objc private func decreaseFontSize(_ sender: Any?) {
model.bumpFontSize(by: -1)
}
@objc private func resetFontSize(_ sender: Any?) {
model.resetFontSize()
}
}
#endif