main
Colby Knox 0.2.103: update_pcb keeps board-only nets and pairs and returns Altium's Yes/No questions (#39); demo/show surfaces wai… c97bab4
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
//! Sheets as a whole, the rest of the EDA Bridge Standard's schematic batch 1 on Altium: the page and title block, a
//! new sheet (alone or as a child of a project's root), the sheet tree read from the files, sheet symbol pins, part
//! fields back where the library put them, and placed symbols updated from their libraries. Millimetres, y up.
use crate::sch::{agent_data, clean, maybe_save, st};
use crate::schdoc::{cfb_streams, records};
use crate::schwire::{self, apply, bad, dry, id_of, load, pts_arg, Sheet};
use crate::{agent, support};
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

type Rec = BTreeMap<String, String>;

/// Altium's sheet styles (TSheetStyle order) and their size in mil, landscape.
const PAGES: &[(&str, i64, i64, i64)] = &[
    ("A4", 0, 11500, 7600), ("A3", 1, 15500, 11100), ("A2", 2, 22300, 15700), ("A1", 3, 31500, 22300), ("A0", 4, 44600, 31500),
    ("A", 5, 9500, 7500), ("B", 6, 15000, 9500), ("C", 7, 20000, 15000), ("D", 8, 32000, 20000), ("E", 9, 42000, 32000),
    ("USLetter", 10, 11000, 8500), ("USLegal", 11, 14000, 8500), ("USLedger", 12, 17000, 11000),
];

fn r2(v: f64) -> f64 { (v * 100.0).round() / 100.0 }

/// The title block's standard names and the Altium document parameters behind them.
const TITLE: &[(&str, &str)] = &[("title", "Title"), ("date", "Date"), ("rev", "Revision"), ("company", "CompanyName")];

fn doc_params(set: &[String]) -> Result<Vec<Value>, Value> {
    let r = agent::call("doc_params", &[("params", set.join(";"))], None, Duration::from_secs(60));
    let d = agent_data(&r)?;
    Ok(d["params"].as_array().cloned().unwrap_or_default())
}

fn title_block(params: &[Value]) -> Value {
    let get = |n: &str| params.iter().find(|p| st(&p["name"]).eq_ignore_ascii_case(n)).map(|p| st(&p["value"])).unwrap_or_default();
    let mut tb = serde_json::Map::new();
    for (k, n) in TITLE { tb.insert(k.to_string(), json!(get(n))); }
    let mut comments = Vec::new();
    for i in 1..=9 { let c = get(&format!("Comment{i}")); if c.is_empty() { break; } comments.push(json!(c)); }
    tb.insert("comments".into(), json!(comments));
    Value::Object(tb)
}

/// The page as the standard reports it: paper, size in mm, orientation.
fn page_of(sh: &Sheet) -> Value {
    let pg = &sh.page;
    let portrait = pg["orientation"].as_i64() == Some(1);
    let (name, w, h) = if pg["custom"].as_bool() == Some(true) {
        ("custom".to_string(), sh.mm(pg["cx"].as_i64().unwrap_or(0)), sh.mm(pg["cy"].as_i64().unwrap_or(0)))
    } else {
        let s = pg["style"].as_i64().unwrap_or(-1);
        match PAGES.iter().find(|p| p.1 == s) { Some(p) => (p.0.to_string(), r2(p.2 as f64 * 0.0254), r2(p.3 as f64 * 0.0254)), None => (format!("altium style {s}"), 0.0, 0.0) }
    };
    let (w, h) = if portrait { (w.min(h), w.max(h)) } else { (w.max(h), w.min(h)) };
    json!({"paper": name, "widthMm": w, "heightMm": h, "orientation": if portrait { "portrait" } else { "landscape" }})
}

/// The page step (A|style|custom|cx|cy|orientation) and the title block's parameters for page/create arguments.
fn page_changes(sh: &Sheet, args: &Value) -> Result<(Option<String>, Vec<String>), Value> {
    let mut step = None;
    let paper = args.get("paper").and_then(|v| v.as_str());
    let orient = args.get("orientation").and_then(|v| v.as_str());
    if paper.is_some() || orient.is_some() {
        let o = match orient { Some("portrait") => "1", Some("landscape") => "0", Some(x) => return Err(bad(format!("orientation {x}: portrait or landscape"))), None => "" };
        let (style, custom, cx, cy) = match paper {
            None => (String::new(), String::new(), String::new(), String::new()),
            Some(p) if p.eq_ignore_ascii_case("custom") || p.eq_ignore_ascii_case("A5") => {
                let (w, h) = if p.eq_ignore_ascii_case("A5") { (210.0, 148.0) } else {
                    match (args.get("widthMm").and_then(|v| v.as_f64()), args.get("heightMm").and_then(|v| v.as_f64())) { (Some(w), Some(h)) => (w, h), _ => return Err(bad("custom paper needs widthMm and heightMm")) }
                };
                (String::new(), "1".into(), sh.raw(w.max(h)).to_string(), sh.raw(w.min(h)).to_string())
            }
            Some(p) => match PAGES.iter().find(|x| x.0.eq_ignore_ascii_case(p) || (p.eq_ignore_ascii_case("Letter") && x.0 == "USLetter") || (p.eq_ignore_ascii_case("Tabloid") && x.0 == "USLedger")) {
                Some(x) => (x.1.to_string(), "0".into(), String::new(), String::new()),
                None => return Err(bad(format!("paper {p}: A4 to A0, A5, A to E, USLetter, USLegal, USLedger or custom"))),
            },
        };
        step = Some(format!("A|{style}|{custom}|{cx}|{cy}|{o}"));
    }
    let mut params = Vec::new();
    for (k, n) in TITLE { if let Some(v) = args.get(*k).and_then(|v| v.as_str()) { params.push(format!("{n}={}", clean(v).replace(';', ","))); } }
    if let Some(cs) = args.get("comments").and_then(|v| v.as_array()) {
        for (i, c) in cs.iter().enumerate() { params.push(format!("Comment{}={}", i + 1, clean(&st(c)).replace(';', ","))); }
    }
    Ok((step, params))
}

/// altium_sch_page {sheet, paper?, orientation?, widthMm?, heightMm?, title?, date?, rev?, company?, comments?, dryRun, save}
pub fn page(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let (step, params) = match page_changes(&sh, args) { Ok(x) => x, Err(e) => return e };
    let changed = step.is_some() || !params.is_empty();
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "now": page_of(&sh), "pageStep": step, "set": params}); }
    if let Some(s) = &step { if let Err(e) = apply(args, &[s.clone()]) { return e; } }
    let ps = match doc_params(&params) { Ok(p) => p, Err(e) => return e };
    let sh2 = if step.is_some() { match load(args) { Ok((_, s)) => s, Err(e) => return e } } else { sh };
    let mut out = page_of(&sh2);
    out["success"] = json!(true); out["sheet"] = json!(sheet); out["titleBlock"] = title_block(&ps); out["changed"] = json!(changed);
    out["saved"] = if changed { maybe_save(args, &sheet) } else { json!(false) };
    out["_hint"] = json!("Altium's title block shows Title, Date, Revision and CompanyName through its special strings; comments are kept as parameters Comment1, Comment2... (a template shows them only if it has =Comment1 strings). Shrinking the paper moves nothing.");
    out
}

// -- reading sheet files without Altium ------------------------------------------------------------------------------

