main
Colby Knox 0.2.86: sch_batch and log_tail (the standard's last two), engine 0.22.0 (schematic_review design checks, placement scor… 2e9e947
//! Read an Altium schematic straight from its file, without Altium: a .SchDoc is an OLE compound file whose
//! "FileHeader" stream holds the sheet as `|KEY=value|...` records. Parts, designators, parameters, pins, positions
//! and UniqueIDs come out in milliseconds, with Altium closed.
use serde_json::{json, Map, Value};
use std::collections::BTreeMap;

const END: u32 = 0xFFFF_FFFA; // ENDOFCHAIN and the other markers sit at or above this

fn u16_at(b: &[u8], o: usize) -> Option<u16> { b.get(o..o + 2).map(|s| u16::from_le_bytes([s[0], s[1]])) }
fn u32_at(b: &[u8], o: usize) -> Option<u32> { b.get(o..o + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])) }
fn u64_at(b: &[u8], o: usize) -> Option<u64> { b.get(o..o + 8).map(|s| u64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]])) }

/// The named streams of a compound file (MS-CFB): FAT and DIFAT chains, the directory, the mini stream.
pub fn cfb_streams(b: &[u8]) -> Result<BTreeMap<String, Vec<u8>>, String> {
    if b.len() < 512 || b[..8] != [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1] { return Err("not a compound file (no OLE signature)".into()); }
    let ss = 1usize << u16_at(b, 0x1E).ok_or("short header")?;
    let mss = 1usize << u16_at(b, 0x20).ok_or("short header")?;
    let (nfat, dir1, cutoff, mf1, nmf, df1, mut ndf) = (u32_at(b, 0x2C).unwrap_or(0) as usize, u32_at(b, 0x30).unwrap_or(END), u32_at(b, 0x38).unwrap_or(4096) as u64,
        u32_at(b, 0x3C).unwrap_or(END), u32_at(b, 0x40).unwrap_or(0), u32_at(b, 0x44).unwrap_or(END), u32_at(b, 0x48).unwrap_or(0));
    let sector = |s: u32| -> Option<&[u8]> { let o = (s as usize + 1) * ss; b.get(o..o + ss) };
    let mut difat: Vec<u32> = (0..109).filter_map(|i| u32_at(b, 0x4C + i * 4)).collect();
    let mut s = df1;
    while s < END && ndf > 0 {
        let sec = sector(s).ok_or("bad DIFAT sector")?;
        let n = ss / 4;
        difat.extend((0..n - 1).filter_map(|i| u32_at(sec, i * 4)));
        s = u32_at(sec, (n - 1) * 4).unwrap_or(END);
        ndf -= 1;
    }
    let mut fat: Vec<u32> = Vec::new();
    for &fs in difat.iter().take(nfat) {
        let sec = sector(fs).ok_or("bad FAT sector")?;
        fat.extend((0..ss / 4).filter_map(|i| u32_at(sec, i * 4)));
    }
    let chain = |start: u32, table: &[u32]| -> Vec<u32> {
        let mut out = Vec::new();
        let mut s = start;
        while s < END && (s as usize) < table.len() && out.len() < table.len() { out.push(s); s = table[s as usize]; }
        out
    };
    let read = |start: u32, size: u64| -> Vec<u8> {
        let mut v = Vec::new();
        for s in chain(start, &fat) { if let Some(sec) = sector(s) { v.extend_from_slice(sec); } }
        v.truncate(size.min(v.len() as u64) as usize);
        v
    };
    let dir = read(dir1, u64::MAX);
    let mut ents: Vec<(String, u8, u32, u64)> = dir.chunks(128).filter(|e| e.len() == 128).map(|e| {
        let nl = u16_at(e, 64).unwrap_or(0) as usize;
        let units: Vec<u16> = (0..nl.saturating_sub(2) / 2).filter_map(|i| u16_at(e, i * 2)).collect();
        (String::from_utf16_lossy(&units), e[66], u32_at(e, 0x74).unwrap_or(END), u64_at(e, 0x78).unwrap_or(0))
    }).collect();
    // a stream inside a storage is named storage/stream (a SchLib keeps one "Data" stream per symbol storage; flat
    // names made them overwrite each other); top-level streams keep their bare name
    let links: Vec<(u32, u32, u32)> = dir.chunks(128).filter(|e| e.len() == 128).map(|e| (u32_at(e, 0x44).unwrap_or(END), u32_at(e, 0x48).unwrap_or(END), u32_at(e, 0x4C).unwrap_or(END))).collect();
    let mut stack: Vec<(u32, String)> = links.first().map(|l| vec![(l.2, String::new())]).unwrap_or_default();
    let mut seen = vec![false; ents.len()];
    while let Some((i, prefix)) = stack.pop() {
        let i = i as usize;
        if i >= ents.len() || seen[i] { continue; }
        seen[i] = true;
        let (l, r, c) = links[i];
        stack.push((l, prefix.clone()));
        stack.push((r, prefix.clone()));
        let full = if prefix.is_empty() { ents[i].0.clone() } else { format!("{prefix}/{}", ents[i].0) };
        if ents[i].1 == 1 { stack.push((c, full.clone())); }
        ents[i].0 = full;
    }
    let root = ents.first().ok_or("no root entry")?;
    let mini = read(root.2, root.3);
    let mut minifat: Vec<u32> = Vec::new();
    if nmf > 0 { for s in chain(mf1, &fat) { if let Some(sec) = sector(s) { minifat.extend((0..ss / 4).filter_map(|i| u32_at(sec, i * 4))); } } }
    let mut out = BTreeMap::new();
    for (name, typ, start, size) in ents.iter().skip(1) {
        if *typ != 2 { continue; }
        let data = if *size < cutoff {
            let mut v = Vec::new();
            for s in chain(*start, &minifat) { let o = s as usize * mss; if let Some(m) = mini.get(o..o + mss) { v.extend_from_slice(m); } }
            v.truncate(*size as usize);
            v
        } else { read(*start, *size) };
        out.insert(name.clone(), data);
    }
    Ok(out)
}

