← Commit history
Upload chipsmith source (MIT) — Ray can commit on top
6 files changed
+377
src/cli/detect.rsadded+114@@ -0,0 +1,114 @@+//! `adom-chipsmith detect <chip-fetcher-dir>` — run detection headlessly and+//! print a JSON report. Boots a transient server in --no-open mode, drives+//! the JS detection pipeline via /eval, then reports + shuts down. Useful+//! for batch validation across an entire chip-fetcher library.++use crate::cli::{err, ok, DEFAULT_PORT};+use crate::server::{self, convert, ServerConfig, ServerState};+use anyhow::{anyhow, Result};+use clap::Parser;+use std::path::PathBuf;+use std::time::Duration;++#[derive(Parser)]+pub struct Args {+ /// Path to a chip-fetcher library directory.+ pub dir: PathBuf,++ /// Print JSON instead of human text.+ #[arg(long)]+ pub json: bool,++ /// Port to bind during the headless run.+ #[arg(long, default_value_t = DEFAULT_PORT)]+ pub port: u16,+}++pub fn run(args: Args) -> Result<()> {+ if !args.dir.is_dir() {+ return Err(anyhow!("not a directory: {}", args.dir.display()));+ }+ let mpn = args.dir.file_name()+ .and_then(|s| s.to_str())+ .ok_or_else(|| anyhow!("can't derive MPN from dir: {}", args.dir.display()))?+ .to_string();++ let mut step_path = args.dir.join(format!("{mpn}.step"));+ if !step_path.exists() { step_path = args.dir.join(format!("{mpn}.STEP")); }+ if !step_path.exists() {+ return Err(anyhow!("no .step file in {}", args.dir.display()));+ }++ let step_bytes = std::fs::read(&step_path).map_err(|e| anyhow!("read STEP: {e}"))?;+ let result = convert::convert_step_bytes(&step_bytes)+ .map_err(|e| anyhow!("conversion failed: {e}"))?;++ let config = ServerConfig {+ port: args.port,+ initial_glb_path: Some(result.glb_path.clone()),+ initial_source_label: Some(format!("{mpn}.step")),+ initial_source_type: Some("chip-fetcher".to_string()),+ };+ let state = ServerState::new(config);++ // Seed spec + footprint from the dir+ let info_path = args.dir.join("info.json");+ if info_path.exists() {+ if let Ok(s) = std::fs::read_to_string(&info_path) {+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(&s) {+ *state.spec.lock().unwrap() = v;+ }+ }+ }+ *state.signoff_dir.lock().unwrap() = Some(args.dir.clone());+ *state.source_step_path.lock().unwrap() = Some(step_path.clone());++ // Spawn server thread+ let server_state = state.clone();+ std::thread::spawn(move || {+ let _ = server::run(server_state);+ });++ // Headless detection requires a JS context — for now, we report what the+ // Rust side knows: GLB stats + spec + footprint pad count. Full live+ // detection requires a webview running the JS. Future: bake detection+ // into Rust once /step-meta delivers the structured B-rep.+ std::thread::sleep(Duration::from_millis(800));++ let spec = state.spec.lock().unwrap().clone();+ let report = serde_json::json!({+ "mpn": mpn,+ "source": format!("{mpn}.step"),+ "step_size_kb": step_bytes.len() / 1024,+ "glb_size_kb": result.size_bytes / 1024,+ "glb_meshes": result.meshes,+ "glb_nodes": result.nodes,+ "glb_cache_hit": result.cache_hit,+ "spec": spec,+ "step_meta_available": match convert::fetch_step_meta(&step_bytes) {+ Ok(Some(_)) => true,+ _ => false,+ },+ "headless_detect_status": "stub — full detection requires live webview; loads STEP + caches GLB + checks /step-meta availability",+ });++ if args.json {+ println!("{}", serde_json::to_string_pretty(&report).unwrap());+ } else {+ ok(format!("MPN: {mpn}"));+ ok(format!("STEP: {} KB → GLB: {} KB ({})", step_bytes.len() / 1024, result.size_bytes / 1024, if result.cache_hit { "cached" } else { "fresh" }));+ if let Some(p) = spec.get("package_family") {+ ok(format!("package: {p}"));+ }+ if let Some(p) = spec.get("pin_count") {+ ok(format!("pin count: {p}"));+ }+ let step_meta_ok = match convert::fetch_step_meta(&step_bytes) {+ Ok(Some(_)) => "yes",+ Ok(None) => "no (service-step2glb /step-meta not deployed)",+ Err(e) => { let _ = e; "error" }+ };+ ok(format!("step-meta available: {step_meta_ok}"));+ }+ Ok(())+}
src/cli/hide.rsadded+22@@ -0,0 +1,22 @@+use crate::cli::{eval, ok, DEFAULT_PORT};+use anyhow::Result;+use clap::Parser;++#[derive(Parser)]+pub struct Args {+ pub name: String,+ #[arg(long, default_value_t = 5)]+ pub timeout_secs: u64,+ #[arg(long, default_value_t = DEFAULT_PORT)]+ pub port: u16,+}++pub fn run(args: Args) -> Result<()> {+ let code = format!(+ "return window.adomStep ? window.adomStep.hide({}) : {{ error: 'adomStep not loaded' }};",+ serde_json::to_string(&args.name).unwrap()+ );+ eval::eval_snippet(&code, args.timeout_secs, args.port, true)?;+ ok(format!("hide {}", args.name));+ Ok(())+}
src/cli/mod.rsadded+48@@ -0,0 +1,48 @@+pub mod console;+pub mod detect;+pub mod eval;+pub mod frame;+pub mod health;+pub mod hide;+pub mod install;+pub mod isolate;+pub mod list_components;+pub mod open;+pub mod reveal;+pub mod screenshot;+pub mod show;+pub mod show_all;+pub mod status;+pub mod stop;+pub mod view;+pub mod view_library;+pub mod place_pin1;+pub mod set_overlay;+pub mod sign_off;+pub mod restart;++use colored::Colorize;++pub fn ok(msg: impl AsRef<str>) {+ println!("{} {}", "OK:".green().bold(), msg.as_ref());+}++pub fn err(msg: impl AsRef<str>) {+ eprintln!("{} {}", "ERROR:".red().bold(), msg.as_ref());+}++pub fn hint(msg: impl AsRef<str>) {+ eprintln!("{} {}", "Hint:".yellow().bold(), msg.as_ref());+}++pub const DEFAULT_PORT: u16 = 8871;++/// Service-step2glb base URL. Override at runtime with `STEP2GLB_SERVICE_API`.+pub const DEFAULT_STEP2GLB_URL: &str = "https://step2glb-gmdoncpxdwx0.adom.cloud";++pub fn step2glb_service_url() -> String {+ std::env::var("STEP2GLB_SERVICE_API")+ .unwrap_or_else(|_| DEFAULT_STEP2GLB_URL.to_string())+ .trim_end_matches('/')+ .to_string()+}
src/cli/place_pin1.rsadded+73@@ -0,0 +1,73 @@+use crate::cli::{err, hint, ok, DEFAULT_PORT};+use crate::cli::eval::eval_snippet;+use anyhow::Result;+use clap::Parser;++/// Place a synthetic pin-1 indicator on the chip's top face — the CLI+/// counterpart to the Pin-1 tab's mode + shape pickers. Three placement+/// modes (one is required):+///+/// --corner NW|NE|SW|SE pick a corner manually+/// --from-fp-marker project the silkscreen pin-1 marker from+/// the first available footprint source onto+/// the body top, snap to nearest corner —+/// chip + silkscreen agree by construction+/// --xy <x> <y> click-style placement at (x,y) mm relative+/// to chip body center+///+/// Three indicator shapes (--shape):+/// dimple (default) recessed cylinder, Ø 0.40 × 0.05 mm+/// raisedDot protruding cylinder, Ø 0.40 × 0.05 mm+/// chamfer angled cut on the body's top corner edge+#[derive(Parser)]+pub struct Args {+ #[arg(long, conflicts_with_all = &["from_fp_marker", "xy"])]+ pub corner: Option<String>,++ #[arg(long, conflicts_with_all = &["corner", "xy"])]+ pub from_fp_marker: bool,++ /// Two values: <x> <y> in mm relative to chip body center.+ #[arg(long, num_args = 2, value_names = &["X_MM", "Y_MM"], conflicts_with_all = &["corner", "from_fp_marker"])]+ pub xy: Option<Vec<f64>>,++ #[arg(long, default_value = "dimple")]+ pub shape: String,++ #[arg(long, default_value_t = DEFAULT_PORT)]+ pub port: u16,+}++pub fn run(args: Args) -> Result<()> {+ if args.corner.is_none() && !args.from_fp_marker && args.xy.is_none() {+ err("place-pin1 needs --corner, --from-fp-marker, or --xy".to_string());+ hint("e.g. adom-chipsmith place-pin1 --corner NE --shape dimple".to_string());+ return Err(anyhow::anyhow!("missing mode arg"));+ }+ let shape = args.shape;+ let snippet = if let Some(corner) = &args.corner {+ let c = corner.to_uppercase();+ if !matches!(c.as_str(), "NW" | "NE" | "SW" | "SE") {+ err(format!("invalid --corner '{c}', expected NW|NE|SW|SE"));+ return Err(anyhow::anyhow!("bad corner"));+ }+ format!(+ "return window.adomChipsmith.placePin1({{mode:'corner', corner:'{c}', shape:'{shape}'}});"+ )+ } else if args.from_fp_marker {+ format!("return window.adomChipsmith.placePin1({{mode:'fpMarker', shape:'{shape}'}});")+ } else if let Some(xy) = &args.xy {+ let x = xy[0];+ let y = xy[1];+ format!("return window.adomChipsmith.placePin1({{mode:'click', xyMm:[{x},{y}], shape:'{shape}'}});")+ } else {+ return Err(anyhow::anyhow!("unreachable"));+ };+ let v = eval_snippet(&snippet, 5, args.port, true)?;+ if let Some(e) = v.get("error").and_then(|x| x.as_str()) {+ err(format!("placePin1: {e}"));+ return Err(anyhow::anyhow!("place failed"));+ }+ ok(format!("pin-1 placed: {}", serde_json::to_string(&v).unwrap_or_default()));+ Ok(())+}
src/cli/set_overlay.rsadded+76@@ -0,0 +1,76 @@+use crate::cli::{err, ok, DEFAULT_PORT};+use crate::cli::eval::eval_snippet;+use anyhow::Result;+use clap::Parser;++/// Toggle a chipsmith overlay layer on/off — CLI parity for the buttons+/// in the Footprint / Heatsink / Solder-jet tabs.+///+/// Supported layer kinds:+/// datasheet|kicad|fusion|altium individual footprint sources+/// stock service-kicad authoritative ghost+/// (will fetch on first show)+/// all-sources every available user footprint at once+/// faux-pcb 1.6 mm FR4 plate w/ CSG-drilled holes+/// heatsink auto-generated via grid under EP+/// solderjet 300 µm domes per pad+/// pin1 user-placed pin-1 indicator+#[derive(Parser)]+pub struct Args {+ /// Layer kind to toggle.+ pub kind: String,+ /// "on" or "off" (case-insensitive).+ pub state: String,+ #[arg(long, default_value_t = DEFAULT_PORT)]+ pub port: u16,+}++pub fn run(args: Args) -> Result<()> {+ let on = match args.state.to_lowercase().as_str() {+ "on" | "true" | "1" | "show" => true,+ "off" | "false" | "0" | "hide" => false,+ other => {+ err(format!("invalid state '{other}', expected on|off"));+ return Err(anyhow::anyhow!("bad state"));+ }+ };+ let snippet = match args.kind.to_lowercase().as_str() {+ "datasheet" | "kicad" | "fusion" | "altium" => format!(+ "return window.adomChipsmith.setFootprintOverlay('{}', {});",+ args.kind, on+ ),+ "stock" => format!(+ // Stock-library overlay is a two-step transaction: load (if+ // not cached) then toggle. Fold into one snippet so a single+ // CLI invocation Just Works.+ "{{ const r = await window.adomChipsmith.loadStockLibraryOverlay({{force:false}}); \+ if (r && r.error) return r; \+ return window.adomChipsmith.setStockOverlayVisible({on}); }}",+ on = on+ ),+ "all-sources" => format!("return window.adomChipsmith.setAllFootprintOverlays({on});"),+ "faux-pcb" => format!("return window.adomChipsmith.setFauxPcbVisible({on});"),+ "heatsink" => format!("return window.adomChipsmith.setHeatsinkVisible({on});"),+ "solderjet" | "solder-jet" => format!(+ "return window.adomChipsmith.setSolderJetVisible({on});"+ ),+ "pin1" => {+ if on {+ err("'pin1 on' is ambiguous — use `place-pin1 --corner ...` instead".to_string());+ return Err(anyhow::anyhow!("use place-pin1"));+ }+ "return window.adomChipsmith.removePin1Indicator();".to_string()+ }+ other => {+ err(format!("unknown kind '{other}'"));+ return Err(anyhow::anyhow!("bad kind"));+ }+ };+ let v = eval_snippet(&snippet, 8, args.port, true)?;+ if let Some(e) = v.get("error").and_then(|x| x.as_str()) {+ err(format!("set-overlay: {e}"));+ return Err(anyhow::anyhow!("toggle failed"));+ }+ ok(format!("set-overlay {} {}: {}", args.kind, if on {"on"} else {"off"}, serde_json::to_string(&v).unwrap_or_default()));+ Ok(())+}
src/cli/status.rsadded+44@@ -0,0 +1,44 @@+use crate::cli::{err, ok, DEFAULT_PORT};+use anyhow::Result;+use clap::Parser;+use std::time::Duration;++#[derive(Parser)]+pub struct Args {+ #[arg(long, default_value_t = DEFAULT_PORT)]+ pub port: u16,+ /// Print result as a single JSON line (machine-parseable).+ /// Per gallia/skills/adom-cli-design — every status command supports+ /// `--json` so AI agents can consume it without scraping OK:/ERROR: lines.+ #[arg(long)]+ pub json: bool,+}++pub fn run(args: Args) -> Result<()> {+ let url = format!("http://127.0.0.1:{}/state", args.port);+ match ureq::get(&url).timeout(Duration::from_secs(2)).call() {+ Ok(r) => {+ let body: serde_json::Value = r.into_json()?;+ if args.json {+ println!(+ "{}",+ serde_json::json!({"ok": true, "port": args.port, "state": body})+ );+ } else {+ ok(serde_json::to_string_pretty(&body).unwrap_or_default());+ }+ Ok(())+ }+ Err(e) => {+ if args.json {+ println!(+ "{}",+ serde_json::json!({"ok": false, "port": args.port, "error": format!("{e}")})+ );+ } else {+ err(format!("not running on port {}: {e}", args.port));+ }+ Err(anyhow::anyhow!("not running"))+ }+ }+}