fn file_records(path: &str) -> Result<Vec<Rec>, String> {
    let b = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
    let s = cfb_streams(&b)?;
    let fh = s.get("FileHeader").ok_or("no FileHeader stream")?;
    let recs = records(fh);
    Ok(if recs.first().map(|r| r.contains_key("HEADER")).unwrap_or(false) { recs[1..].to_vec() } else { recs })
}

fn num(r: &Rec, k: &str) -> i64 { r.get(k).and_then(|v| v.parse::<i64>().ok()).unwrap_or(0) }
/// mil from a 10-mil value and its _FRAC (1/100000 of one)
fn mil(r: &Rec, k: &str) -> f64 { (num(r, k) as f64 + num(r, &format!("{k}_FRAC")) as f64 / 100_000.0) * 10.0 }
fn mm(v: f64) -> f64 { (v * 0.0254 * 10000.0).round() / 10000.0 }

#[derive(Debug, Clone, Default)]
pub struct SymRec { pub name: String, pub file: String, pub at: (f64, f64), pub size: (f64, f64), pub entries: Vec<(String, i64, f64, i64)> }

/// Sheet symbols of a sheet file (record 15) with their name (32), file (33) and entries (16); mil. Pure.
pub fn sheet_symbols(recs: &[Rec]) -> Vec<SymRec> {
    let mut out = Vec::new();
    for (i, r) in recs.iter().enumerate() {
        if r.get("RECORD").map(|v| v.as_str()) != Some("15") { continue; }
        let mut s = SymRec { at: (mil(r, "LOCATION.X"), mil(r, "LOCATION.Y")), size: (mil(r, "XSIZE"), mil(r, "YSIZE")), ..Default::default() };
        for c in recs.iter().filter(|c| c.get("OWNERINDEX").and_then(|v| v.parse::<usize>().ok()) == Some(i)) {
            match c.get("RECORD").map(|v| v.as_str()) {
                Some("32") => s.name = c.get("TEXT").cloned().unwrap_or_default(),
                Some("33") => s.file = c.get("TEXT").cloned().unwrap_or_default(),
                Some("16") => s.entries.push((c.get("NAME").cloned().unwrap_or_default(), num(c, "SIDE"), mil(c, "DISTANCEFROMTOP"), num(c, "IOTYPE"))),
                _ => {}
            }
        }
        out.push(s);
    }
    out
}

/// The sheet's own parameter (record 41 without an owner part), e.g. SheetNumber.
pub fn sheet_param(recs: &[Rec], name: &str) -> Option<String> {
    recs.iter().find(|r| r.get("RECORD").map(|v| v.as_str()) == Some("41") && r.get("NAME").map(|n| n.eq_ignore_ascii_case(name)).unwrap_or(false)
        && r.get("OWNERINDEX").map(|o| o.parse::<i64>().unwrap_or(-1) < 0).unwrap_or(true)).and_then(|r| r.get("TEXT").cloned())
}

/// The ports of a sheet file (record 18): name and Altium IOType.
pub fn ports(recs: &[Rec]) -> Vec<(String, i64)> {
    recs.iter().filter(|r| r.get("RECORD").map(|v| v.as_str()) == Some("18")).map(|r| (r.get("NAME").cloned().unwrap_or_default(), num(r, "IOTYPE"))).collect()
}

fn kind_of(io: i64) -> &'static str { match io { 1 => "output", 2 => "input", 3 => "bidirectional", _ => "passive" } }
fn io_of(kind: &str) -> i64 { match kind { "output" => 1, "input" => 2, "bidirectional" | "tri_state" => 3, _ => 0 } }
fn side_name(s: i64) -> &'static str { match s { 1 => "right", 2 => "top", 3 => "bottom", _ => "left" } }
fn side_of(s: &str) -> i64 { match s { "right" => 1, "top" => 2, "bottom" => 3, _ => 0 } }

fn resolve(dir: &Path, f: &str) -> PathBuf { let p = Path::new(f); if p.is_absolute() || f.contains(':') { p.to_path_buf() } else { dir.join(f.replace('\\', "/").replace('/', std::path::MAIN_SEPARATOR_STR)) } }

/// A project's sheets (DocumentPath entries ending .SchDoc), absolute.
fn project_sheets(prj: &str) -> Result<Vec<String>, Value> {
    let text = std::fs::read(prj).map(|b| String::from_utf8_lossy(&b).to_string()).map_err(|e| json!({"success": false, "errorCode": "project_not_found", "error": format!("{prj}: {e}")}))?;
    let dir = Path::new(prj).parent().unwrap_or(Path::new(".")).to_path_buf();
    Ok(text.lines().filter_map(|l| l.trim().strip_prefix("DocumentPath=")).filter(|d| d.to_lowercase().ends_with(".schdoc")).map(|d| resolve(&dir, d).to_string_lossy().to_string()).collect())
}

/// The root sheet of a project: the sheet no sheet symbol points to.
fn project_root(prj: &str) -> Result<String, Value> {
    let sheets = project_sheets(prj)?;
    let mut children = std::collections::BTreeSet::new();
    for s in &sheets {
        let dir = Path::new(s).parent().unwrap_or(Path::new(".")).to_path_buf();
        if let Ok(r) = file_records(s) { for sy in sheet_symbols(&r) { children.insert(resolve(&dir, &sy.file).to_string_lossy().to_lowercase()); } }
    }
    sheets.iter().find(|s| !children.contains(&s.to_lowercase())).cloned().ok_or_else(|| json!({"success": false, "errorCode": "no_root", "error": "every sheet of the project is somebody's child: no root"}))
}

fn tree(file: &str, name: &str, path: &str, ancestors: &mut Vec<String>, problems: &mut Vec<Value>, order: &mut Vec<(String, String, Option<i64>)>, sym: Option<&SymRec>) -> Value {
    let mut node = json!({"name": name, "file": file, "id": format!("sheet-{}", &crate::routing::fnv(path)[..10]), "path": path});
    if let Some(s) = sym {
        node["at"] = json!([mm(s.at.0), mm(s.at.1)]);
        node["sizeMm"] = json!([mm(s.size.0), mm(s.size.1)]);
        node["pins"] = json!(s.entries.iter().map(|(n, _, _, io)| json!({"name": n, "kind": kind_of(*io)})).collect::<Vec<_>>());
    }
    if ancestors.iter().any(|a| a.eq_ignore_ascii_case(file)) { problems.push(json!({"sheet": path, "problem": "recursive"})); return node; }
    let recs = match file_records(file) {
        Ok(r) => r,
        Err(e) => { problems.push(json!({"sheet": path, "problem": if Path::new(file).exists() { "unreadable" } else { "missing" }, "detail": e})); return node; }
    };
    let page = sheet_param(&recs, "SheetNumber").and_then(|v| v.trim().parse::<i64>().ok());
    node["page"] = json!(page);
    order.push((file.to_string(), path.to_string(), page));
    ancestors.push(file.to_string());
    let dir = Path::new(file).parent().unwrap_or(Path::new(".")).to_path_buf();
    let kids: Vec<Value> = sheet_symbols(&recs).iter().map(|s| {
        let f = resolve(&dir, &s.file).to_string_lossy().to_string();
        tree(&f, &s.name, &format!("{path}/{}", s.name), ancestors, problems, order, Some(s))
    }).collect();
    ancestors.pop();
    node["children"] = json!(kids);
    node
}