/// The text records of a FileHeader stream, keys upper-cased; a `%UTF8%KEY` value (UTF-8) replaces KEY's (stored in
/// the local codepage, so "±20%" read back garbled).
pub fn records(data: &[u8]) -> Vec<BTreeMap<String, String>> {
    let mut out = Vec::new();
    let mut i = 0;
    while i + 4 <= data.len() {
        let n = u32_at(data, i).unwrap_or(0);
        let (len, typ) = ((n & 0x00FF_FFFF) as usize, n >> 24);
        i += 4;
        let body = &data[i..(i + len).min(data.len())];
        i += len;
        if typ != 0 { continue; }
        let mut m = BTreeMap::new();
        let mut utf8: Vec<(String, String)> = Vec::new();
        for part in body.split(|&c| c == b'|') {
            let part: &[u8] = if part.last() == Some(&0) { &part[..part.len() - 1] } else { part };
            let Some(eq) = part.iter().position(|&c| c == b'=') else { continue };
            let key = String::from_utf8_lossy(&part[..eq]).to_ascii_uppercase();
            let raw = &part[eq + 1..];
            if let Some(k) = key.strip_prefix("%UTF8%") { utf8.push((k.to_string(), String::from_utf8_lossy(raw).to_string())); continue; }
            m.insert(key, raw.iter().map(|&c| c as char).collect::<String>());
        }
        for (k, v) in utf8 { m.insert(k, v); }
        out.push(m);
    }
    out
}

fn num(r: &BTreeMap<String, String>, k: &str) -> i64 { r.get(k).and_then(|v| v.parse::<i64>().ok()).unwrap_or(0) }
/// A coordinate in mil: the value is in 10 mil units, with a _FRAC part in 1/100000 of one.
fn mil(r: &BTreeMap<String, String>, k: &str) -> f64 { (num(r, k) as f64 + num(r, &format!("{k}_FRAC")) as f64 / 100_000.0) * 10.0 }

