diff --git a/docs/AUTHORING-DEVELOPMENT.md b/docs/AUTHORING-DEVELOPMENT.md index cc22c80..192a6cc 100644 --- a/docs/AUTHORING-DEVELOPMENT.md +++ b/docs/AUTHORING-DEVELOPMENT.md @@ -21,7 +21,9 @@ request and supplies `aiThread` from its global flag if the file omits it. Operations are `add_library {key,symbol}`, `replace_library {key,symbol}`, `place {component:{reference,library,value,x,y,rotation}}`, `move {reference,x,y,rotation}`, `connect {connection:{id,from,to}}`, -`label {label:{endpoint,net}}`, and `undo`. Endpoints are `{reference,pin}`. +`label {label:{endpoint,net,angle?}}`, +`place_field {reference,field,x,y,rotation}`, +`style_label {endpoint,angle}`, and `undo`. Endpoints are `{reference,pin}`. Undo must be the only operation. Coordinates are sheet millimetres; rotations are 0/90/180/270. Exact library sources are retained with SHA-256. Replacement requires the same pin-number/electrical-type signature; callers must inspect any origin or @@ -65,8 +67,9 @@ connectivity/ERC or symbol-body clearance checks. The fast renderer currently omits pin/group text and some symbol graphics; use the hash-matched native inspection for readable pin/group review. Human authoring UI -currently exposes placement, connection and undo only. Library registration, -replacement, movement and labeling use typed transactions. Caller names provide +exposes placement, connection, undo, field placement and label orientation. +Library registration, replacement, component movement and label creation use +typed transactions. Caller names provide attribution, not authentication. The server binds loopback and is a development instance, not a hardened shared service. @@ -77,4 +80,6 @@ project and exact exported file hash. ### Native field and label placement -The KiCad exporter retains library Reference/Value positions and effects, transforms them with the placed component, and directs pin-attached net labels away from the symbol body. A rotation test covers all four right-angle orientations and preserves electrical anchors. Native revision-21 SVG inspection confirms the central TMF8829 artwork is no longer covered by its value. General field/label collision avoidance remains open: vertical ground labels can overlap capacitor and regulator fields. Native rendering is not electrical qualification. +The KiCad exporter retains library Reference/Value positions and effects, transforms them with the placed component, and directs pin-attached net labels away from the symbol body. A rotation test covers all four right-angle orientations and preserves electrical anchors. Native revision-21 SVG inspection confirms the central TMF8829 artwork is no longer covered by its value. The Text layout controls and matching typed operations now support per-instance Reference/Value placement and existing-label orientation. Field coordinates are component-local millimetres, Y-up, rotated with the component; label angles are absolute sheet angles. Only right angles are accepted. These operations preserve electrical pin and label anchors, connections, net names and source library hashes, and survive persistence and undo. An omitted override keeps the source field placement or outward pin-label orientation. Overrides use visible 1.27 mm left-justified fields. + +The local preview uses the exported field positions and text angles, so accepted text edits are visible through SSE. Its browser font differs from KiCad's native stroke font; native rendering remains the visual reference. Toolbar height follows wrapping and expanded text controls so it does not cover the canvas. Automatic text collision detection, default-field reset and a complete text typography editor remain open. Native rendering is not electrical qualification. diff --git a/src/author.rs b/src/author.rs index cef1f17..466e4fb 100644 --- a/src/author.rs +++ b/src/author.rs @@ -139,6 +139,15 @@ pub struct Component { pub x: f64, pub y: f64, pub rotation: u16, + /// Optional per-instance fields in component-local millimetres, Y-up. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub fields: BTreeMap, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct FieldPlacement { + pub x: f64, + pub y: f64, + pub rotation: u16, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub struct PinRef { @@ -155,6 +164,9 @@ pub struct Connection { pub struct Label { pub endpoint: PinRef, pub net: String, + /// Sheet text orientation only. Its anchor remains the electrical pin. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub angle: Option, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Document { @@ -203,6 +215,17 @@ pub enum Operation { Label { label: Label, }, + PlaceField { + reference: String, + field: String, + x: f64, + y: f64, + rotation: u16, + }, + StyleLabel { + endpoint: PinRef, + angle: u16, + }, Undo, } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -465,6 +488,38 @@ impl Document { }; self.labels.push(l.clone()); } + Operation::PlaceField { + reference, + field, + x, + y, + rotation, + } => { + if !["Reference", "Value"].contains(&field.as_str()) { + bail!("Only Reference and Value support instance field placement") + } + coords(*x, *y, *rotation)?; + self.components + .get_mut(reference) + .context("Unknown reference")? + .fields + .insert( + field.clone(), + FieldPlacement { + x: *x, + y: *y, + rotation: *rotation, + }, + ); + } + Operation::StyleLabel { endpoint, angle } => { + coords(0., 0., *angle)?; + self.labels + .iter_mut() + .find(|l| &l.endpoint == endpoint) + .context("Unknown label endpoint; create its net label first")? + .angle = Some(*angle); + } Operation::Undo => bail!("Undo must be the sole operation in a transaction"), }; Ok(()) @@ -503,6 +558,12 @@ impl Document { fn validate(&self) -> Result<()> { for c in self.components.values() { coords(c.x, c.y, c.rotation)?; + for (name, f) in &c.fields { + if !["Reference", "Value"].contains(&name.as_str()) { + bail!("Unknown instance field") + } + coords(f.x, f.y, f.rotation)?; + } pins( &self .libraries @@ -517,6 +578,9 @@ impl Document { } for l in &self.labels { self.endpoint(&l.endpoint)?; + if let Some(angle) = l.angle { + coords(0., 0., angle)?; + } } Ok(()) } @@ -641,6 +705,14 @@ impl Document { ("Reference", c.reference.as_str(), -2.54), ("Value", c.value.as_str(), 0.0), ] { + if let Some(f) = c.fields.get(key) { + let a = -(c.rotation as f64).to_radians(); + let x = c.x + f.x * a.cos() + f.y * a.sin(); + let y = c.y + f.x * a.sin() - f.y * a.cos(); + let angle = (f.rotation + c.rotation) % 180; + out+=&format!("(property {} {} (at {x} {y} {angle}) (effects (font (size 1.27 1.27)) (justify left)))\n",q(key),q(value)); + continue; + } if let Some(source) = lib .list() .iter() @@ -730,7 +802,10 @@ impl Document { .find(|p| p.number == l.endpoint.pin) .context("Unknown label pin")?; // Library pin angles point toward the body; label text extends out. - let angle = (pin.angle + c.rotation as f64 + 180.0).rem_euclid(360.0); + let angle = l + .angle + .map(f64::from) + .unwrap_or_else(|| (pin.angle + c.rotation as f64 + 180.0).rem_euclid(360.0)); let justify = if angle < 180.0 { "left" } else { "right" }; out+=&format!("(label {} (at {} {} {angle}) (effects (font (size 1.27 1.27)) (justify {justify} bottom)) (uuid {}))\n",q(&l.net),a[0],a[1],id(&self.id,&format!("label:{}:{}",l.endpoint.reference,l.endpoint.pin))); } @@ -769,6 +844,7 @@ mod tests { x: 50., y: 50., rotation: 0, + fields: BTreeMap::new(), }, }, ], @@ -784,6 +860,7 @@ mod tests { pin: "1".into(), }, net: "SUPPLY".into(), + angle: None, }); // The manufacturer's field is (+5.08,+5.08) in Y-up library space. // Its upper vertical pin points down toward the body (270 degrees). @@ -845,6 +922,118 @@ mod tests { assert_eq!(p.document.libraries["cap"].symbol, CAP); } #[test] + fn text_layout_preserves_electrical_anchors_and_survives_restore() { + let p = placed(); + let endpoint = PinRef { + reference: "C1".into(), + pin: "1".into(), + }; + let p = p + .stage(&tx( + &p, + "label", + vec![Operation::Label { + label: Label { + endpoint: endpoint.clone(), + net: "VDD".into(), + angle: None, + }, + }], + )) + .unwrap(); + let pins_before = p.document.pin_inventory().unwrap(); + let q = p + .stage(&tx( + &p, + "text", + vec![ + Operation::PlaceField { + reference: "C1".into(), + field: "Reference".into(), + x: 5.08, + y: 1.27, + rotation: 0, + }, + Operation::StyleLabel { + endpoint: endpoint.clone(), + angle: 0, + }, + ], + )) + .unwrap(); + assert_eq!(q.document.pin_inventory().unwrap(), pins_before); + assert_eq!(q.document.labels[0].net, "VDD"); + assert_eq!( + q.document.libraries["cap"].source_sha256, + p.document.libraries["cap"].source_sha256 + ); + let export = q.document.export_kicad().unwrap(); + let preview = crate::kicad_self::render_inner(&export); + assert!(preview.contains("translate(55.080 48.730) rotate(-0.000)")); + assert!(preview.contains(">VDD")); + let crop = crate::sch_parse::parse(&export).content_bbox; + assert!(crop.0 <= 50.0 && crop.0 + crop.2 > 55.08); + let left_label = export.replace("(justify left bottom)", "(justify right bottom)").replace("\"VDD\"", "\"A_LONG_NET_LABEL\""); + assert!(crate::sch_parse::parse(&left_label).content_bbox.0 < 35.0); + + let native = parse(&export).unwrap(); + let label = native + .list() + .iter() + .find(|n| n.tag() == Some("label")) + .unwrap(); + assert_eq!(label.child("at").unwrap().arg(3).unwrap(), "0"); + let component = native + .list() + .iter() + .find(|n| n.tag() == Some("symbol")) + .unwrap(); + let field = component + .list() + .iter() + .find(|n| n.tag() == Some("property") && n.arg(1).ok() == Some("Reference")) + .unwrap(); + let at = field.child("at").unwrap(); + assert_eq!(at.arg(1).unwrap().parse::().unwrap(), 55.08); + assert_eq!(at.arg(2).unwrap().parse::().unwrap(), 48.73); + // Invalid rotation rejects the batch, including its earlier field move. + assert!(q + .stage(&tx( + &q, + "bad-style", + vec![ + Operation::PlaceField { + reference: "C1".into(), + field: "Value".into(), + x: 99., + y: 99., + rotation: 0 + }, + Operation::StyleLabel { + endpoint, + angle: 45 + }, + ] + )) + .is_err()); + assert!(!q.document.components["C1"].fields.contains_key("Value")); + let folder = std::env::temp_dir().join(format!("adom-text-{}", Uuid::new_v4())); + q.persist(&folder).unwrap(); + let restored = Project::restore(&folder).unwrap(); + assert_eq!( + restored.document.export_kicad().unwrap(), + q.document.export_kicad().unwrap() + ); + let undone = q + .stage(&tx(&q, "undo-text", vec![Operation::Undo])) + .unwrap(); + assert_eq!( + undone.document.export_kicad().unwrap(), + p.document.export_kicad().unwrap() + ); + std::fs::remove_dir_all(folder).unwrap(); + } + #[test] fn detects_wire_through_unintended_capacitor_pin() { let mut p = placed(); p.document.components.insert( @@ -856,6 +1045,7 @@ mod tests { x: 70., y: 30., rotation: 0, + fields: BTreeMap::new(), }, ); p.document.connections.push(Connection { @@ -962,6 +1152,7 @@ mod tests { label: Label { endpoint: pin, net: "VIO".into(), + angle: None, }, }, ], diff --git a/src/author_ui.js b/src/author_ui.js index 40a042b..c6334e3 100644 --- a/src/author_ui.js +++ b/src/author_ui.js @@ -2,15 +2,20 @@ (async()=>{ const initial=await fetch('state').then(r=>r.json());if(!initial.author)return; let latest=initial.author;const style=document.createElement('style');style.textContent=` - body.author #svgbox{top:152px!important}body.author #side{display:none!important}#authorBar{position:absolute;top:44px;left:0;right:0;min-height:92px;z-index:10;padding:6px 12px;background:var(--panel,#15202b);border-bottom:1px solid var(--edge,#39434d);font:12px sans-serif;color:var(--ink,#eee)} + body.author #svgbox{top:var(--author-canvas-top,152px)!important}body.author #side{display:none!important}#authorBar{position:absolute;top:44px;left:0;right:0;min-height:92px;z-index:10;padding:6px 12px;background:var(--panel,#15202b);border-bottom:1px solid var(--edge,#39434d);font:12px sans-serif;color:var(--ink,#eee)} #authorBar .row{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin:4px 0}#authorBar input,#authorBar select,#authorBar button{font:inherit;background:var(--bg,#18232e);color:inherit;border:1px solid var(--edge,#40505d);border-radius:4px;padding:4px}#authorBar input[type=number]{width:48px}#authorBar .ref{width:44px}#authorStatus{color:var(--muted,#abb7c2)}#authorBar a{color:var(--accent,#73caca)} `;document.head.append(style);document.body.classList.add('author'); - const bar=document.createElement('section');bar.id='authorBar';bar.innerHTML=`
Development circuit • not releasedKiCad file
`;document.body.append(bar); + const bar=document.createElement('section');bar.id='authorBar';bar.innerHTML=`
Development circuit • not releasedKiCad file
Text layout
Text only; electrical anchors stay fixed.
`;document.body.append(bar);new ResizeObserver(()=>document.body.style.setProperty('--author-canvas-top',`${44+bar.getBoundingClientRect().height}px`)).observe(bar); const $=s=>document.getElementById(s);function options(el,rows){const old=el.value;el.replaceChildren(...rows.map(([v,t])=>{const o=document.createElement('option');o.value=v;o.textContent=t;return o}));if(rows.some(([v])=>v===old))el.value=old;} - function update(s){if(!s.author)return;latest=s.author;window.AdomAuthorSnapshot=s;window.AdomAuthorState=latest;window.AdomSch.mount(s.svg,s.meta);$('authorRevision').textContent=`${s.name} · revision ${latest.revision}`;options($('authorLib'),latest.libraries.map(k=>[k,k]));const pins=latest.pins.map(p=>[JSON.stringify(p.endpoint),`${p.endpoint.reference}.${p.endpoint.pin}`]);options($('authorFrom'),pins);options($('authorTo'),pins);requestAnimationFrame(()=>requestAnimationFrame(()=>fetch('author/ack',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({revision:latest.revision,componentCount:latest.pins.length?Object.keys(latest.components).length:0,paintedAt:new Date().toISOString()})})));} + function update(s){if(!s.author)return;latest=s.author;window.AdomAuthorSnapshot=s;window.AdomAuthorState=latest;window.AdomSch.mount(s.svg,s.meta);$('authorRevision').textContent=`${s.name} · revision ${latest.revision}`;options($('authorLib'),latest.libraries.map(k=>[k,k]));const pins=latest.pins.map(p=>[JSON.stringify(p.endpoint),`${p.endpoint.reference}.${p.endpoint.pin}`]);options($('authorFrom'),pins);options($('authorTo'),pins);options($('authorFieldRef'),Object.keys(latest.components).map(r=>[r,r]));options($('authorLabelPin'),latest.labels.map(l=>[JSON.stringify(l.endpoint),`${l.endpoint.reference}.${l.endpoint.pin}: ${l.net}`]));requestAnimationFrame(()=>requestAnimationFrame(()=>fetch('author/ack',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({revision:latest.revision,componentCount:latest.pins.length?Object.keys(latest.components).length:0,paintedAt:new Date().toISOString()})})));} async function transact(operations){const r=await fetch('author/transaction',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({aiThread:'Schematic UI',expectedRevision:latest.revision,operationId:crypto.randomUUID(),operations})});const s=await r.json();if(!s.ok){window.AdomSch.toast(s.error,'error');return}window.AdomSch.toast(`Saved revision ${s.revision}`,'success');} $('authorPlace').onclick=()=>transact([{op:'place',component:{reference:$('authorRef').value,library:$('authorLib').value,value:$('authorLib').value,x:Number($('authorX').value),y:Number($('authorY').value),rotation:0}}]); $('authorConnect').onclick=()=>{if(!$('authorFrom').value||!$('authorTo').value)return;transact([{op:'connect',connection:{id:crypto.randomUUID(),from:JSON.parse($('authorFrom').value),to:JSON.parse($('authorTo').value)}}]);}; + $('authorFieldApply').onclick=()=>transact([{op:'place_field',reference:$('authorFieldRef').value,field:$('authorFieldName').value,x:Number($('authorFieldX').value),y:Number($('authorFieldY').value),rotation:Number($('authorFieldAngle').value)}]); + $('authorLabelApply').onclick=()=>{if($('authorLabelPin').value)transact([{op:'style_label',endpoint:JSON.parse($('authorLabelPin').value),angle:Number($('authorLabelAngle').value)}]);}; + function fieldSelection(){const f=latest.components[$('authorFieldRef').value]?.fields?.[$('authorFieldName').value];if(f){$('authorFieldX').value=f.x;$('authorFieldY').value=f.y;$('authorFieldAngle').value=f.rotation;}} + $('authorFieldRef').onchange=fieldSelection;$('authorFieldName').onchange=fieldSelection; + $('authorLabelPin').onchange=()=>{const l=latest.labels.find(l=>JSON.stringify(l.endpoint)===$('authorLabelPin').value);if(l?.angle!==undefined)$('authorLabelAngle').value=l.angle;}; $('authorNative').onclick=async()=>{const r=await fetch('author/native');const v=await r.json();if(!v.ok){window.AdomSch.toast(v.error,'error');return}window.AdomSch.mount(v.svg,v.meta);$('authorStatus').textContent=`KiCad ${v.report.kicadVersion} service render • revision ${v.report.revision} • ${v.report.violationCount} ERC findings`;}; $('authorLocal').onclick=()=>{update({name:initial.name,author:latest,...window.AdomAuthorSnapshot});$('authorStatus').textContent='Live Rust preview • native checks separate';}; $('authorUndo').onclick=()=>transact([{op:'undo'}]);update(initial);const events=new EventSource('events');events.addEventListener('state',e=>update(JSON.parse(e.data)));events.onerror=()=>{$('authorStatus').textContent='Reconnecting… saved document retained';};events.onopen=()=>{$('authorStatus').textContent='Live • development circuit • ERC pending';}; diff --git a/src/kicad_self.rs b/src/kicad_self.rs index 8f34982..16354d9 100644 --- a/src/kicad_self.rs +++ b/src/kicad_self.rs @@ -328,6 +328,20 @@ fn nth_quoted(s: &str, n: usize) -> Option { /// Render the sheet's drawable content (symbols + wires + power + labels) as the /// inner SVG for ``. Returns "" if there's nothing to draw. +fn placed_text(block: &str, text: &str, color: &str) -> String { + if text.is_empty() || block.contains("(hide yes)") || block.contains("hide)") { return String::new(); } + let at = Regex::new(r"\(at\s+(-?[\d.]+)\s+(-?[\d.]+)(?:\s+(-?[\d.]+))?\)").unwrap(); + let Some(a) = at.captures(block) else { return String::new() }; + let (x, y, angle) = (f(a.get(1)), f(a.get(2)), f(a.get(3)).rem_euclid(180.0)); + let justify = capture1(block, r"\(justify\s+([^)]*)\)").unwrap_or_default(); + let words: Vec<_> = justify.split_whitespace().collect(); + let anchor = if words.contains(&"left") { "start" } else if words.contains(&"right") { "end" } else { "middle" }; + let baseline = if words.contains(&"bottom") { "auto" } else if words.contains(&"top") { "hanging" } else { "central" }; + let size = capture1(block, r"\(size\s+([\d.]+)").and_then(|s| s.parse::().ok()).unwrap_or(1.27); + let dy = if words.contains(&"bottom") { -0.25 } else { 0.0 }; + format!(r##"{text}"##, rotation=-angle, text=esc(text)) +} + pub fn render_inner(content: &str) -> String { let at3 = Regex::new(r"\(at\s+(-?[\d.]+)\s+(-?[\d.]+)(?:\s+(-?[\d.]+))?\)").unwrap(); let se = Regex::new(r"\(start\s+(-?[\d.]+)\s+(-?[\d.]+)\)\s*\(end\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap(); @@ -393,13 +407,7 @@ pub fn render_inner(content: &str) -> String { for l in blocks(&content_wo_lib, "label").into_iter() .chain(blocks(&content_wo_lib, "global_label")) .chain(blocks(&content_wo_lib, "hierarchical_label")) { - if let Some(a) = at3.captures(l) { - let text = quoted(l).unwrap_or_default(); - if !text.is_empty() { - let _ = write!(out, r##"{}"##, - f(a.get(1)) + 0.5, f(a.get(2)), C_LABEL, esc(&text)); - } - } + out.push_str(&placed_text(l, "ed(l).unwrap_or_default(), C_LABEL)); } // ── symbol instances ── @@ -409,18 +417,16 @@ pub fn render_inner(content: &str) -> String { let (px, py, rot) = (f(a.get(1)), f(a.get(2)), f(a.get(3))); let mirror = mirror_re.captures(inst).map(|c| if &c[1] == "x" { 2u8 } else { 1u8 }).unwrap_or(0); - let (mut reference, mut value) = (String::new(), String::new()); + let mut reference = String::new(); for c in prop.captures_iter(inst) { - match &c[1] { "Reference" => reference = c[2].to_string(), "Value" => value = c[2].to_string(), _ => {} } + if &c[1] == "Reference" { reference = c[2].to_string(); } } let is_power = lib_id.starts_with("power:"); let lib = resolve_lib(&libs, &bare, &lib_id); let mut body = String::new(); - let (mut minx, mut miny, mut maxx, mut maxy) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); if let Some(lib) = lib { for pr in &lib.prims { let tp: Vec<(f64, f64)> = pr.pts.iter().map(|&(x, y)| xf(x, y, px, py, rot, mirror)).collect(); - for &(x, y) in &tp { minx = minx.min(x); miny = miny.min(y); maxx = maxx.max(x); maxy = maxy.max(y); } match pr.kind { 1 => { let _ = write!(body, r##""##, tp[0].0, tp[0].1, pr.r, C_SYM); } 2 => { let _ = write!(body, r##""##, tp[0].0, tp[0].1, tp[1].0, tp[1].1, C_SYM); } @@ -428,15 +434,13 @@ pub fn render_inner(content: &str) -> String { } } } - if !minx.is_finite() { minx = px - 1.27; miny = py - 1.27; maxx = px + 1.27; maxy = py + 1.27; } - // power symbols show their net name; regular parts show ref + value - if is_power { - if !value.is_empty() { - let _ = write!(body, r##"{}"##, px, maxy + 1.6, C_LABEL, esc(&value)); - } - } else if !reference.is_empty() { - let _ = write!(body, r##"{}"##, maxx + 0.4, miny + 1.2, C_NAME, esc(&reference)); - if !value.is_empty() { let _ = write!(body, r##"{}"##, maxx + 0.4, miny + 2.7, C_VALUE, esc(&value)); } + // Native instance properties already carry absolute sheet positions. + for pb in blocks(inst, "property") { + let name = quoted(pb).unwrap_or_default(); + if name != "Reference" && name != "Value" { continue; } + if is_power && name == "Reference" { continue; } + let color = if is_power { C_LABEL } else if name == "Reference" { C_NAME } else { C_VALUE }; + body.push_str(&placed_text(pb, &nth_quoted(pb, 1).unwrap_or_default(), color)); } let _ = write!(out, r##"{}"##, esc(&reference), body); } diff --git a/src/sch_parse.rs b/src/sch_parse.rs index 3efbe03..d8472ac 100644 --- a/src/sch_parse.rs +++ b/src/sch_parse.rs @@ -208,7 +208,7 @@ pub fn parse(content: &str) -> Sheet { else if pb.contains("(justify left") { (0.0, w) } else { (-w / 2.0, w / 2.0) }; let r = if (trot - 90.0).abs() < 1.0 || (trot - 270.0).abs() < 1.0 { - [tx - hh, ty + a0, tx + hh, ty + a1] // vertical text + [tx - hh, ty - a1, tx + hh, ty - a0] // positive KiCad rotation reads upward } else { [tx + a0, ty - hh, tx + a1, ty + hh] }; @@ -219,6 +219,18 @@ pub fn parse(content: &str) -> Sheet { } // include wires in the content bounds so the crop isn't too tight + for tag in ["label", "global_label", "hierarchical_label"] { + for label in blocks(&content_wo_lib, tag) { + let Some(a) = at3.captures(label) else { continue }; + let (tx, ty, angle) = (f(a.get(1)), f(a.get(2)), f(a.get(3)).rem_euclid(180.0)); + let size = Regex::new(r"\(size\s+([\d.]+)").ok().and_then(|r| r.captures(label).map(|c| f(c.get(1)))).unwrap_or(1.27); + let w = quoted(label).unwrap_or_default().chars().count() as f64 * size * 0.9 + 1.2; + let (a0, a1) = if label.contains("(justify right") { (-w, 0.0) } else { (0.0, w) }; + let r = if (angle - 90.0).abs() < 1.0 { [tx-size, ty-a1, tx+size, ty-a0] } + else { [tx+a0, ty-size, tx+a1, ty+size] }; + gminx = gminx.min(r[0]); gminy = gminy.min(r[1]); gmaxx = gmaxx.max(r[2]); gmaxy = gmaxy.max(r[3]); + } + } for w in blocks(&content_wo_lib, "wire") { for c in xy.captures_iter(w) { let (x, y) = (f(c.get(1)), f(c.get(2))); gminx = gminx.min(x); gminy = gminy.min(y); gmaxx = gmaxx.max(x); gmaxy = gmaxy.max(y); } }