/// altium_sch_hierarchy {sheet | project, renumber?, dryRun?}
pub fn hierarchy(args: &Value) -> Value {
    let root = match (support::s(args, "sheet"), support::s(args, "project").or_else(|| support::s(args, "projectPath"))) {
        (Some(s), _) => s,
        (None, Some(p)) => match project_root(&p) { Ok(r) => r, Err(e) => return e },
        _ => return bad("give sheet (the root sheet) or project"),
    };
    let stem = Path::new(&root).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
    let (mut problems, mut order) = (vec![], vec![]);
    let t = tree(&root, &stem, &format!("/{stem}"), &mut vec![], &mut problems, &mut order, None);
    let mut seen: BTreeMap<i64, usize> = BTreeMap::new();
    for (_, _, p) in &order { if let Some(p) = p { *seen.entry(*p).or_default() += 1; } }
    let dups: Vec<i64> = seen.iter().filter(|(_, n)| **n > 1).map(|(p, _)| *p).collect();
    let mut out = json!({"success": true, "root": root, "tree": [t], "problems": problems, "duplicatePages": dups,
        "_hint": "Read from the saved files, without Altium. A file used by two sheet symbols appears twice (one instance each). renumber:true writes SheetNumber depth-first from the root."});
    if args.get("renumber").and_then(|v| v.as_bool()) == Some(true) {
        // depth-first numbers; a file used twice keeps its first number
        let mut done: Vec<String> = Vec::new();
        let mut plan = Vec::new();
        for (f, path, page) in &order {
            if done.iter().any(|d| d.eq_ignore_ascii_case(f)) { continue; }
            done.push(f.clone());
            let want = done.len() as i64;
            if *page != Some(want) { plan.push((f.clone(), path.clone(), *page, want)); }
        }
        let renum: Vec<Value> = plan.iter().map(|(_, p, from, to)| json!({"sheet": p, "from": from, "to": to})).collect();
        out["renumbered"] = json!(renum);
        if !dry(args) {
            if let Some(g) = support::need_licensed() { return g; }
            for (f, _, _, to) in &plan {
                if let Some(e) = support::must_open(f, 60) { return e; }
                if let Err(e) = doc_params(&[format!("SheetNumber={to}"), format!("SheetTotal={}", done.len())]) { return e; }
                let _ = maybe_save(args, f);
            }
        } else { out["dryRun"] = json!(true); }
    }
    out
}

// -- sheet symbol pins -------------------------------------------------------------------------------------------------

/// altium_sch_sheet_pins {sheet, sheetSymbol?, action: list|add|edit|delete, name, kind, side, at, newName, import, validate, dryRun, save}
pub fn sheet_pins(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let dir = Path::new(&sheet).parent().unwrap_or(Path::new(".")).to_path_buf();
    let syms: Vec<&schwire::Item> = sh.items.iter().filter(|it| it.t == 'S').collect();
    let want = args.get("sheetSymbol").and_then(|v| v.as_str());
    let picked: Vec<&schwire::Item> = match want {
        Some(w) => syms.iter().filter(|s| s.text.eq_ignore_ascii_case(w) || id_of(&s.key) == w).cloned().collect(),
        None => syms.clone(),
    };
    if picked.is_empty() { return json!({"success": false, "errorCode": "not_found", "error": if syms.is_empty() { "no sheet symbol on this sheet".to_string() } else { format!("no sheet symbol {}", want.unwrap_or("")) }}); }
    let list = |s: &schwire::Item| -> Vec<Value> { s.entries.iter().map(|(n, side, dist, io)| json!({"id": format!("{}/{n}", id_of(&s.key)), "name": n, "kind": kind_of(*io), "side": side_name(*side), "at": sh.pt(schwire::entry_point(s, *side, *dist))})).collect() };
    let action = args.get("action").and_then(|v| v.as_str()).unwrap_or("list");
    let child_ports = |s: &schwire::Item| -> Result<Vec<(String, i64)>, String> { let f = resolve(&dir, &s.file); file_records(&f.to_string_lossy()).map(|r| ports(&r)) };
    // validate: every symbol's pins against its child's ports
    if args.get("validate").and_then(|v| v.as_bool()) == Some(true) {
        let mut problems = Vec::new();
        for s in &picked {
            match child_ports(s) {
                Err(e) => problems.push(json!({"sheetSymbol": s.text, "problem": "child_unreadable", "detail": e})),
                Ok(ps) => {
                    for (n, _, _, io) in &s.entries {
                        match ps.iter().find(|(p, _)| p.eq_ignore_ascii_case(n)) {
                            None => problems.push(json!({"sheetSymbol": s.text, "pin": n, "problem": "no_port"})),
                            Some((_, pio)) if *pio != *io && *io != 0 && *pio != 0 => problems.push(json!({"sheetSymbol": s.text, "pin": n, "problem": "kind_mismatch", "pinKind": kind_of(*io), "portKind": kind_of(*pio)})),
                            _ => {}
                        }
                    }
                    for (p, _) in &ps { if !s.entries.iter().any(|(n, ..)| n.eq_ignore_ascii_case(p)) { problems.push(json!({"sheetSymbol": s.text, "pin": p, "problem": "no_pin"})); } }
                }
            }
        }
        return json!({"success": true, "sheet": sheet, "problems": problems, "pins": picked.iter().flat_map(|s| list(s)).collect::<Vec<_>>(),
            "_hint": "no_port: a pin with no port of that name inside the child; no_pin: a port with no pin on the symbol (import:true adds them)."});
    }
    let import = args.get("import").and_then(|v| v.as_bool()) == Some(true);
    if action == "list" && !import { return json!({"success": true, "sheet": sheet, "pins": picked.iter().flat_map(|s| list(s)).collect::<Vec<_>>()}); }
    if picked.len() != 1 { return bad("name the sheet symbol (sheetSymbol: its name or id) to change its pins"); }
    let s = picked[0];
    let step = sh.raw(2.54);
    // the first free slot on a side, 2.54 mm apart from 2.54 mm in
    let free_slot = |side: i64, taken: &[(i64, i64)]| -> i64 {
        let len = if side >= 2 { s.w } else { s.h };
        (1..).map(|k| k * step).find(|d| *d >= len || !taken.iter().any(|(sd, t)| *sd == side && (t - d).abs() < step / 2)).unwrap_or(step)
    };
    let mut taken: Vec<(i64, i64)> = s.entries.iter().map(|(_, sd, d, _)| (*sd, *d)).collect();
    let snap = |at: (f64, f64), side: Option<i64>| -> (i64, i64) {
        let p = (sh.raw(at.0), sh.raw(at.1));
        // the nearest edge unless a side is given; distance from the top (left/right) or the left (top/bottom)
        let d = [(0, (p.0 - s.at.0).abs()), (1, (p.0 - s.at.0 - s.w).abs()), (2, (p.1 - s.at.1).abs()), (3, (p.1 - s.at.1 + s.h).abs())];
        let sd = side.unwrap_or_else(|| d.iter().min_by_key(|x| x.1).unwrap().0);
        let dist = if sd >= 2 { p.0 - s.at.0 } else { s.at.1 - p.1 };
        (sd, (dist as f64 / step as f64).round() as i64 * step)
    };
    let mut ops = Vec::new();
    let mut added = Vec::new();
    if import {
        let ps = match child_ports(s) { Ok(p) => p, Err(e) => return json!({"success": false, "errorCode": "child_unreadable", "error": e}) };
        for (p, io) in ps.iter().filter(|(p, _)| !s.entries.iter().any(|(n, ..)| n.eq_ignore_ascii_case(p))) {
            let side = if *io == 2 { 0 } else { 1 };
            let d = free_slot(side, &taken);
            taken.push((side, d));
            ops.push(format!("Y|{}|{}|{side}|{d}|{io}", s.key, clean(p)));
            added.push(json!(p));
        }
    } else {
        let name = clean(&st(&args["name"]));
        if name.is_empty() { return bad("name (the pin) is required"); }
        let kind = args.get("kind").and_then(|v| v.as_str());
        let side_arg = args.get("side").and_then(|v| v.as_str()).map(side_of);
        let at = args.get("at").and_then(pts_arg);
        match action {
            "add" => {
                if s.entries.iter().any(|(n, ..)| n.eq_ignore_ascii_case(&name)) { return json!({"success": false, "errorCode": "exists", "error": format!("{name} is already a pin of {}", s.text)}); }
                let io = io_of(kind.unwrap_or("passive"));
                let (sd, d) = match at { Some(a) => snap(a, side_arg), None => { let sd = side_arg.unwrap_or(if io == 2 { 0 } else { 1 }); (sd, free_slot(sd, &taken)) } };
                ops.push(format!("Y|{}|{name}|{sd}|{d}|{io}", s.key));
                added.push(json!(name));
            }
            "edit" => {
                if !s.entries.iter().any(|(n, ..)| n.eq_ignore_ascii_case(&name)) { return json!({"success": false, "errorCode": "not_found", "error": format!("no pin {name}")}); }
                let nn = args.get("newName").and_then(|v| v.as_str()).map(clean).unwrap_or_default();
                let (sd, d) = match at { Some(a) => { let (a1, b1) = snap(a, side_arg); (a1.to_string(), b1.to_string()) } None => (side_arg.map(|x| x.to_string()).unwrap_or_default(), String::new()) };
                ops.push(format!("Q|{}|{name}|{nn}|{sd}|{d}|{}", s.key, kind.map(|k| io_of(k).to_string()).unwrap_or_default()));
            }
            "delete" => ops.push(format!("Z|{}|{name}", s.key)),
            o => return bad(format!("action {o}: list, add, edit or delete")),
        }
    }
    if ops.is_empty() { return json!({"success": true, "sheet": sheet, "added": [], "pins": list(s), "_hint": "Nothing to do: every port of the child already has a pin."}); }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "steps": ops.len(), "added": added}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    let after = match load(args) { Ok((_, s2)) => s2, Err(e) => return e };
    let ns = after.items.iter().find(|it| it.t == 'S' && it.text == s.text && it.at == s.at);
    let pins: Vec<Value> = ns.map(|n| n.entries.iter().map(|(nm, side, dist, io)| json!({"id": format!("{}/{nm}", id_of(&n.key)), "name": nm, "kind": kind_of(*io), "side": side_name(*side), "at": after.pt(schwire::entry_point(n, *side, *dist))})).collect()).unwrap_or_default();
    json!({"success": schwire::failed(&res).is_empty(), "sheet": sheet, "pins": pins, "added": added, "failed": schwire::failed(&res), "saved": maybe_save(args, &sheet),
        "_hint": "A pin joins the child's port of the same name: wire it on this sheet at its at. Renaming a pin does not rename the port inside the child: check with validate:true."})
}

