Files
Reims-Go/internal/opencore/plist.go
T
Nwflower b2f7f036d8 feat(m5): add macOS prev-lang preset, disk resize/compact, audio diagnostics, and VM thumbnails
- M5.5: add pure-Go internal/opencore reader/in-place patcher for OpenCore NVRAM prev-lang:kbd with sidecar persistence, automatic replay after update-opencore/graphics changes/CoW clones, wizard/settings/CLI (--guest-lang) support
- M5.6: add stopped VM disk resize (qemu-img resize + dynamic macOS APFS expand command) and standalone qcow2 compaction (backing-file guard, free-space check, qemu-img check, atomic swap) in GUI Settings and CLI (vm resize/compact)
- M5.9: add Win32 winmm audio output/input device probing, fix reims-ctl show audio_backend parsing, expose audio backend selector (auto/dsound/none) and latency/mic diagnostics in Settings & CLI
- UI & thumbnails: add QMP screendump VM thumbnails (internal/thumb, thumbnail_flow.go), VMPage/CreateWizard layout polish, and docs/ui-audit.md
- Update docs/roadmap.md for M5.5, M5.6, and M5.9
2026-11-28 10:17:54 -07:00

306 lines
8.4 KiB
Go

package opencore
import (
"bytes"
"encoding/base64"
"encoding/xml"
"fmt"
"io"
"strings"
)
// AppleNVRAMGUID is Apple's boot variable NVRAM GUID where macOS Recovery,
// Setup Assistant, and LoginWindow read `prev-lang:kbd`.
const AppleNVRAMGUID = "7C436110-AB2A-4BBB-A880-FE41995C9F82"
type xmlElem struct {
name string
start int // byte offset of '<name...>'
contentStart int // byte offset right after '>'
contentEnd int // byte offset of '</name>' (or end of self-closing tag)
end int // byte offset right after closing '>'
selfClosing bool
text string
children []*xmlElem
}
// parsePlistTree builds a lightweight byte-offset-preserving tree of XML plist
// elements so we can read and surgically patch specific keys without
// reformatting unrelated sections of OpenCore's config.plist.
func parsePlistTree(src []byte) (*xmlElem, error) {
dec := xml.NewDecoder(bytes.NewReader(src))
var stack []*xmlElem
var root *xmlElem
for {
tokStart := int(dec.InputOffset())
tok, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("parse plist xml: %w", err)
}
tokEnd := int(dec.InputOffset())
switch t := tok.(type) {
case xml.StartElement:
// Advance tokStart past leading whitespace/comments to '<'.
lt := bytes.IndexByte(src[tokStart:tokEnd], '<')
if lt >= 0 {
tokStart += lt
}
el := &xmlElem{
name: t.Name.Local,
start: tokStart,
contentStart: tokEnd,
}
if len(stack) > 0 {
parent := stack[len(stack)-1]
parent.children = append(parent.children, el)
} else {
root = el
}
stack = append(stack, el)
case xml.EndElement:
if len(stack) == 0 {
return nil, fmt.Errorf("unexpected closing tag </%s>", t.Name.Local)
}
el := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// Distinguish self-closing <data/> from <data></data>.
if tokStart == el.contentStart && tokEnd == el.contentStart {
el.selfClosing = true
el.contentEnd = tokEnd
el.end = tokEnd
} else {
closeStart := bytes.LastIndex(src[el.contentStart:tokEnd], []byte("</"))
if closeStart >= 0 {
el.contentEnd = el.contentStart + closeStart
} else {
el.contentEnd = tokStart
}
el.end = tokEnd
}
if el.name == "key" || el.name == "string" || el.name == "data" {
el.text = strings.TrimSpace(string(src[el.contentStart:el.contentEnd]))
}
}
}
if root == nil {
return nil, fmt.Errorf("empty plist")
}
return root, nil
}
func findRootDict(root *xmlElem) *xmlElem {
if root == nil {
return nil
}
if root.name == "dict" {
return root
}
for _, c := range root.children {
if c.name == "dict" {
return c
}
}
return nil
}
func dictLookup(dict *xmlElem, key string) (*xmlElem, *xmlElem) {
if dict == nil || dict.name != "dict" {
return nil, nil
}
for i := 0; i+1 < len(dict.children); i += 2 {
k := dict.children[i]
v := dict.children[i+1]
if k.name == "key" && k.text == key {
return k, v
}
}
return nil, nil
}
func findAppleNVRAMAddDict(root *xmlElem) *xmlElem {
top := findRootDict(root)
_, nvram := dictLookup(top, "NVRAM")
_, add := dictLookup(nvram, "Add")
_, apple := dictLookup(add, AppleNVRAMGUID)
if apple != nil && apple.name == "dict" {
return apple
}
return nil
}
func findAppleNVRAMDeleteArray(root *xmlElem) *xmlElem {
top := findRootDict(root)
_, nvram := dictLookup(top, "NVRAM")
_, del := dictLookup(nvram, "Delete")
_, apple := dictLookup(del, AppleNVRAMGUID)
if apple != nil && apple.name == "array" {
return apple
}
return nil
}
// ReadPrevLang extracts the NVRAM > Add > 7C436110-... > prev-lang:kbd string
// from an OpenCore XML config.plist.
func ReadPrevLang(src []byte) (string, bool) {
root, err := parsePlistTree(src)
if err != nil {
return "", false
}
apple := findAppleNVRAMAddDict(root)
if apple == nil {
return "", false
}
_, val := dictLookup(apple, "prev-lang:kbd")
if val == nil {
return "", false
}
switch val.name {
case "data":
cleaned := strings.Join(strings.Fields(val.text), "")
if cleaned == "" {
return "", false
}
raw, err := base64.StdEncoding.DecodeString(cleaned)
if err != nil {
return "", false
}
return strings.TrimRight(string(raw), "\x00"), true
case "string":
return strings.TrimSpace(val.text), val.text != ""
default:
return "", false
}
}
// lineIndent returns the leading whitespace on the line containing offset.
func lineIndent(src []byte, offset int) string {
if offset > len(src) {
offset = len(src)
}
nl := bytes.LastIndexByte(src[:offset], '\n')
lineStart := nl + 1
i := lineStart
for i < offset && (src[i] == ' ' || src[i] == '\t') {
i++
}
return string(src[lineStart:i])
}
type bytePatch struct {
start int
end int
repl []byte
}
// PatchPrevLang returns a modified copy of an OpenCore XML config.plist with
// NVRAM > Add > 7C436110-... > prev-lang:kbd set to base64(lang) (and ensured
// present in NVRAM > Delete so OpenCore overrides any cached OVMF_VARS value).
func PatchPrevLang(src []byte, lang string) ([]byte, error) {
norm, err := NormalizeGuestLang(lang)
if err != nil {
return nil, err
}
if norm == "" {
return nil, fmt.Errorf("guest language must not be empty")
}
root, err := parsePlistTree(src)
if err != nil {
return nil, err
}
apple := findAppleNVRAMAddDict(root)
if apple == nil {
return nil, fmt.Errorf("config.plist missing NVRAM > Add > %s", AppleNVRAMGUID)
}
b64 := base64.StdEncoding.EncodeToString([]byte(norm))
var patches []bytePatch
if keyEl, valEl := dictLookup(apple, "prev-lang:kbd"); keyEl != nil && valEl != nil {
indent := lineIndent(src, valEl.start)
var repl string
if valEl.name == "data" && bytes.Contains(src[valEl.start:valEl.end], []byte("\n")) {
// Match reims-util's multiline <data>\n\t\t\t\tBASE64\n\t\t\t\t</data> style.
nl := "\n"
if bytes.Contains(src[valEl.start:valEl.end], []byte("\r\n")) {
nl = "\r\n"
}
repl = fmt.Sprintf("<data>%s%s%s%s%s</data>", nl, indent, b64, nl, indent)
} else {
repl = fmt.Sprintf("<data>%s</data>", b64)
}
patches = append(patches, bytePatch{start: valEl.start, end: valEl.end, repl: []byte(repl)})
} else {
// Insert before </dict> of Apple NVRAM Add dict.
closeIndent := lineIndent(src, apple.contentEnd)
entryIndent := closeIndent + "\t"
if len(apple.children) > 0 {
entryIndent = lineIndent(src, apple.children[0].start)
}
nl := "\n"
if bytes.Contains(src, []byte("\r\n")) {
nl = "\r\n"
}
insert := fmt.Sprintf("%s<key>prev-lang:kbd</key>%s%s<data>%s%s%s%s%s</data>%s%s",
entryIndent, nl, entryIndent, nl, entryIndent, b64, nl, entryIndent, nl, closeIndent)
// Insert right at the start of the closing tag line (after the last newline before </dict>).
insertPos := apple.contentEnd
for insertPos > apple.contentStart && (src[insertPos-1] == ' ' || src[insertPos-1] == '\t') {
insertPos--
}
patches = append(patches, bytePatch{start: insertPos, end: apple.contentEnd, repl: []byte(insert)})
}
// Ensure prev-lang:kbd is also in NVRAM > Delete > 7C436110-... so OVMF_VARS
// does not hold onto an old value across boots.
if delArr := findAppleNVRAMDeleteArray(root); delArr != nil {
hasDelete := false
for _, item := range delArr.children {
if item.name == "string" && item.text == "prev-lang:kbd" {
hasDelete = true
break
}
}
if !hasDelete && !delArr.selfClosing {
closeIndent := lineIndent(src, delArr.contentEnd)
entryIndent := closeIndent + "\t"
if len(delArr.children) > 0 {
entryIndent = lineIndent(src, delArr.children[0].start)
}
nl := "\n"
if bytes.Contains(src, []byte("\r\n")) {
nl = "\r\n"
}
insert := fmt.Sprintf("%s<string>prev-lang:kbd</string>%s%s", entryIndent, nl, closeIndent)
insertPos := delArr.contentEnd
for insertPos > delArr.contentStart && (src[insertPos-1] == ' ' || src[insertPos-1] == '\t') {
insertPos--
}
patches = append(patches, bytePatch{start: insertPos, end: delArr.contentEnd, repl: []byte(insert)})
}
}
// Apply patches in reverse byte-offset order so earlier offsets stay valid.
out := append([]byte(nil), src...)
for i := 0; i < len(patches); i++ {
for j := i + 1; j < len(patches); j++ {
if patches[j].start > patches[i].start {
patches[i], patches[j] = patches[j], patches[i]
}
}
}
for _, p := range patches {
buf := make([]byte, 0, len(out)-(p.end-p.start)+len(p.repl))
buf = append(buf, out[:p.start]...)
buf = append(buf, p.repl...)
buf = append(buf, out[p.end:]...)
out = buf
}
return out, nil
}