/// The sheet's components, each with its designator, parameters and (its own part's) pins. Pure, for the tests.
pub fn components(recs: &[BTreeMap<String, String>], with_pins: bool, with_params: bool) -> Vec<Value> {
    // the first record is the file header; owners count from the record after it
    let body: &[BTreeMap<String, String>] = if recs.first().map(|r| r.contains_key("HEADER")).unwrap_or(false) { &recs[1..] } else { recs };
    let mut owned: BTreeMap<i64, Vec<&BTreeMap<String, String>>> = BTreeMap::new();
    for r in body { if let Some(o) = r.get("OWNERINDEX").and_then(|v| v.parse::<i64>().ok()) { owned.entry(o).or_default().push(r); } }
    let mut out = Vec::new();
    for (i, c) in body.iter().enumerate() {
        if c.get("RECORD").map(|r| r.as_str()) != Some("1") { continue; }
        let kids = owned.get(&(i as i64)).cloned().unwrap_or_default();
        let field = |rec: &str, name: &str| kids.iter().find(|k| k.get("RECORD").map(|r| r.as_str()) == Some(rec) && k.get("NAME").map(|n| n.eq_ignore_ascii_case(name)).unwrap_or(false)).and_then(|k| k.get("TEXT").cloned());
        let part = num(c, "CURRENTPARTID").max(1);
        let mode = num(c, "DISPLAYMODE");
        let mut o = Map::new();
        o.insert("designator".into(), json!(kids.iter().find(|k| k.get("RECORD").map(|r| r.as_str()) == Some("34")).and_then(|k| k.get("TEXT").cloned()).unwrap_or_default()));
        o.insert("libReference".into(), json!(c.get("LIBREFERENCE").cloned().unwrap_or_default()));
        // the standard's names for the same (the engine's design checks read libRef and value, else comment)
        o.insert("libRef".into(), json!(c.get("LIBREFERENCE").cloned().unwrap_or_default()));
        o.insert("value".into(), json!(field("41", "Value").unwrap_or_default()));
        o.insert("comment".into(), json!(field("41", "Comment").unwrap_or_default()));
        o.insert("description".into(), json!(c.get("COMPONENTDESCRIPTION").cloned().unwrap_or_default()));
        o.insert("uniqueId".into(), json!(c.get("UNIQUEID").cloned().unwrap_or_default()));
        o.insert("partId".into(), json!(part));
        o.insert("partCount".into(), json!((num(c, "PARTCOUNT") - 1).max(1)));
        o.insert("xMil".into(), json!(mil(c, "LOCATION.X").round()));
        o.insert("yMil".into(), json!(mil(c, "LOCATION.Y").round()));
        o.insert("orientation".into(), json!(num(c, "ORIENTATION")));
        o.insert("sourceLibrary".into(), json!(c.get("SOURCELIBRARYNAME").cloned().unwrap_or_default()));
        if with_params {
            let ps: Vec<Value> = kids.iter().filter(|k| k.get("RECORD").map(|r| r.as_str()) == Some("41"))
                .filter_map(|k| Some(json!({"name": k.get("NAME")?, "value": k.get("TEXT").cloned().unwrap_or_default()}))).collect();
            o.insert("params".into(), json!(ps));
        }
        if with_pins {
            // a placed part holds every part's and display mode's pins: the ones it shows are its own part, the shared
            // part 0, and its display mode
            let pins: Vec<Value> = kids.iter().filter(|k| k.get("RECORD").map(|r| r.as_str()) == Some("2"))
                .filter(|k| { let p = num(k, "OWNERPARTID"); (p == part || p == 0) && num(k, "OWNERPARTDISPLAYMODE") == mode })
                .map(|k| json!({"number": k.get("DESIGNATOR").cloned().unwrap_or_default(), "name": k.get("NAME").cloned().unwrap_or_default(), "electrical": num(k, "ELECTRICAL")})).collect();
            o.insert("pins".into(), json!(pins));
        }
        out.push(Value::Object(o));
    }
    out
}