// -- part fields back where the library put them ------------------------------------------------------------------------

/// The library's designator and comment offsets (mil, from the symbol's origin), orientation and justification for
/// one symbol of a SchLib file. Pure over the file's streams.
pub fn lib_fields(streams: &BTreeMap<String, Vec<u8>>, libref: &str) -> Option<[(f64, f64, i64, i64); 2]> {
    for (name, data) in streams {
        if !name.ends_with("Data") { continue; }
        let recs = records(data);
        let Some(c) = recs.iter().find(|r| r.get("RECORD").map(|v| v.as_str()) == Some("1")) else { continue };
        if !c.get("LIBREFERENCE").map(|l| l.eq_ignore_ascii_case(libref)).unwrap_or(false) { continue; }
        let f = |rec: Option<&Rec>| rec.map(|r| (mil(r, "LOCATION.X"), mil(r, "LOCATION.Y"), num(r, "ORIENTATION"), num(r, "JUSTIFICATION"))).unwrap_or((0.0, 0.0, 0, 0));
        let des = recs.iter().find(|r| r.get("RECORD").map(|v| v.as_str()) == Some("34"));
        let cmt = recs.iter().find(|r| r.get("RECORD").map(|v| v.as_str()) == Some("41") && r.get("NAME").map(|n| n.eq_ignore_ascii_case("Comment")).unwrap_or(false));
        return Some([f(des), f(cmt)]);
    }
    None
}

/// An offset in the symbol's frame turned into the sheet's: mirrored in x first, then rotated by quarter turns.
pub fn place_offset(off: (f64, f64), rot: i64, mirror: bool) -> (f64, f64) {
    let (mut x, y) = off;
    if mirror { x = -x; }
    match rot.rem_euclid(4) { 1 => (-y, x), 2 => (-x, -y), 3 => (y, -x), _ => (x, y) }
}

/// The libraries to look a symbol up in: its own library path when that is a file, else every .SchLib beside the
/// sheet (Altium writes "*", any library, for parts placed from an open library).
fn candidate_libs(lib_path: &str, sheet: &str) -> Vec<String> {
    if !lib_path.is_empty() && lib_path != "*" && Path::new(lib_path).is_file() { return vec![lib_path.to_string()]; }
    let dir = Path::new(sheet).parent().unwrap_or(Path::new(".")).to_path_buf();
    let mut v: Vec<String> = std::fs::read_dir(&dir).map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.path()).filter(|p| p.extension().map(|x| x.eq_ignore_ascii_case("schlib")).unwrap_or(false)).map(|p| p.to_string_lossy().to_string()).collect()).unwrap_or_default();
    v.sort();
    v
}

fn find_in_libs<T>(libs: &mut BTreeMap<String, Option<BTreeMap<String, Vec<u8>>>>, cands: &[String], f: impl Fn(&BTreeMap<String, Vec<u8>>) -> Option<T>) -> Option<(String, T)> {
    for c in cands {
        let streams = libs.entry(c.clone()).or_insert_with(|| std::fs::read(c).ok().and_then(|b| cfb_streams(&b).ok()));
        if let Some(t) = streams.as_ref().and_then(|s| f(s)) { return Some((c.clone(), t)); }
    }
    None
}

