Files
Lyrebird/Sources/LyrebirdUI/LyrebirdNodeTreeView.swift
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-10 21:09:11 -07:00

514 lines
16 KiB
Swift

// LyrebirdNodeTreeView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if canImport(SwiftUI)
import SwiftUI
import LyrebirdSynth
/// Live tree view of the engine's `NodeTreeMirror`.
///
/// Renders rows head→tail (top-to-bottom reading order matches RT signal
/// flow). Groups expand / collapse via `DisclosureGroup`. Each row shows
/// a kind glyph, a class name, an optional 4-hex identity suffix, and a
/// child-count badge for groups.
///
/// ## Hosting
///
/// Embed inside any SwiftUI parent:
///
/// ```swift
/// LyrebirdNodeTreeView(engine: engine)
/// .padding()
/// ```
///
/// On macOS, `presentInWindow(...)` opens a detached `LyrebirdWindow`.
///
/// ## Threading
///
/// `NodeTreeMirror` and its `snapshot` are read on the main thread. SwiftUI
/// view bodies run on the main thread; reads are safe.
public struct LyrebirdNodeTreeView: View {
/// `@Observable` reference; SwiftUI tracks `snapshot` reads via the
/// macro-synthesized observation registrar.
private let mirror: NodeTreeMirror
@State private var expanded: Set<ObjectIdentifier> = []
/// Creates a node-tree view bound to the given engine's mirror.
public init(engine: SynthesisEngine) {
self.mirror = engine.nodeTreeMirror
}
/// Creates a node-tree view bound to the given mirror.
public init(mirror: NodeTreeMirror) {
self.mirror = mirror
}
public var body: some View {
VStack(alignment: .leading, spacing: 6) {
headerRow
Divider()
ScrollView {
VStack(alignment: .leading, spacing: 2) {
NodeRowList(
node: mirror.snapshot.root,
depth: 0,
expanded: $expanded
)
}
.padding(.vertical, 4)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding(12)
.background(Color.lyrebirdControlBackground)
.frame(minWidth: 320, minHeight: 220)
.onAppear { _seedDefaultExpansion() }
}
private var headerRow: some View {
HStack(spacing: 8) {
Text("Node Tree")
.font(.headline)
Spacer()
Button("Expand All") { _expandAll() }
.font(.caption)
Button("Collapse All") { expanded.removeAll() }
.font(.caption)
}
}
/// Default expansion: root + mainGroup open, deeper nodes collapsed.
private func _seedDefaultExpansion() {
guard expanded.isEmpty else { return }
let root: NodeTreeSnapshot.Node = mirror.snapshot.root
expanded.insert(root.id)
for child: NodeTreeSnapshot.Node in root.children where _isContainer(child.kind) {
expanded.insert(child.id)
}
}
private func _expandAll() {
var ids: Set<ObjectIdentifier> = []
_collectContainerIds(mirror.snapshot.root, into: &ids)
expanded = ids
}
private func _collectContainerIds(
_ node: NodeTreeSnapshot.Node,
into ids: inout Set<ObjectIdentifier>
) {
if _isContainer(node.kind) {
ids.insert(node.id)
}
for child: NodeTreeSnapshot.Node in node.children {
_collectContainerIds(child, into: &ids)
}
}
private func _isContainer(_ kind: NodeTreeSnapshot.Node.Kind) -> Bool {
switch kind {
case .group, .parallelGroup: return true
case .synth: return false
}
}
}
// MARK: - Recursive row list
private struct NodeRowList: View {
let node: NodeTreeSnapshot.Node
let depth: Int
@Binding var expanded: Set<ObjectIdentifier>
var body: some View {
let isContainer: Bool = _isContainer(node.kind)
let isExpanded: Bool = expanded.contains(node.id)
NodeRow(
node: node,
depth: depth,
isContainer: isContainer,
isExpanded: isExpanded,
toggle: {
if isExpanded { expanded.remove(node.id) }
else { expanded.insert(node.id) }
}
)
if isContainer && isExpanded {
ForEach(node.children) { child in
NodeRowList(
node: child,
depth: depth + 1,
expanded: $expanded
)
}
}
}
private func _isContainer(_ kind: NodeTreeSnapshot.Node.Kind) -> Bool {
switch kind {
case .group, .parallelGroup: return true
case .synth: return false
}
}
}
// MARK: - Single row
private struct NodeRow: View {
let node: NodeTreeSnapshot.Node
let depth: Int
let isContainer: Bool
let isExpanded: Bool
let toggle: () -> Void
private static let indentPoints: CGFloat = 14
private static let dotIconSize: CGFloat = 6
private static let chevronWidth: CGFloat = 12
private static let identityHexSuffixLen: Int = 4
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 6) {
Spacer()
.frame(width: CGFloat(depth) * NodeRow.indentPoints)
if isContainer {
Button(action: toggle) {
Image(systemName: isExpanded ? "chevron.down" : "chevron.right")
.font(.caption2)
.foregroundStyle(.secondary)
.frame(width: NodeRow.chevronWidth, alignment: .center)
}
.buttonStyle(.plain)
} else {
Image(systemName: "circle.fill")
.font(.system(size: NodeRow.dotIconSize))
.foregroundStyle(.tertiary)
.frame(width: NodeRow.chevronWidth, alignment: .center)
}
Text(node.displayName)
.font(.callout.monospaced())
.foregroundStyle(.primary)
if let badge: String = childCountBadge {
Text(badge)
.font(.caption2.monospaced())
.foregroundStyle(.secondary)
}
Text(_identityShort(node.id))
.font(.caption2.monospaced())
.foregroundStyle(.tertiary)
Spacer(minLength: 0)
}
.contentShape(Rectangle())
.onTapGesture { if isContainer { toggle() } }
}
private var childCountBadge: String? {
guard isContainer else { return nil }
return "(\(node.children.count))"
}
private func _identityShort(_ id: ObjectIdentifier) -> String {
// Use `hashValue` rather than parsing `String(describing:)`. The
// textual form of `ObjectIdentifier` is a stdlib implementation
// detail with no API guarantee; `hashValue` is process-stable for
// a given object identity (Hashable conformance) and yields a
// deterministic short hex disambiguator.
let mask: Int = (1 << (NodeRow.identityHexSuffixLen * 4)) - 1
let masked: Int = id.hashValue & mask
let raw: String = String(masked, radix: 16, uppercase: false)
let padded: String
if raw.count < NodeRow.identityHexSuffixLen {
padded = String(repeating: "0", count: NodeRow.identityHexSuffixLen - raw.count) + raw
} else {
padded = raw
}
return "#" + padded
}
}
// MARK: - Standalone window (macOS)
#if os(macOS)
extension LyrebirdNodeTreeView {
/// Opens a `LyrebirdWindow` hosting a node-tree view.
///
/// - Parameters:
/// - engine: The engine to mirror.
/// - title: Window title bar text. Defaults to `"Node Tree"`.
/// - width: Initial width in points. Defaults to `420`.
/// - height: Initial height in points. Defaults to `420`.
@MainActor
@discardableResult
public static func presentInWindow(
engine: SynthesisEngine,
title: String = "Node Tree",
width: CGFloat = 420,
height: CGFloat = 420
) -> LyrebirdWindow {
let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height)
win.open {
LyrebirdNodeTreeView(engine: engine)
}
return win
}
}
#endif
#else
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdNodeTreeView`: a live indented
// tree of the engine's `NodeTreeMirror`, rows head→tail. Live updates come from
// reading `mirror.snapshot` in the body (observation-tracked, `NodeTreeMirror`
// is `@Observable`). Groups expand/collapse via a tapped glyph.
//
// Differences vs the Apple side: SF-Symbol chevrons/dots become text glyphs
// (▼ / ▶ / •) — `DrawingContext` has no image atlas and Text is available here;
// monospaced fonts fall back to the default font. `presentInWindow` opens a
// detached GTK window (needs a running `GtkApplication`).
//
// SwiftOpenUI is always present in this target (see Package.swift).
import SwiftOpenUI
import LyrebirdSynth
/// Live indented tree of the engine's `NodeTreeMirror` for the Linux/GTK4 UI.
/// Mirrors `LyrebirdUI.LyrebirdNodeTreeView`; same public API/init as the Apple
/// side.
public struct LyrebirdNodeTreeView: View {
private let mirror: NodeTreeMirror
@State private var expanded: Set<ObjectIdentifier> = []
private let minPanelWidth: Double = 320
private let minPanelHeight: Double = 220
/// Creates a node-tree view bound to the given engine's mirror.
public init(engine: SynthesisEngine) {
self.mirror = engine.nodeTreeMirror
}
/// Creates a node-tree view bound to the given mirror.
public init(mirror: NodeTreeMirror) {
self.mirror = mirror
}
public var body: some View {
VStack(alignment: .leading, spacing: 6) {
headerRow
Divider()
ScrollView {
VStack(alignment: .leading, spacing: 2) {
NodeRowList(
node: mirror.snapshot.root,
depth: 0,
expanded: $expanded
)
}
.padding(top: 4, bottom: 4, leading: 0, trailing: 0)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding(12)
.background(Color.lyrebirdControlBackground)
.frame(minWidth: minPanelWidth, minHeight: minPanelHeight)
.onAppear { _seedDefaultExpansion() }
}
private var headerRow: some View {
HStack(spacing: 8) {
Text("Node Tree")
.font(.headline)
Spacer()
Button("Expand All") { _expandAll() }
.font(.caption)
Button("Collapse All") { expanded.removeAll() }
.font(.caption)
}
}
/// Default expansion: root + mainGroup open, deeper nodes collapsed.
private func _seedDefaultExpansion() {
guard expanded.isEmpty else { return }
let root: NodeTreeSnapshot.Node = mirror.snapshot.root
expanded.insert(root.id)
for child: NodeTreeSnapshot.Node in root.children where _isContainer(child.kind) {
expanded.insert(child.id)
}
}
private func _expandAll() {
var ids: Set<ObjectIdentifier> = []
_collectContainerIds(mirror.snapshot.root, into: &ids)
expanded = ids
}
private func _collectContainerIds(
_ node: NodeTreeSnapshot.Node,
into ids: inout Set<ObjectIdentifier>
) {
if _isContainer(node.kind) {
ids.insert(node.id)
}
for child: NodeTreeSnapshot.Node in node.children {
_collectContainerIds(child, into: &ids)
}
}
private func _isContainer(_ kind: NodeTreeSnapshot.Node.Kind) -> Bool {
switch kind {
case .group, .parallelGroup: return true
case .synth: return false
}
}
}
// MARK: - Recursive row list
private struct NodeRowList: View {
let node: NodeTreeSnapshot.Node
let depth: Int
@Binding var expanded: Set<ObjectIdentifier>
var body: some View {
let isContainer: Bool = _isContainer(node.kind)
let isExpanded: Bool = expanded.contains(node.id)
VStack(alignment: .leading, spacing: 2) {
NodeRow(
node: node,
depth: depth,
isContainer: isContainer,
isExpanded: isExpanded,
toggle: {
if isExpanded { expanded.remove(node.id) }
else { expanded.insert(node.id) }
}
)
if isContainer && isExpanded {
ForEach(node.children) { child in
NodeRowList(
node: child,
depth: depth + 1,
expanded: $expanded
)
}
}
}
}
private func _isContainer(_ kind: NodeTreeSnapshot.Node.Kind) -> Bool {
switch kind {
case .group, .parallelGroup: return true
case .synth: return false
}
}
}
// MARK: - Single row
private struct NodeRow: View {
let node: NodeTreeSnapshot.Node
let depth: Int
let isContainer: Bool
let isExpanded: Bool
let toggle: () -> Void
private static let indentPoints: Double = 14
private static let glyphWidth: Double = 12
private static let identityHexSuffixLen: Int = 4
var body: some View {
HStack(spacing: 6) {
Spacer()
.frame(width: Double(depth) * NodeRow.indentPoints)
Text(glyph)
.font(.caption2)
.foregroundStyle(.secondary)
.frame(width: NodeRow.glyphWidth, alignment: .center)
Text(node.displayName)
.font(.callout)
.foregroundStyle(.primary)
if let badge: String = childCountBadge {
Text(badge)
.font(.caption2)
.foregroundStyle(.secondary)
}
Text(_identityShort(node.id))
.font(.caption2)
.foregroundStyle(.tertiary)
Spacer(minLength: 0)
}
.onTapGesture { if isContainer { toggle() } }
}
/// Expand/collapse glyph for containers; a bullet for leaf synth nodes.
private var glyph: String {
guard isContainer else { return "•" }
return isExpanded ? "▼" : "▶"
}
private var childCountBadge: String? {
guard isContainer else { return nil }
return "(\(node.children.count))"
}
private func _identityShort(_ id: ObjectIdentifier) -> String {
// Use `hashValue` rather than parsing `String(describing:)`. The
// textual form of `ObjectIdentifier` is a stdlib implementation
// detail with no API guarantee; `hashValue` is process-stable for
// a given object identity (Hashable conformance) and yields a
// deterministic short hex disambiguator.
let mask: Int = (1 << (NodeRow.identityHexSuffixLen * 4)) - 1
let masked: Int = id.hashValue & mask
let raw: String = String(masked, radix: 16, uppercase: false)
let padded: String
if raw.count < NodeRow.identityHexSuffixLen {
padded = String(repeating: "0", count: NodeRow.identityHexSuffixLen - raw.count) + raw
} else {
padded = raw
}
return "#" + padded
}
}
// MARK: - Standalone window (Linux)
extension LyrebirdNodeTreeView {
/// Opens a `LyrebirdWindow` hosting a node-tree view. Requires a running
/// `GtkApplication` loop.
///
/// - Parameters:
/// - engine: The engine to mirror.
/// - title: Window title-bar text. Defaults to `"Node Tree"`.
/// - width: Initial width in points. Defaults to `420`.
/// - height: Initial height in points. Defaults to `420`.
@discardableResult
public static func presentInWindow(
engine: SynthesisEngine,
title: String = "Node Tree",
width: Double = 420,
height: Double = 420
) -> LyrebirdWindow {
let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height)
win.open {
LyrebirdNodeTreeView(engine: engine)
}
return win
}
}
#endif