/// altium_read_sheet_file {path, pins?, params?}: the sheet's parts read from the file, no Altium needed.
pub fn read_sheet_file(args: &Value) -> Value {
    let Some(path) = crate::support::s(args, "path").or_else(|| crate::support::s(args, "filePath")).filter(|p| p.to_lowercase().ends_with(".schdoc")) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "path (a .SchDoc) is required"});
    };
    let t0 = std::time::Instant::now();
    let b = match std::fs::read(&path) { Ok(b) => b, Err(e) => return json!({"success": false, "errorCode": "not_found", "error": format!("{path}: {e}")}) };
    let streams = match cfb_streams(&b) { Ok(s) => s, Err(e) => return json!({"success": false, "errorCode": "not_a_schdoc", "error": e, "_hint": "Only binary .SchDoc files (Altium's default) are read; an ASCII-format sheet is not."}) };
    let Some(fh) = streams.get("FileHeader") else { return json!({"success": false, "errorCode": "not_a_schdoc", "error": "no FileHeader stream"}) };
    let recs = records(fh);
    let pins = args.get("pins").and_then(|v| v.as_bool()) != Some(false);
    let params = args.get("params").and_then(|v| v.as_bool()) == Some(true);
    let comps = components(&recs, pins, params);
    let header = recs.first().and_then(|r| r.get("HEADER").cloned()).unwrap_or_default();
    json!({"success": true, "path": path, "format": header, "records": recs.len(), "count": comps.len(), "components": comps, "elapsedMs": t0.elapsed().as_millis() as u64,
        "_hint": "Read from the saved file, without Altium: unsaved edits in an open Altium are not here (altium_schematic_data reads the live sheet). Coordinates are mil; pins are each part's own plus the shared part 0."})
}

#[cfg(test)]
mod tests {
    use super::*;

    fn comps(bytes: &[u8]) -> Vec<Value> {
        let s = cfb_streams(bytes).unwrap();
        components(&records(&s["FileHeader"]), true, true)
    }

    #[test]
    fn the_lane_sheet_reads_like_altium_reports_it() {
        let c = comps(include_bytes!("../testdata/lane.SchDoc"));
        let des: Vec<&str> = c.iter().map(|x| x["designator"].as_str().unwrap()).collect();
        assert_eq!(des, vec!["U2", "U3", "U1", "R90"]);
        // the same ids altium_schematic_data reported live (2026-10-23)
        assert_eq!(c[0]["uniqueId"], json!("HXDEWKXY"));
        assert_eq!(c[0]["xMil"], json!(2400.0));
        assert_eq!(c[0]["pins"].as_array().unwrap().len(), 8);
        assert_eq!(c[3]["libReference"], json!("RES-2"));
    }

    #[test]
    fn a_two_part_mcu_shows_each_part_its_own_pins_and_utf8_text() {
        // Altium's own example sheet, not redistributed here: read from an install (or ALTIUM_EXAMPLE_SCHDOC) when one
        // is reachable, else skipped
        let ex = "Examples/Bluetooth Sentinel/Microcontroller_STM32F101.SchDoc";
        let tries: Vec<String> = std::env::var("ALTIUM_EXAMPLE_SCHDOC").into_iter()
            .chain(["ADDevelop", "AD26"].iter().map(|v| format!("/mnt/c/Users/Public/Documents/Altium/{v}/{ex}"))).collect();
        let Some(bytes) = tries.iter().find_map(|p| std::fs::read(p).ok()) else { eprintln!("skipped: no Altium example sheet at {tries:?}"); return };
        let c = comps(&bytes);
        assert_eq!(c.len(), 16);
        let u2: Vec<&Value> = c.iter().filter(|x| x["designator"] == json!("U2")).collect();
        assert_eq!(u2.len(), 2);
        assert_eq!((u2[0]["partId"].clone(), u2[1]["partId"].clone(), u2[0]["partCount"].clone()), (json!(1), json!(2), json!(2)));
        let (a, b) = (u2[0]["pins"].as_array().unwrap().len(), u2[1]["pins"].as_array().unwrap().len());
        assert!(a > 0 && b > 0 && a + b <= 37 + 37, "each part lists its own pins ({a} + {b})");
        assert!(u2[0]["description"].as_str().unwrap().starts_with("STM32 ARM-based 32-bit MCU"));
    }

    #[test]
    fn a_file_that_is_not_a_compound_file_is_refused() {
        assert!(cfb_streams(b"hello world, definitely not OLE").is_err());
    }
}