/// altium_sch_reset_fields {sheet, references? | all, fields?, dryRun, save}
pub fn reset_fields(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let all = args.get("all").and_then(|v| v.as_bool()) == Some(true);
    let refs: Vec<String> = args.get("references").and_then(|v| v.as_array()).map(|a| a.iter().map(|x| st(x).to_uppercase()).collect()).unwrap_or_default();
    if !all && refs.is_empty() { return bad("give references or all:true"); }
    let fields: Vec<String> = args.get("fields").and_then(|v| v.as_array()).map(|a| a.iter().map(|x| st(x).to_lowercase()).collect()).unwrap_or(vec!["designator".into(), "value".into()]);
    let mut libs: BTreeMap<String, Option<BTreeMap<String, Vec<u8>>>> = BTreeMap::new();
    let (mut ops, mut reset, mut fails) = (vec![], vec![], vec![]);
    for c in sh.comps.iter().filter(|c| all || refs.contains(&c.r.to_uppercase())) {
        let cands = candidate_libs(&c.lib_path, &sheet);
        let Some((_, fs)) = find_in_libs(&mut libs, &cands, |st| lib_fields(st, &c.lib)) else {
            fails.push(json!({"ref": c.r, "error": format!("{} is in none of {:?} (an integrated or database library part has no .SchLib to read)", c.lib, cands)}));
            continue;
        };
        for (k, (field, f)) in [("designator", fs[0]), ("comment", fs[1])].iter().enumerate() {
            let asked = fields.iter().any(|x| x == field || (*field == "comment" && x == "value"));
            if !asked { continue; }
            let _ = k;
            let (dx, dy) = place_offset((f.0, f.1), c.rot, c.mirror);
            let (x, y) = (c.at.0 + sh.raw(dx * 0.0254), c.at.1 + sh.raw(dy * 0.0254));
            ops.push(format!("F|{}|{field}|{x}|{y}|{}|{}", c.r, (f.2 + c.rot).rem_euclid(4), f.3));
            reset.push(json!({"ref": c.r, "field": if *field == "comment" { "value" } else { "designator" }, "at": sh.pt((x, y))}));
        }
    }
    if ops.is_empty() { return json!({"success": false, "errorCode": "nothing_to_do", "error": "no field could be reset", "failed": fails}); }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "reset": reset, "failed": fails}); }
    let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };
    json!({"success": fails.is_empty() && schwire::failed(&res).is_empty(), "sheet": sheet, "reset": reset, "failed": fails, "stepsFailed": schwire::failed(&res), "saved": maybe_save(args, &sheet),
        "_hint": "Positions come from the symbol's library file (the part's library path), turned and mirrored with the part. Font and visibility are untouched."})
}

// -- placed symbols updated from their libraries ------------------------------------------------------------------------

fn lib_pins(streams: &BTreeMap<String, Vec<u8>>, libref: &str) -> Option<Vec<String>> {
    for (name, data) in streams {
        if !name.ends_with("Data") { continue; }
        let recs = records(data);
        let Some(c) = recs.iter().find(|r| r.get("RECORD").map(|v| v.as_str()) == Some("1")) else { continue };
        if !c.get("LIBREFERENCE").map(|l| l.eq_ignore_ascii_case(libref)).unwrap_or(false) { continue; }
        let mut pins: Vec<String> = recs.iter().filter(|r| r.get("RECORD").map(|v| v.as_str()) == Some("2")).filter_map(|r| r.get("DESIGNATOR").cloned()).collect();
        pins.extend(binary_pins(data).into_iter().map(|p| p.1));
        pins.sort(); pins.dedup();
        return Some(pins);
    }
    None
}

/// The pins a SchLib stores as binary records (record type 1): (name, designator). The layout (record id 2, flags,
/// owner part, edges, description, types, length, location, colour, then name and designator as length-prefixed
/// strings) is Altium's binary pin record. Pure.
pub fn binary_pins(data: &[u8]) -> Vec<(String, String)> {
    let mut out = Vec::new();
    let mut i = 0;
    let pstr = |b: &[u8], at: &mut usize| -> Option<String> { let n = *b.get(*at)? as usize; let s = b.get(*at + 1..*at + 1 + n)?; *at += 1 + n; Some(s.iter().map(|&c| c as char).collect()) };
    while i + 4 <= data.len() {
        let n = u32::from_le_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]);
        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 != 1 || body.len() < 12 || u32::from_le_bytes([body[0], body[1], body[2], body[3]]) != 2 { continue; }
        // 4 id, 1 unknown, 2 owner part, 1 display mode, 4 symbol edges
        let mut at = 12;
        let Some(_desc) = pstr(body, &mut at) else { continue };
        at += 3 + 2 + 2 + 2 + 4; // formal type, electrical, conglomerate; length; x; y; colour
        let (Some(name), Some(des)) = (pstr(body, &mut at), pstr(body, &mut at)) else { continue };
        out.push((name, des));
    }
    out
}

