// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later import Foundation /// Captions and value text, as Android's Panels.kt shortLabel() / formatParam(). enum Format { private static let prefix = try! NSRegularExpression(pattern: "^(Osc\\s?\\d|Mod\\d?|LFO|Duck|F\\.)\\s+") private static let unit = try! NSRegularExpression(pattern: "\\s*\\((dB|ms|s)\\)|\\s+s$") private static let arrow = try! NSRegularExpression(pattern: "^.*>\\s*") private static let timeKeys: Set = ["attack", "decay", "release", "mattack", "mdecay", "mrelease", "fatk", "fdec", "frel"] private static let divisionKeys: Set = ["division", "lfodiv"] private static let keyUnits: [String: String] = [ "predelay": "ms", "modrate": "Hz", "mtime": "s", "loopXfade": "ms", "pitch": "st", "pitch_rand": "st", "semitones": "st", "o1semi": "st", "o2semi": "st", "o1fine": "ct", "o2fine": "ct", "roomsize": "×", ] private static func replace(_ re: NSRegularExpression, _ s: String, _ with: String) -> String { re.stringByReplacingMatches(in: s, range: NSRange(s.startIndex..., in: s), withTemplate: with) } /// A control's caption: the card's override, else the label without its section /// prefix ("Osc1 Level" → "Level", "LFO > Pitch" → "→ Pitch") or unit. static func shortLabel(_ p: ParamInfo, labels: [String: String]?) -> String { if let l = labels?[p.key] { return l } return replace(arrow, replace(prefix, replace(unit, p.label, ""), ""), "→ ") } private static func roundToInt(_ v: Float) -> Int { Int((Double(v) + 0.5).rounded(.down)) } /// How a value reads under its knob: time in ms / s, 0..1 as %, divisions by name. static func value(_ p: ParamInfo, _ v: Float) -> String { if p.isEnum { let i = max(0, min(p.choices.count - 1, roundToInt(v))); return p.choices[i] } if p.key.hasSuffix("Div"), let names = Layouts.file?.delayDivisions { return names[max(0, min(names.count - 1, Int(v)))] } if divisionKeys.contains(p.key), let names = Layouts.file?.timeDivisions { return names[max(0, min(names.count - 1, roundToInt(v)))] } let u = keyUnits[p.key] ?? (p.label.contains("(dB)") ? "dB" : p.label.contains("(ms)") ? "ms" : "") func signed(_ s: String, _ x: Float) -> String { p.min < 0 && x > 0 ? "+" + s : s } if p.isInt { return signed("\(roundToInt(v))", v) + u } if timeKeys.contains(p.key) && p.max > 1 { if v < 1 { return "\(roundToInt(v * 1000))ms" } return String(format: v < 10 ? "%.2fs" : "%.1fs", v) } if !u.isEmpty { let f = (u == "ms" || u == "ct" || abs(v) >= 100) ? "%.0f" : (u == "Hz" || u == "×") ? "%.2f" : "%.1f" return signed(String(format: f, v), v) + u } if p.min == 0 && p.max == 1 { return "\(roundToInt(v * 100))%" } if p.min == -1 && p.max == 1 { return signed("\(roundToInt(v * 100))", v) + "%" } return signed(String(format: "%.2f", v), v) } }