main
Colby Knox 0.2.61 source (not yet released, needs signing): altium_workspace_search/workspace_place (Altium 365 workspace parts vi… 52dda87
//! Parts from the signed-in Altium 365 workspace (the shared cloud library), through Altium's own Components
//! panel: Altium's 365 API is a closed beta, but the running Altium already searches the workspace. The panel is
//! WPF in a docked host window: its search box takes real typing, its results grid reads through UI Automation,
//! and a result goes onto the sheet the way a person does it (double-click the row, click the sheet).
use crate::support::{self, s};
use crate::{ab, agent, instance};
use serde_json::{json, Value};
use std::collections::HashSet;
use std::time::Duration;

fn main_hwnd() -> Option<i64> {
    instance::invalidate_snapshot();
    instance::main_window().and_then(|w| w.get("hwnd").and_then(|h| h.as_i64()))
}

/// The Components panel's WPF host window, showing the panel first when it is not on screen.
/// What the panel search saw, for a failure reply.
fn panel_diag() -> Value {
    let Some(main) = main_hwnd() else { return json!({"main": null}) };
    let kids = crate::win32::child_windows(main);
    json!({"main": main, "children": kids.len(),
        "panels": kids.iter().filter(|k| k.class == "TXPPanel").map(|k| json!([k.hwnd, k.title, k.visible])).collect::<Vec<_>>(),
        "wpfHosts": kids.iter().filter(|k| k.class.starts_with("HwndWrapper")).map(|k| json!([k.hwnd, k.parent, k.visible])).collect::<Vec<_>>()})
}

/// Altium comes to the front first: an unpinned (pop-out) panel does not open, and its WPF tree does not answer,
/// while another app is in front (measured on the laptop with Hydrogen in front: the tree read timed out).
fn panel_hwnd() -> Option<i64> {
    if let Some(m) = main_hwnd() {
        let _ = ab::call("desktop_bring_to_front", json!({"hwnd": m, "reason": "the workspace search types into Altium's Components panel"}), &[], 20);
        std::thread::sleep(Duration::from_millis(600));
    }
    for attempt in 0..2 {
        let main = main_hwnd()?;
        let kids = crate::win32::child_windows(main);
        // the WPF host hangs under the panel's view windows, all titled "Components" (TLazyLoadViewComponent ->
        // WinForms "Components" -> elementHost), not under the TXPPanel itself (measured AD 26.11.1)
        let panels: Vec<i64> = kids.iter().filter(|k| k.visible && k.title == "Components").map(|k| k.hwnd).collect();
        let host = kids.iter().find(|k| k.visible && k.class.starts_with("HwndWrapper") && {
            // a descendant of the Components panel (the host sits a few windows down)
            let mut p = k.parent;
            let mut hit = false;
            for _ in 0..8 { if panels.contains(&p) { hit = true; break; } match kids.iter().find(|x| x.hwnd == p) { Some(x) => p = x.parent, None => break } }
            hit
        });
        if let Some(h) = host { return Some(h.hwnd); }
        if attempt == 0 {
            // through Altium's -R command line, not the agent: an agent call would restart the loop this verb parked,
            // and with the loop running the panel answers UI Automation in minutes (measured)
            if let Some(exe) = crate::lifecycle::x2_exe_pub() {
                if let Ok(mut child) = crate::lifecycle::spawn_helper_pub(&exe, "-RClient:CustomizeResources(Action=Show|ObjectKind=Panel|ID=Altium.Edp.ComponentSearch.Plugin)") {
                    let t = std::time::Instant::now();
                    while t.elapsed() < Duration::from_secs(10) { if let Ok(Some(_)) = child.try_wait() { break; } std::thread::sleep(Duration::from_millis(200)); }
                    let _ = child.kill();
                }
            }
            std::thread::sleep(Duration::from_secs(3));
        }
    }
    None
}

/// The results grid: one row per DataItem, named "Name; Description; Footprint".
fn read_results(hwnd: i64) -> (Vec<Value>, Option<i64>, Option<(i64, i64)>) {
    fn walk(n: &Value, rows: &mut Vec<Value>, count: &mut Option<i64>, bx: &mut Option<(i64, i64)>, in_grid: bool) {
        let role = n.get("role").and_then(|r| r.as_str()).unwrap_or("");
        let name = n.get("name").and_then(|r| r.as_str()).unwrap_or("");
        // results are the DataItems of the grid; the Details pane below it has DataItems of its own
        let in_grid = in_grid || n.get("automationId").and_then(|a| a.as_str()) == Some("ComponentsGrid");
        if n.get("automationId").and_then(|a| a.as_str()) == Some("TextBoxSearchAdv") {
            if let (Some(x), Some(y)) = (n["rect"]["centerX"].as_i64(), n["rect"]["centerY"].as_i64()) { *bx = Some((x, y)); }
        }
        if role == "DataItem" && in_grid {
            let f: Vec<&str> = name.splitn(3, "; ").collect();
            if f.first().map(|x| !x.trim().is_empty()).unwrap_or(false) {
                rows.push(json!({"name": f[0].trim(), "description": f.get(1).map(|x| x.trim()).unwrap_or(""), "footprint": f.get(2).map(|x| x.trim()).unwrap_or(""), "rect": n.get("rect")}));
            }
            return;
        }
        if role == "Text" { if let Some(c) = name.strip_prefix("Results: ") { *count = c.trim().parse().ok(); } }
        for c in n.get("children").and_then(|c| c.as_array()).into_iter().flatten() { walk(c, rows, count, bx, in_grid); }
    }
    let tree = ab::call("desktop_ui_tree", json!({"hwnd": hwnd, "maxDepth": 8, "maxNodes": 600, "timeout": 150}), &[], 160);
    let root = tree.get("root").cloned().or_else(|| tree.get("output").and_then(|o| o.as_str()).and_then(|t| serde_json::from_str::<Value>(t).ok()).and_then(|v| v.get("root").cloned())).unwrap_or(Value::Null);
    let mut rows = Vec::new();
    let mut count = None;
    let mut bx = None;
    walk(&root, &mut rows, &mut count, &mut bx, false);
    (rows, count, bx)
}

/// Type the query into the panel's search box (it takes real keystrokes, not a set value) and read the results.
/// UIA lookups by automation id take 30-70 s in this WPF panel (measured), so the box is found in one tree read
/// and clicked, and the old text is replaced with Ctrl+A.
fn search(hwnd: i64, query: &str) -> Result<Vec<Value>, Value> {
    // a panel that has just been shown loads its content lazily: read again until the search box is there
    let mut bx = None;
    for wait in [0u64, 3, 5] {
        std::thread::sleep(Duration::from_secs(wait));
        bx = read_results(hwnd).2;
        if bx.is_some() { break; }
    }
    let Some((x, y)) = bx else {
        return Err(json!({"success": false, "errorCode": "search_box_not_found", "error": "the Components panel's search box is not in its UI tree"}));
    };
    let main = main_hwnd().unwrap_or(0);
    let _ = ab::call("desktop_click", json!({"hwnd": main, "x": x, "y": y, "reason": "focus the Components panel search"}), &[], 20);
    let _ = ab::call("desktop_press_key", json!({"key": "ctrl+a", "hwnd": main, "reason": "select the old search text"}), &[], 20);
    let _ = ab::call("desktop_type", json!({"hwnd": main, "text": query, "reason": "search the Altium workspace library"}), &[], 30);
    let _ = ab::call("desktop_press_key", json!({"key": "Enter", "hwnd": main, "reason": "run the workspace search"}), &[], 20);
    let mut rows = Vec::new();
    for wait in [3u64, 4, 6] {
        std::thread::sleep(Duration::from_secs(wait));
        let (r, count, _) = read_results(hwnd);
        rows = r;
        if !rows.is_empty() || count == Some(0) { break; }
    }
    Ok(rows)
}

fn public_rows(rows: &[Value], limit: usize) -> Vec<Value> {
    rows.iter().take(limit).enumerate().map(|(i, r)| json!({"index": i, "name": r["name"], "description": r["description"], "footprint": r["footprint"]})).collect()
}

/// altium_workspace_search {query, limit?}
pub fn workspace_search(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    let Some(q) = s(args, "query").filter(|q| !q.trim().is_empty()) else { return json!({"success": false, "errorCode": "bad_args", "error": "query is required (e.g. '100nF 0402', an MPN, 'TPS54202')"}) };
    let _ = crate::lifecycle::stop_all_live();
    let Some(hwnd) = panel_hwnd() else {
        return json!({"success": false, "errorCode": "components_panel_not_found", "error": "the Components panel did not come up", "seen": panel_diag(), "_hint": "Open a schematic first (altium_show_schematic); the panel needs a document."});
    };
    let t0 = support::now();
    // the resident agent loop keeps Altium's UI thread busy, and this WPF panel then answers UI Automation in
    // 100+ s instead of ~15 (measured): park the loop while the panel is driven; the next verb restarts it
    let rows = match search(hwnd, &q) { Ok(r) => r, Err(e) => return e };
    let limit = args.get("limit").and_then(|v| v.as_u64()).unwrap_or(25) as usize;
    json!({"success": true, "query": q, "count": rows.len(), "results": public_rows(&rows, limit), "elapsedSec": support::elapsed_round(t0),
        "_hint": if rows.is_empty() { "No results in the workspace for that text: try fewer words, the MPN, or the value and package ('100nF 0402')." }
                 else { "These come from the Altium workspace Altium is signed in to (and whatever library the panel's selector shows). altium_workspace_place {sheet, query, pick} puts one on a sheet with its workspace link, parameters and footprint." }})
}

fn sheet_parts(sheet: &str) -> Vec<Value> {
    if support::must_open(sheet, 60).is_some() { return vec![]; }
    let r = agent::call("schematic_data", &[("pins", "0".into()), ("params", "0".into()), ("limit", "5000".into())], None, Duration::from_secs(120));
    r.get("data").and_then(|d| d.get("components")).and_then(|c| c.as_array()).cloned().unwrap_or_default()
}

fn mil(v: &Value) -> i64 { v.as_f64().map(|f| f.round() as i64).unwrap_or(0) }

/// altium_workspace_place {sheet, query, pick?, x?, y?, designator?, save?}
pub fn workspace_place(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    let Some(sheet) = s(args, "sheet").or_else(|| s(args, "filePath")).filter(|p| p.to_lowercase().ends_with(".schdoc")) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "sheet (.SchDoc path) is required"});
    };
    let Some(q) = s(args, "query").filter(|q| !q.trim().is_empty()) else { return json!({"success": false, "errorCode": "bad_args", "error": "query is required: the search that finds the part (an MPN is best)"}) };
    let t0 = support::now();
    let before: HashSet<String> = sheet_parts(&sheet).iter().filter_map(|c| c["uniqueId"].as_str().map(str::to_string)).collect();
    let _ = crate::lifecycle::stop_all_live(); // see workspace_search: the panel answers fast only with the loop parked
    let Some(hwnd) = panel_hwnd() else { return json!({"success": false, "errorCode": "components_panel_not_found", "error": "the Components panel did not come up", "seen": panel_diag()}) };
    let rows = match search(hwnd, &q) { Ok(r) => r, Err(e) => return e };
    if rows.is_empty() { return json!({"success": false, "errorCode": "no_results", "query": q, "_hint": "altium_workspace_search with other words; an MPN finds one part."}); }
    // pick: a row index, or text the row's name contains; default the first row
    let row = match args.get("pick") {
        Some(Value::Number(n)) => rows.get(n.as_u64().unwrap_or(0) as usize).cloned(),
        Some(Value::String(t)) => rows.iter().find(|r| r["name"].as_str().map(|n| n.to_lowercase().contains(&t.to_lowercase())).unwrap_or(false)).cloned(),
        _ => rows.first().cloned(),
    };
    let Some(row) = row else { return json!({"success": false, "errorCode": "pick_not_found", "results": public_rows(&rows, 25)}) };
    let (Some(rx), Some(ry)) = (row["rect"]["centerX"].as_i64(), row["rect"]["centerY"].as_i64()) else {
        return json!({"success": false, "errorCode": "row_not_on_screen", "results": public_rows(&rows, 25)});
    };
    let Some(main) = main_hwnd() else { return json!({"success": false, "errorCode": "altium_not_running"}) };
    // the drop point: near the schematic view's lower-left corner, usually blank, so the part lands on no wire
    let view = crate::win32::child_windows(main).into_iter().find(|k| k.visible && k.class == "TSCHView_GraphicalForm");
    let Some(view) = view else { return json!({"success": false, "errorCode": "no_schematic_view", "_hint": "The sheet must be the document on screen (altium_show_schematic)."}) };
    let (l, _, _, b) = view.rect;
    let mut steps = Vec::new();
    let mut new = None;
    // twice at most: a double-click that only brought Altium to the front placed nothing (intermittent on
    // Altium Designer Develop, 2026-10-22)
    for attempt in 1..=2 {
        let _ = ab::call("desktop_bring_to_front", json!({"hwnd": main, "reason": "the placement clicks go to Altium"}), &[], 20);
        std::thread::sleep(Duration::from_millis(500));
        // a pop-out (unpinned) Components panel slides away when Altium takes focus: show it again and read where
        // the row is NOW (on Altium Develop the panel lived in the side bar and the first clicks hit the sheet)
        let (mut px, mut py) = (rx, ry);
        if let Some(h2) = panel_hwnd() {
            let (now, _, _) = read_results(h2);
            if let Some(r) = now.iter().find(|r| r["name"] == row["name"]) {
                if let (Some(x), Some(y)) = (r["rect"]["centerX"].as_i64(), r["rect"]["centerY"].as_i64()) { px = x; py = y; }
            }
        }
        let d1 = ab::call("desktop_double_click", json!({"hwnd": main, "x": px, "y": py, "reason": "pick a workspace part in Altium's Components panel"}), &[], 20);
        steps.push(json!({"attempt": attempt, "pickRow": row["name"], "ok": d1.get("success")}));
        std::thread::sleep(Duration::from_millis(2500));
        let d2 = ab::call("desktop_click", json!({"hwnd": main, "x": l + 160, "y": b - 160, "reason": "drop the workspace part on the sheet"}), &[], 20);
        steps.push(json!({"attempt": attempt, "drop": [l + 160, b - 160], "ok": d2.get("success")}));
        std::thread::sleep(Duration::from_millis(1500));
        for _ in 0..2 { let _ = ab::call("desktop_press_key", json!({"key": "Escape", "hwnd": main, "reason": "end Altium's part placement"}), &[], 20); std::thread::sleep(Duration::from_millis(500)); }
        let after = sheet_parts(&sheet);
        new = after.iter().find(|c| c["uniqueId"].as_str().map(|u| !before.contains(u)).unwrap_or(false)).cloned();
        if new.is_some() { break; }
        let _ = crate::lifecycle::stop_all_live();
    }
    let Some(new) = new else {
        return json!({"success": false, "errorCode": "not_placed", "steps": steps, "_hint": "Altium did not put the part on the sheet after two tries: the part may have no symbol, or a dialog took the clicks. altium_check_dialogs, then try again."});
    };
    // where it should go, and its designator: a temporary unique name lets the edit verbs find exactly this part
    let des0 = new["designator"].as_str().unwrap_or("").to_string();
    let (nx, ny) = (mil(&new["xMil"]), mil(&new["yMil"]));
    let tmp = "ADOMNEW1".to_string();
    let _ = agent::call("sch_rename_at", &[], Some(&format!("{des0}|{tmp}|{nx}|{ny}")), Duration::from_secs(60));
    let (tx, ty) = (args.get("x").and_then(|v| v.as_f64()).map(|v| v.round() as i64), args.get("y").and_then(|v| v.as_f64()).map(|v| v.round() as i64));
    let (fx, fy) = match (tx, ty) {
        (Some(x), Some(y)) => { let _ = agent::call("sch_edit", &[], Some(&format!("{tmp}|move|{x}|{y}")), Duration::from_secs(60)); (x, y) }
        _ => (nx, ny),
    };
    let des = s(args, "designator").unwrap_or(des0.clone());
    let _ = agent::call("sch_rename_at", &[], Some(&format!("{tmp}|{des}|{fx}|{fy}")), Duration::from_secs(60));
    let saved = if args.get("save").and_then(|b| b.as_bool()) == Some(false) { json!(false) } else { json!(crate::surfaces::save(&json!({"filePath": sheet})).get("success")) };
    let placed = sheet_parts(&sheet).into_iter().find(|c| c["uniqueId"] == new["uniqueId"]).unwrap_or(new);
    json!({"success": true, "sheet": sheet, "query": q, "picked": {"name": row["name"], "description": row["description"], "footprint": row["footprint"]},
        "placed": {"designator": placed["designator"], "libReference": placed["libReference"], "comment": placed["comment"], "itemGuid": placed["itemGuid"],
                   "sourceLibrary": placed["sourceLibrary"], "xMil": placed["xMil"], "yMil": placed["yMil"]},
        "steps": steps, "saved": saved, "elapsedSec": support::elapsed_round(t0),
        "_hint": "The workspace part is on the sheet with its workspace link (itemGuid), parameters and footprint. Number it with altium_annotate (a '?' designator), wire it with altium_sch_connect, carry it to the board with altium_update_pcb."})
}