/// altium_sch_update_from_library {sheet, symbols?, library?, force?, dryRun, save}
pub fn update_from_library(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let only: Option<Vec<String>> = args.get("symbols").and_then(|v| v.as_array()).map(|a| a.iter().map(|x| st(x).to_uppercase()).collect());
    let lib_arg = support::s(args, "library");
    let force = args.get("force").and_then(|v| v.as_bool()) == Some(true);
    let g = schwire::graph(&sh);
    let nets = schwire::nets(&sh, &g);
    let connected = |pin: &str| nets.iter().any(|n| n["pins"].as_array().map(|a| a.iter().any(|x| st(x) == pin) && (a.len() > 1 || !n["labels"].as_array().map(|l| l.is_empty()).unwrap_or(true))).unwrap_or(false));
    let (mut changed, mut unchanged, mut not_found, mut refused, mut todo) = (vec![], vec![], vec![], vec![], vec![]);
    let mut libs: BTreeMap<String, Option<BTreeMap<String, Vec<u8>>>> = BTreeMap::new();
    for c in &sh.comps {
        if let Some(o) = &only { if !o.contains(&c.lib.to_uppercase()) && !o.contains(&c.r.to_uppercase()) { continue; } }
        let cands = match &lib_arg { Some(l) => vec![l.clone()], None => candidate_libs(&c.lib_path, &sheet) };
        let Some((lp, lpins)) = find_in_libs(&mut libs, &cands, |st| lib_pins(st, &c.lib)) else { not_found.push(json!({"symbol": c.lib, "ref": c.r, "searched": cands})); continue; };
        let mut placed: Vec<String> = sh.pins.iter().filter(|p| p.r == c.r).map(|p| p.num.clone()).collect();
        placed.sort(); placed.dedup();
        let added: Vec<&String> = lpins.iter().filter(|p| !placed.contains(p)).collect();
        let removed: Vec<&String> = placed.iter().filter(|p| !lpins.contains(p)).collect();
        let dropped: Vec<&String> = removed.iter().filter(|p| connected(&format!("{}.{}", c.r, p))).cloned().collect();
        if !dropped.is_empty() && !force { refused.push(json!({"symbol": c.lib, "ref": c.r, "droppedPins": dropped})); continue; }
        if added.is_empty() && removed.is_empty() && only.is_none() && lib_arg.is_none() { unchanged.push(json!({"symbol": c.lib, "ref": c.r})); continue; }
        changed.push(json!({"symbol": c.lib, "ref": c.r, "pinsAdded": added, "pinsRemoved": removed}));
        todo.push((c.r.clone(), lp, c.lib.clone()));
    }
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "changed": changed, "unchanged": unchanged, "notFound": not_found, "refused": refused}); }
    let mut fails = Vec::new();
    for (r, lp, sym) in &todo {
        let res = crate::sch::swap_part(&json!({"sheet": sheet, "designator": r, "library": lp, "symbol": sym, "keepComment": true, "save": false}));
        if res.get("success").and_then(|b| b.as_bool()) != Some(true) { fails.push(json!({"ref": r, "error": res})); }
    }
    json!({"success": fails.is_empty(), "sheet": sheet, "changed": changed, "unchanged": unchanged, "notFound": not_found, "refused": refused, "failed": fails, "saved": maybe_save(args, &sheet),
        "_hint": "unchanged: the library symbol has the same pins (Altium cannot compare graphics from the sheet; name the symbols, or give library, to re-place them anyway). A changed symbol is re-placed from its library where it stood, keeping its designator and comment, with a wire from each moved pin's old end. Check with altium_compile."})
}

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

    fn rec(kv: &[(&str, &str)]) -> Rec { kv.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect() }

    #[test]
    fn sheet_symbols_carry_their_name_file_and_entries() {
        let recs = vec![
            rec(&[("RECORD", "1")]),
            rec(&[("RECORD", "15"), ("LOCATION.X", "1000"), ("LOCATION.Y", "600"), ("XSIZE", "140"), ("YSIZE", "40")]),
            rec(&[("RECORD", "32"), ("OWNERINDEX", "1"), ("TEXT", "Power")]),
            rec(&[("RECORD", "33"), ("OWNERINDEX", "1"), ("TEXT", "Power.SchDoc")]),
            rec(&[("RECORD", "16"), ("OWNERINDEX", "1"), ("NAME", "VIN"), ("SIDE", "0"), ("DISTANCEFROMTOP", "10"), ("IOTYPE", "2")]),
            rec(&[("RECORD", "41"), ("NAME", "SheetNumber"), ("TEXT", "3")]),
        ];
        let s = sheet_symbols(&recs);
        assert_eq!(s.len(), 1);
        assert_eq!((s[0].name.as_str(), s[0].file.as_str()), ("Power", "Power.SchDoc"));
        assert_eq!(s[0].at, (10000.0, 6000.0));
        assert_eq!(s[0].size, (1400.0, 400.0));
        assert_eq!(s[0].entries, vec![("VIN".to_string(), 0, 100.0, 2)]);
        assert_eq!(sheet_param(&recs, "SheetNumber").as_deref(), Some("3"));
    }

    #[test]
    fn field_offsets_turn_and_mirror_with_the_part() {
        assert_eq!(place_offset((100.0, 50.0), 0, false), (100.0, 50.0));
        assert_eq!(place_offset((100.0, 50.0), 1, false), (-50.0, 100.0));
        assert_eq!(place_offset((100.0, 50.0), 2, false), (-100.0, -50.0));
        assert_eq!(place_offset((100.0, 50.0), 0, true), (-100.0, 50.0));
    }

    #[test]
    fn a_schlib_lists_its_symbols() {
        // a real SchLib when ADOM_SCHLIB names one, else skipped
        let Ok(p) = std::env::var("ADOM_SCHLIB") else { return };
        let st = cfb_streams(&std::fs::read(p).unwrap()).unwrap();
        for (n, d) in &st { let r = records(d); eprintln!("{n}: {} recs, first {:?}, binary pins {:?}", r.len(), r.first().map(|x| (x.get("RECORD"), x.get("LIBREFERENCE"))), binary_pins(d)); }
    }

    #[test]
    fn binary_pin_records_give_name_and_designator() {
        let mut body = vec![2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0];
        body.push(0); // description
        body.extend([4, 4, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // types (3), length, x, y (2 each), colour (4)
        body.push(4); body.extend(b"OUT1");
        body.push(1); body.extend(b"1");
        let mut data = ((body.len() as u32) | (1 << 24)).to_le_bytes().to_vec();
        data.extend(&body);
        assert_eq!(binary_pins(&data), vec![("OUT1".to_string(), "1".to_string())]);
    }

    #[test]
    fn kinds_round_trip() {
        for k in ["input", "output", "bidirectional", "passive"] { assert_eq!(kind_of(io_of(k)), k); }
        assert_eq!(kind_of(io_of("tri_state")), "bidirectional");
    }
}

/// altium_sch_create {sheet, paper?, orientation?, widthMm?, heightMm?, title.., comments?, project?, sheetName?, at?, dryRun}
pub fn create(args: &Value) -> Value {
    let Some(path) = support::s(args, "sheet").filter(|p| p.to_lowercase().ends_with(".schdoc")) else { return bad("sheet (the .SchDoc path to create) is required") };
    if Path::new(&path).exists() { return json!({"success": false, "errorCode": "exists", "error": format!("{path} exists: sch_create never overwrites")}); }
    let prj = support::s(args, "project").or_else(|| support::s(args, "projectPath"));
    let root = match &prj { Some(p) => match project_root(p) { Ok(r) => Some(r), Err(e) => return e }, None => None };
    // the next page number: one past the project's highest
    let page_no = match &prj {
        Some(p) => project_sheets(p).unwrap_or_default().iter().filter_map(|s| file_records(s).ok().and_then(|r| sheet_param(&r, "SheetNumber")).and_then(|v| v.trim().parse::<i64>().ok())).max().unwrap_or(1) + 1,
        None => 1,
    };
    let name = support::s(args, "sheetName").unwrap_or_else(|| Path::new(&path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default());
    if dry(args) { return json!({"success": true, "dryRun": true, "sheet": path, "page": page_no, "root": root, "sheetName": name}); }
    if let Some(g) = support::need_licensed() { return g; }
    let tpl = match support::altium_public_file(r"Templates\ANSI B Landscape.SchDot") { Ok(p) => p, Err(e) => return json!({"success": false, "errorCode": "template_missing", "error": e}) };
    if let Err(e) = support::copy_template(&tpl, &path) { return json!({"success": false, "errorCode": "write_failed", "error": e}); }
    // page, title block and page number on the new sheet
    let mut a = args.clone();
    a["sheet"] = json!(path);
    a["dryRun"] = json!(false);
    let pg = page(&a);
    if pg.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "page_failed", "sheet": path, "reply": pg}); }
    if let Err(e) = doc_params(&[format!("SheetNumber={page_no}")]) { return e; }
    let _ = maybe_save(&json!({}), &path);
    let mut sym = Value::Null;
    if let (Some(p), Some(r)) = (&prj, &root) {
        if let Err(e) = crate::hier::add_to_project(p, &path) { return e; }
        let at = args.get("at").and_then(pts_arg);
        let mut sa = json!({"sheet": r, "child": path, "name": name, "entries": [], "ports": false, "projectPath": p});
        if let Some((x, y)) = at { sa["x"] = json!((x / 0.0254).round() as i64); sa["y"] = json!((y / 0.0254).round() as i64); }
        let ss = crate::hier::sheet_symbol(&sa);
        if ss.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "sheet_symbol_failed", "sheet": path, "reply": ss}); }
        let (_, rsh) = match load(&json!({"sheet": r})) { Ok(x) => x, Err(e) => return e };
        sym = rsh.items.iter().filter(|it| it.t == 'S' && it.text == name).last().map(|it| json!({"id": id_of(&it.key), "name": it.text, "at": rsh.pt(it.at)})).unwrap_or(Value::Null);
    }
    json!({"success": true, "sheet": path, "created": true, "page": page_no, "paper": pg["paper"], "sizeMm": [pg["widthMm"], pg["heightMm"]], "titleBlock": pg["titleBlock"], "sheetSymbol": sym, "root": root,
        "_hint": "Made from Altium's ANSI B Landscape template, then resized. A child sheet's symbol has no pins yet: put ports inside the child (altium_sch_connect kind port), then altium_sch_sheet_pins {import:true}."})
}

// -- a sheet as an image, without a window ---------------------------------------------------------------------------

/// PowerShell: render page 1 of a PDF to a PNG with Windows' own PDF renderer (Windows.Data.Pdf), then optionally
/// compare it with a baseline PNG pixel by pixel. Prints one JSON line.
pub(crate) const RENDER_PS: &str = r#"param([string]$Pdf, [string]$Png, [int]$Width, [int]$PageIndex = 0, [string]$Baseline = "", [string]$Diff = "")
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$m = [System.WindowsRuntimeSystemExtensions].GetMethods()
$asOp = ($m | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
$asAct = ($m | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncAction' })[0]
function Await($op, $t) { $k = $asOp.MakeGenericMethod($t).Invoke($null, @($op)); $k.Wait(-1) | Out-Null; $k.Result }
function AwaitAct($op) { $k = $asAct.Invoke($null, @($op)); $k.Wait(-1) | Out-Null }
[Windows.Storage.StorageFile, Windows.Storage, ContentType = WindowsRuntime] | Out-Null
[Windows.Storage.StorageFolder, Windows.Storage, ContentType = WindowsRuntime] | Out-Null
[Windows.Data.Pdf.PdfDocument, Windows.Data.Pdf, ContentType = WindowsRuntime] | Out-Null
$f = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync($Pdf)) ([Windows.Storage.StorageFile])
$doc = Await ([Windows.Data.Pdf.PdfDocument]::LoadFromFileAsync($f)) ([Windows.Data.Pdf.PdfDocument])
$ix = if ($PageIndex -lt 0) { [Math]::Max(0, $doc.PageCount + $PageIndex) } else { [Math]::Min($PageIndex, $doc.PageCount - 1) }
$pg = $doc.GetPage($ix)
$dir = Await ([Windows.Storage.StorageFolder]::GetFolderFromPathAsync([IO.Path]::GetDirectoryName($Png))) ([Windows.Storage.StorageFolder])
$out = Await ($dir.CreateFileAsync([IO.Path]::GetFileName($Png), [Windows.Storage.CreationCollisionOption]::ReplaceExisting)) ([Windows.Storage.StorageFile])
Add-Type -AssemblyName System.Drawing
function Render([int]$w) {
  $s = Await ($out.OpenAsync([Windows.Storage.FileAccessMode]::ReadWrite)) ([Windows.Storage.Streams.IRandomAccessStream])
  $s.Size = 0
  $o = New-Object Windows.Data.Pdf.PdfPageRenderOptions
  $o.DestinationWidth = $w
  AwaitAct ($pg.RenderToStreamAsync($s, $o))
  $s.Dispose()
  $b = [System.Drawing.Image]::FromFile($Png); $got = $b.Width; $b.Dispose(); $got
}
# Windows scales the destination by the display's scale factor (3000 px for 2000 at 150%): ask again, corrected
$got = Render $Width
if ($got -ne $Width) { $got = Render ([int][Math]::Round($Width * $Width / $got)) }
$renderer = "Windows.Data.Pdf " + [Environment]::OSVersion.Version.ToString()
if ($Baseline -eq "") { $b = [System.Drawing.Image]::FromFile($Png); "{""width"":$($b.Width),""height"":$($b.Height),""renderer"":""$renderer""}"; $b.Dispose(); exit 0 }
Add-Type -ReferencedAssemblies System.Drawing -TypeDefinition @"
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices;
public static class AdomPxDiff {
  static int[] Px(Bitmap b) { var r = new Rectangle(0, 0, b.Width, b.Height); var d = b.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); var a = new int[b.Width * b.Height]; Marshal.Copy(d.Scan0, a, 0, a.Length); b.UnlockBits(d); return a; }
  public static string Run(string now, string was, string diff) {
    var A = new Bitmap(now); var B = new Bitmap(was);
    if (A.Width != B.Width || A.Height != B.Height) { string s = "{\"width\":" + A.Width + ",\"height\":" + A.Height + ",\"driftPercent\":100,\"sizeChanged\":true}"; A.Dispose(); B.Dispose(); return s; }
    int w = A.Width, h = A.Height; var pa = Px(A); var pb = Px(B); var po = new int[w * h]; var po2 = new int[w * h]; var gr = new int[w * h];
    long n = 0; int x0 = w, y0 = h, x1 = -1, y1 = -1;
    for (int i = 0; i < pa.Length; i++) {
      int a = pa[i], c = pb[i];
      int d = Math.Max(Math.Abs(((a >> 16) & 255) - ((c >> 16) & 255)), Math.Max(Math.Abs(((a >> 8) & 255) - ((c >> 8) & 255)), Math.Abs((a & 255) - (c & 255))));
      int g = (((a >> 16) & 255) + ((a >> 8) & 255) + (a & 255)) / 3; g = 160 + g * 95 / 255;
      po[i] = d > 64 ? 1 : 0;
      gr[i] = g;
    }
    // a changed pixel counts when at least 3 of its 8 neighbours changed too: lone specks are anti-aliasing noise
    for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) {
      int i = y * w + x; int g = gr[i]; bool hit = false;
      if (po[i] == 1) { int k = 0; for (int dy = -1; dy <= 1; dy++) for (int dx = -1; dx <= 1; dx++) { int xx = x + dx, yy = y + dy; if ((dx != 0 || dy != 0) && xx >= 0 && yy >= 0 && xx < w && yy < h && (po[yy * w + xx] & 1) == 1) k++; } hit = k >= 3; }
      if (hit) { n++; if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; }
      po2[i] = hit ? unchecked((int)0xFFFF0000) : unchecked((int)0xFF000000) | (g << 16) | (g << 8) | g;
    }
    var o = new Bitmap(w, h, PixelFormat.Format32bppArgb); var od = o.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); Marshal.Copy(po2, 0, od.Scan0, po2.Length); o.UnlockBits(od); o.Save(diff, ImageFormat.Png);
    o.Dispose(); A.Dispose(); B.Dispose();
    return "{\"width\":" + w + ",\"height\":" + h + ",\"changed\":" + n + ",\"driftPercent\":" + (100.0 * n / pa.Length).ToString("0.####", System.Globalization.CultureInfo.InvariantCulture) + (n > 0 ? ",\"box\":[" + x0 + "," + y0 + "," + x1 + "," + y1 + "]" : "") + "}";
  }
}
"@
$r = [AdomPxDiff]::Run($Png, $Baseline, $Diff)
$r.TrimEnd('}') + ",""renderer"":""$renderer""}"
"#;

pub(crate) fn powershell(script: &Path, args: &[String]) -> Result<Value, String> {
    let mut cmd = std::process::Command::new("powershell");
    cmd.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]).arg(script).args(args);
    #[cfg(windows)]
    { use std::os::windows::process::CommandExt; cmd.creation_flags(0x0800_0000); }
    let o = cmd.output().map_err(|e| format!("powershell failed to start: {e}"))?;
    let out = String::from_utf8_lossy(&o.stdout).to_string();
    let line = out.lines().rev().find(|l| l.trim_start().starts_with('{')).ok_or_else(|| format!("no result: {} {}", out.trim(), String::from_utf8_lossy(&o.stderr).trim()))?;
    serde_json::from_str(line.trim()).map_err(|e| format!("{e}: {line}"))
}

/// altium_render_schematic {sheet, width?, outputDir?, baseline?: set|compare, threshold?}
pub fn render_schematic(args: &Value) -> Value {
    let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };
    let width = args.get("width").and_then(|v| v.as_i64()).unwrap_or(2000).clamp(200, 10000);
    let stem = Path::new(&sheet).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or("sheet".into());
    let dir = support::s(args, "outputDir").map(PathBuf::from).unwrap_or_else(|| Path::new(&sheet).parent().unwrap_or(Path::new(".")).join("render"));
    if let Err(e) = std::fs::create_dir_all(dir.join("baselines")) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", dir.display())}); }
    // printed by Altium's own schematic print: through the sheet's own project when one beside it lists it (its title
    // block's fields resolve there, and the page is the sheet's place in the project), else a one-sheet project
    let tmp = std::env::temp_dir().join("adom-altium-render").join(format!("{}", (support::now() * 1000.0) as u64));
    if let Err(e) = std::fs::create_dir_all(&tmp) { return json!({"success": false, "errorCode": "temp_write_failed", "error": e.to_string()}); }
    let sdir = Path::new(&sheet).parent().unwrap_or(Path::new(".")).to_path_buf();
    let own = std::fs::read_dir(&sdir).ok().into_iter().flatten().filter_map(|e| e.ok()).map(|e| e.path())
        .filter(|p| p.extension().map(|x| x.eq_ignore_ascii_case("prjpcb")).unwrap_or(false))
        .find_map(|p| { let t = std::fs::read(&p).ok().map(|b| String::from_utf8_lossy(&b).to_string())?; let pr = crate::bom::parse_project(&t, &sdir);
            pr.sheets.iter().position(|x| x.eq_ignore_ascii_case(&sheet)).map(|i| (p.to_string_lossy().to_string(), i)) });
    let (prj, page_ix, temp_prj) = match own {
        Some((p, i)) => (p, i, false),
        None => {
            let p = tmp.join("AdomRender.PrjPcb");
            if let Err(e) = std::fs::write(&p, format!("[Design]\r\nVersion=1.0\r\nHierarchyMode=0\r\n\r\n[Document1]\r\nDocumentPath={sheet}\r\nAnnotationEnabled=1\r\n\r\n")) {
                return json!({"success": false, "errorCode": "temp_write_failed", "error": e.to_string()});
            }
            (p.to_string_lossy().to_string(), 0, true)
        }
    };
    let pdf = dir.join(format!("{stem}.pdf"));
    let print = || -> Result<(), Value> {
        let ex = crate::sch::export_pdf(&json!({"projectPath": prj, "output": pdf.to_string_lossy()}));
        if ex.get("success").and_then(|b| b.as_bool()) != Some(true) { return Err(json!({"success": false, "errorCode": "print_failed", "error": "Altium's schematic print wrote no PDF", "reply": ex})); }
        Ok(())
    };
    if let Err(e) = print() { return e; }
    let script = tmp.join("render.ps1");
    if let Err(e) = std::fs::write(&script, RENDER_PS) { return json!({"success": false, "errorCode": "temp_write_failed", "error": e.to_string()}); }
    let png = dir.join(format!("{stem}.png"));
    let base = dir.join("baselines").join(format!("{stem}-{width}.png"));
    let base_meta = base.with_extension("json");
    let mode = args.get("baseline").and_then(|v| v.as_str());
    let mut ps_args = vec!["-Pdf".to_string(), pdf.to_string_lossy().to_string(), "-Png".into(), png.to_string_lossy().to_string(), "-Width".into(), width.to_string(), "-PageIndex".into(), page_ix.to_string()];
    let diff_png = dir.join(format!("{stem}-diff.png"));
    if mode == Some("compare") {
        if !base.exists() { return json!({"success": false, "errorCode": "no_baseline", "error": format!("no baseline for {stem} at {width} px: set one with baseline:\"set\" first"), "baseline": base.to_string_lossy()}); }
        ps_args.extend(["-Baseline".into(), base.to_string_lossy().to_string(), "-Diff".into(), diff_png.to_string_lossy().to_string()]);
    }
    let mut r = match powershell(&script, &ps_args) { Ok(r) => r, Err(e) => return json!({"success": false, "errorCode": "render_failed", "error": e}) };
    // Altium's print now and then leaves the title block's special strings (=Title, sheet numbers) unfilled, which
    // reads as drift: a failed comparison prints once more and keeps the closer image
    let threshold = args.get("threshold").and_then(|v| v.as_f64()).unwrap_or(0.5);
    let mut reprinted = false;
    if mode == Some("compare") && r["driftPercent"].as_f64().unwrap_or(100.0) > threshold && r["sizeChanged"].as_bool() != Some(true) {
        if print().is_ok() {
            if let Ok(r2) = powershell(&script, &ps_args) {
                reprinted = true;
                if r2["driftPercent"].as_f64().unwrap_or(100.0) < r["driftPercent"].as_f64().unwrap_or(100.0) { r = r2; }
            }
        }
    }
    if temp_prj { let _ = agent::call("close_document", &[("path", prj.clone())], None, Duration::from_secs(30)); }
    let _ = std::fs::remove_dir_all(&tmp);
    let mut out = json!({"success": true, "sheet": sheet, "png": png.to_string_lossy(), "pdf": pdf.to_string_lossy(), "width": r["width"], "height": r["height"], "windowEtiquette": "background",
        "_hint": "Printed by Altium's own schematic print to PDF (no window), then rendered by Windows' PDF renderer. baseline:\"set\" keeps this image; baseline:\"compare\" reports the drift against it."});
    match mode {
        Some("set") => {
            if let Err(e) = std::fs::copy(&png, &base).and_then(|_| std::fs::write(&base_meta, json!({"renderer": r["renderer"], "width": width}).to_string())) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }
            out["baseline"] = json!(base.to_string_lossy());
        }
        Some("compare") => {
            let drift = r["driftPercent"].as_f64().unwrap_or(100.0);
            out["reprinted"] = json!(reprinted);
            let was = std::fs::read_to_string(&base_meta).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).map(|v| v["renderer"].clone()).unwrap_or(Value::Null);
            out["driftPercent"] = json!(drift);
            out["pass"] = json!(drift <= threshold);
            out["threshold"] = json!(threshold);
            out["rendererChanged"] = json!(was != r["renderer"]);
            if r["changed"].as_i64().unwrap_or(0) > 0 { out["diffPng"] = json!(diff_png.to_string_lossy()); }
            // the changed pixels' box in sheet mm (the print fills the page: approximate)
            if let (Some(b), Some(w), Some(h)) = (r["box"].as_array(), r["width"].as_f64(), r["height"].as_f64()) {
                let pg = page_of(&sh);
                let (sw, shh) = (pg["widthMm"].as_f64().unwrap_or(0.0), pg["heightMm"].as_f64().unwrap_or(0.0));
                if sw > 0.0 {
                    let f = |i: usize| b.get(i).and_then(|v| v.as_f64()).unwrap_or(0.0);
                    out["changedRegionMm"] = json!([r2(f(0) / w * sw), r2((h - f(3)) / h * shh), r2(f(2) / w * sw), r2((h - f(1)) / h * shh)]);
                }
            }
            if r["sizeChanged"].as_bool() == Some(true) { out["sizeChanged"] = json!(true); }
        }
        Some(o) => return bad(format!("baseline {o}: set or compare")),
        None => {}
    }
    out
}