UNPKG

@wayrisignals/kicad-webview

Version:

Interactive KiCad schematic, PCB and 3D viewer for the web, with Gerber, Excellon, linked views and offline HTML exports

445 lines (440 loc) • 25.8 kB
/* Copyright (c) 2026 wayri. SPDX-License-Identifier: MPL-2.0 */ /* Saved KiCad object comparison. Browser-only; no geometry renderer required. */ ((root) => { "use strict"; const MAX_FILE = 256 * 1024 * 1024; const sourceByteLimit = () => MAX_FILE; const MAX_PROJECT = 512 * 1024 * 1024; const MAX_FILES = 128; const MAX_DEPTH = 96; const MAX_NODES = 12000000; const MAX_RENDER_PRIMITIVES = 1500000; const SCHEMATIC = new Set(["symbol", "sheet", "wire", "bus", "bus_entry", "label", "global_label", "hierarchical_label", "junction", "no_connect", "text", "text_box", "polyline", "rectangle", "circle", "arc", "image", "rule_area", "netclass_flag", "directive_label"]); const BOARD = new Set(["footprint", "segment", "arc", "via", "zone", "gr_line", "gr_rect", "gr_circle", "gr_arc", "gr_poly", "gr_curve", "gr_text", "gr_text_box", "gr_bitmap", "dimension", "target"]); const OMIT = new Set(["uuid", "tstamp", "filled_polygon", "fill_segments"]); const NUMBER = /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/; // Count source bytes without allocating a second full-size UTF-8 buffer. function sourceByteLength(source) { if(typeof source!=='string')throw new TypeError('KiCad source must be a string.'); if(!/[^\x00-\x7f]/.test(source))return source.length; let bytes=source.length; for(let i=0;i<source.length;i++){ const code=source.charCodeAt(i);if(code<128)continue; if(code<2048){bytes++;continue;} if(code>=0xd800&&code<=0xdbff&&i+1<source.length){const next=source.charCodeAt(i+1);if(next>=0xdc00&&next<=0xdfff){bytes+=2;i++;continue;}} bytes+=2; } return bytes; } // KiCad files are overwhelmingly ASCII. Keep the same ECMAScript whitespace // grammar without constructing/testing a regular expression for every byte. const spaceCode=code=>code===32||(code>=9&&code<=13)||(code>127&&/\s/.test(String.fromCharCode(code))); // Adaptive cubic flattening in world millimetres. The control hull is kept // within 5 micrometres of each output segment; unlike a fixed segment count, // this also preserves small loops and collinear control-point overshoot. function cubicBezierPoints(control) { if (!Array.isArray(control) || control.length !== 4 || control.some(p => !p || !Number.isFinite(p.x) || !Number.isFinite(p.y))) throw Error('Bezier requires four finite control points.'); const result = [{...control[0]}], pending = [control], tolerance2 = .005 ** 2; const distance2 = (p, a, b) => { const dx = b.x-a.x, dy = b.y-a.y, length2 = dx*dx+dy*dy; const t = length2 ? Math.max(0, Math.min(1, ((p.x-a.x)*dx+(p.y-a.y)*dy)/length2)) : 0; return (p.x-a.x-t*dx)**2+(p.y-a.y-t*dy)**2; }; const middle = (a,b) => ({x:a.x/2+b.x/2,y:a.y/2+b.y/2}); while (pending.length) { const [a,b,c,d] = pending.pop(); if (Math.max(distance2(b,a,d),distance2(c,a,d)) <= tolerance2) { if (result.length >= 2049) throw Error('Bezier exceeds the bounded tessellation budget.'); result.push({...d}); } else { const ab=middle(a,b),bc=middle(b,c),cd=middle(c,d),abc=middle(ab,bc),bcd=middle(bc,cd),center=middle(abc,bcd); if (pending.length > 32 || [ab,bc,cd,abc,bcd,center].some(p => !Number.isFinite(p.x)||!Number.isFinite(p.y))) throw Error('Bezier exceeds the bounded tessellation budget.'); pending.push([center,bcd,cd,d],[a,ab,abc,center]); } } return result; } const METADATA_FIELDS=new Set(["version","generator","generator_version","uuid","paper","title_block","property","sheet","symbol","footprint","module","sheet_instances","legacy_source","legacy_diagnostic"]); const FONT_METADATA_FIELDS=new Set([...METADATA_FIELDS,"embedded_files"]); const METADATA_OBJECT_FIELDS=new Set(["property","uuid","path","instances"]); function parse(source, options = {}) { if (typeof source !== "string") throw new TypeError("KiCad source must be a string."); if (/^\s*PCBNEW-BOARD/.test(source))throw Error('Legacy .brd boards are detected but this drawing format is not yet rendered. Open and save a separate .kicad_pcb copy in KiCad.'); if (/^\s*EESchema Schematic File Version [24]\b/.test(source)) { const legacy=root.KiCadLegacy||(typeof module==='object'&&module.exports?require('./legacy-kicad.js'):null); if(!legacy)throw Error('Legacy schematic adapter is unavailable; reload the extension.'); return legacy.parse(source,options); } // UTF-8 uses at most three bytes per UTF-16 code unit. Avoid a full-size // temporary byte array when that upper bound already proves the input fits. if(source.length>MAX_FILE||source.length>MAX_FILE/3&&sourceByteLength(source)>MAX_FILE)throw new Error("KiCad file exceeds browser parser size limits."); const stack = [], roots = []; // Canonical saved vertices dominate large copper fills. Consume the whole // form at once, leaving uncommon whitespace, comments and malformed forms // to the general parser. const coordinate = /\(xy[ \t]+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)[ \t]+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)[ \t]*\)/y; let i = 0, nodes = 0, skippedDepth=0; const isFilledZone = () => stack.length === 3 && stack[0][0] === 'kicad_pcb' && stack[1][0] === 'zone' && stack[2][0] === 'filled_polygon'; // Scan ordinary KiCad fills directly into a numeric buffer. If an unfamiliar // form occurs, leave the cursor unchanged and let the ordinary reader handle it. function packedContour(start) { let cursor = start + 4, length = 0; let coordinates = new Float64Array(128); while (cursor < source.length) { while (spaceCode(source.charCodeAt(cursor))) cursor++; if (source.charCodeAt(cursor) === 41) { if (length < 6) return null; nodes += 1 + length * 2; // pts name and four nodes per vertex. append(['pts', length === coordinates.length ? coordinates : coordinates.slice(0, length)]); return cursor + 1; } coordinate.lastIndex = cursor; const match = coordinate.exec(source); if (!match) return null; const x = Number(match[1]), y = Number(match[2]); if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error("Invalid numeric KiCad value."); if (nodes + 6 + length * 2 > MAX_NODES) throw new Error("KiCad file has too many S-expression nodes."); if (length === coordinates.length) { const larger = new Float64Array(coordinates.length * 2); larger.set(coordinates); coordinates = larger; } coordinates[length++] = x; coordinates[length++] = y; cursor = coordinate.lastIndex; } return null; } const append = (item) => { if (++nodes > MAX_NODES) throw new Error("KiCad file has too many S-expression nodes."); if(!skippedDepth)(stack.at(-1) || roots).push(item); }; while (i < source.length) { const ch = source[i]; if (spaceCode(source.charCodeAt(i))) { i++; continue; } if((ch==="<"||ch===">")&&/^(?:<{7,}|>{7,})(?:\s|$)/.test(source.slice(i,i+120)))throw new Error("Unresolved Git merge conflict at line "+(source.slice(0,i).split("\n").length)+". Resolve the conflict in a separate copy before viewing."); if (ch === ";") { while (i < source.length && source[i] !== "\n") i++; continue; } if (ch === "(") { if (stack.length >= MAX_DEPTH) throw new Error("KiCad S-expression is too deep."); if (options.compactCopper && !options.metadataOnly && source.startsWith('(pts', i) && spaceCode(source.charCodeAt(i + 4)) && isFilledZone()) { const next = packedContour(i); if (next !== null) { i = next; continue; } } if (!options.metadataOnly && stack.length && source.startsWith('(xy', i)) { coordinate.lastIndex = i; const match = coordinate.exec(source); if (match) { const x = Number(match[1]), y = Number(match[2]); if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error("Invalid numeric KiCad value."); nodes += 3; // The name and both coordinates, in addition to the form. append(['xy', x, y]); i = coordinate.lastIndex; continue; } } if(options.metadataOnly&&!skippedDepth){let allowed=null; if(stack.length===1)allowed=options.includeEmbeddedFonts?FONT_METADATA_FIELDS:METADATA_FIELDS; else if(stack.length===2&&['symbol','footprint','module'].includes(stack.at(-1)?.[0]))allowed=METADATA_OBJECT_FIELDS; else if(stack.at(-1)?.[0]==='property')allowed=new Set(); if(allowed){let start=i+1;while(start<source.length&&spaceCode(source.charCodeAt(start)))start++;let end=start;while(end<source.length&&!spaceCode(source.charCodeAt(end))&&!['(',')',';'].includes(source[end]))end++;if(!allowed.has(source.slice(start,end)))skippedDepth=stack.length+1;} } const node = []; append(node); stack.push(node); i++; continue; } if (ch === ")") { if (!stack.length) throw new Error("Unexpected closing parenthesis in KiCad file."); const node=stack.pop(); // Fixed-size small forms avoid retaining the spare capacity of millions // of growable coordinate/attribute arrays. The public tree shape stays // identical; replace only a completed child, never a live stack frame. if(!skippedDepth&&node.length>0&&node.length<=4){ const compact = node.slice(); const parent=stack.at(-1)||roots;parent[parent.length-1]=compact; } if(skippedDepth&&stack.length<skippedDepth)skippedDepth=0; i++; continue; } if (!stack.length) throw new Error("Expected a KiCad S-expression."); if (ch === '"') { let segments=null, chunkStart=++i, closed=false, text=''; while(i<source.length){ const next=source[i++]; if(next==='"'){ closed=true; if(!skippedDepth){const tail=source.slice(chunkStart,i-1);if(segments){segments.push(tail);text=segments.join('');}else text=tail;} break; } if(next==='\\'){ if(i>=source.length)throw new Error("Unterminated KiCad escape sequence."); const escaped=source[i++]; if(!skippedDepth){ segments??=[];segments.push(source.slice(chunkStart,i-2)); const decoded=({n:"\n",r:"\r",t:"\t",'"':'"',"\\":"\\"})[escaped];segments.push(decoded===undefined?'\\'+escaped:decoded); } chunkStart=i; } } if(!closed)throw new Error("Unterminated quoted KiCad string."); append(skippedDepth?null:{quoted:text});continue; } const start = i; while (i < source.length) { const code=source.charCodeAt(i);if(code===40||code===41||code===59||code===34||spaceCode(code))break;i++; } if (start === i) throw new Error("Unexpected KiCad source character."); if(skippedDepth){append(null);continue;} const token = source.slice(start, i); if (NUMBER.test(token)) { const number = Number(token); if (!Number.isFinite(number)) throw new Error("Invalid numeric KiCad value."); append(number); } else append(token==='xy'?'xy':token); } if (stack.length || roots.length !== 1 || !Array.isArray(roots[0])) { throw new Error("Incomplete KiCad S-expression."); } return roots[0]; } const value = (item) => item && typeof item === "object" && !Array.isArray(item) ? item.quoted : item; const kindOf = (form) => Array.isArray(form) ? String(value(form[0])) : ""; const children = (form, kind) => form.filter((item) => Array.isArray(item) && kindOf(item) === kind); const child = (form, kind) => form.find(item => Array.isArray(item) && kindOf(item) === kind); const second = (form, kind) => value(child(form, kind)?.[1]); function ruleAreaPoints(form) { const polygon = child(form, "polyline"); const coordinates = polygon && child(polygon, "pts"); if (!coordinates || coordinates.length < 4 || coordinates.length > 4097) return null; const points = []; for (const item of coordinates.slice(1)) { const x = value(item?.[1]), y = value(item?.[2]); if (!Array.isArray(item) || kindOf(item) !== "xy" || !Number.isFinite(x) || !Number.isFinite(y)) return null; const last = points.at(-1); if (last?.x !== x || last.y !== y) points.push({ x, y }); } if (points[0].x === points.at(-1).x && points[0].y === points.at(-1).y) points.pop(); if (points.length < 3) return null; const origin = points[0]; let area = 0; for (let i = 1; i < points.length - 1; i++) { const a = points[i], b = points[i + 1]; area += (a.x - origin.x) * (b.y - origin.y) - (a.y - origin.y) * (b.x - origin.x); } return Number.isFinite(area) && area !== 0 ? points : null; } function point(form) { for (const name of ["at", "start", "center", "end", "xy"]) { const item = child(form, name); if (item && Number.isFinite(value(item[1])) && Number.isFinite(value(item[2]))) { return { x: value(item[1]), y: value(item[2]) }; } } for (const name of ["pts", "polygon"]) { const wrapper = child(form, name); const xy = wrapper && child(name === "polygon" ? child(wrapper, "pts") || wrapper : wrapper, "xy"); if (xy && Number.isFinite(value(xy[1])) && Number.isFinite(value(xy[2]))) { return { x: value(xy[1]), y: value(xy[2]) }; } } return null; } function properties(form, kind) { const entries = []; for (const field of children(form, "property")) { if (field.length >= 3) entries.push([String(value(field[1])), String(value(field[2]))]); } if(kind==="footprint")for(const [role,name]of [["reference","Reference"],["value","Value"]]){ const legacy=children(form,"fp_text").find(field=>value(field[1])===role); if(legacy&&legacy.length>=3&&!entries.some(([key])=>key===name))entries.push([name,String(value(legacy[2]))]); } for (const key of ["lib_id", "layer", "width", "drill", "size", "unit"]) { const found = child(form, key); if (found) entries.push([key, found.slice(1).map(value).join(", ")]); } const layers = child(form, "layers"); if (layers) entries.push(["Layers", layers.slice(1).map(value).join(", ")]); const net = child(form, "net"); if (net) entries.push(["Net", String(value(net[2] ?? net[1]))]); const at = child(form, "at"); if (at && Number.isFinite(value(at[3]))) entries.push(["Angle", String(value(at[3]))]); if (["label", "global_label", "hierarchical_label", "text", "gr_text", "gr_text_box"].includes(kind)) { entries.push(["Text", String(value(form[1] ?? ""))]); } if (kind === "pad") { entries.push(["Number", String(value(form[1] ?? ""))]); entries.push(["Type", String(value(form[2] ?? ""))]); entries.push(["Shape", String(value(form[3] ?? ""))]); } return Object.fromEntries(entries); } function structural(form) { if (!Array.isArray(form)) return form && typeof form === "object" ? ["quoted", form.quoted] : form; return form.filter((item) => !Array.isArray(item) || !OMIT.has(kindOf(item))).map(structural); } function hash(text) { let h = 2166136261; for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 16777619); return (h >>> 0).toString(16).padStart(8, "0"); } function identity(form, kind, props, signature) { const uuid = second(form, "uuid") ?? second(form, "tstamp") ?? (kind === "rule_area" && child(form, "polyline") ? second(child(form, "polyline"), "uuid") : undefined); if (uuid !== undefined && uuid !== null && String(uuid)) return { key: `uuid:${uuid}`, uuid: String(uuid) }; const anchor = kind === "pad" ? props.Number : kind === "sheet" ? props.Sheetfile : kind === "symbol" || kind === "footprint" ? props.Reference : undefined; return { key: anchor ? `fallback:${String(anchor)}` : `fallback:${hash(typeof signature==="function"?signature():signature)}`, uuid: null }; } function labelFor(form, kind, props, parentLabel) { if (kind === "pad") return `${parentLabel || "Footprint"} pad ${props.Number || ""}`.trim(); return props.Reference || props.Sheetname || props['Sheet name'] || props.Text || (kind === "footprint" ? String(value(form[1] ?? "Footprint")) : kind === "symbol" ? props.lib_id || "symbol" : kind === "netclass_flag" || kind === "directive_label" ? "Directive label" : kind === "rule_area" ? "Rule area" : kind.replace(/_/g, " ")); } function padPosition(local, placement) { if (!local || !placement?.position) return null; const angle = Number(value(child(placement.form, "at")?.[3] ?? 0)); const radians = (Number.isFinite(angle) ? angle : 0) * Math.PI / 180; const c = Math.cos(radians), s = Math.sin(radians); const x = placement.position.x + local.x * c + local.y * s; const y = placement.position.y - local.x * s + local.y * c; const rounded = (number) => Math.round(number * 1e6) / 1e6; return { x: rounded(x), y: rounded(y) }; } function objectRecord(path, form, parent = null, librarySignature = null, forConnectivity = false) { const kind = kindOf(form); const props = properties(form, kind); const local = point(kind === "rule_area" ? child(form, "polyline") || form : form); const position = kind === "pad" ? padPosition(local, parent) : local; let retainedSignature; const signature=()=>retainedSignature??=JSON.stringify([structural(form),position,typeof librarySignature==='function'?librarySignature():librarySignature]); // Connectivity needs saved identities and fields, not canonical comparison copies. if(!forConnectivity)props["Source fingerprint"]=hash(signature()); const identityValue = identity(form, kind, props, signature); const scope = parent ? `${parent.scope}/` : `${path}/`; const key = `${scope}${kind}:${identityValue.key}`; const label = labelFor(form, kind, props, parent?.label); return { key, scope: key, signature:forConnectivity?null:signature(), metadata: { uuid: identityValue.uuid, position, properties: props }, path, kind, label, form }; } function collect(path, content, onParsed = null, {forConnectivity=false,parseOnly=false,compactCopper=false} = {}, preparedAst) { const rootForm = preparedAst || parse(content, {compactCopper}); onParsed?.(rootForm); const rootKind = kindOf(rootForm); if (rootKind !== "kicad_sch" && rootKind !== "kicad_pcb") throw new Error("Expected a KiCad schematic or board."); if(parseOnly)return []; const types = rootKind === "kicad_sch" ? SCHEMATIC : BOARD; const definitions = new Map(); if (rootKind === "kicad_sch") { const library = child(rootForm, "lib_symbols"); if (library) for (const definition of children(library, "symbol")) { const name = value(definition[1]); if (typeof name === "string") definitions.set(name, forConnectivity?definition:JSON.stringify(structural(definition))); } } const objects = []; for (const form of rootForm) { if (!Array.isArray(form) || !types.has(kindOf(form))) continue; const definition = kindOf(form) === "symbol" ? definitions.get(String(second(form, "lib_name") ?? second(form, "lib_id"))) : null; const record = objectRecord(path, form, null, forConnectivity&&definition?()=>JSON.stringify(structural(definition)):definition, forConnectivity); objects.push(record); if (rootKind === "kicad_pcb" && record.kind === "footprint") { for (const pad of children(form, "pad")) objects.push(objectRecord(path, pad, { form, position: record.metadata.position, scope: record.scope, label: record.label }, null, forConnectivity)); } } return objects; } function parseMetadata(source,options={}){ const ast=parse(source,{...options,metadataOnly:true}); return ast.filter((item,index)=>index===0||Array.isArray(item)&&(options.includeEmbeddedFonts?FONT_METADATA_FIELDS:METADATA_FIELDS).has(item[0])).map(item=>Array.isArray(item)&&['symbol','footprint','module'].includes(item[0])?item.filter((field,index)=>index===0||Array.isArray(field)&&METADATA_OBJECT_FIELDS.has(field[0])):item); } // Job-scoped snapshots reuse validated source without retaining projects globally. const preparedProjects = new WeakMap(); function prepareProject(files, {forConnectivity=false,compactCopper=false} = {}) { const parsed = new Map(), records = projectObjects(files, (file, ast) => parsed.set(file.path, ast), null, {forConnectivity,parseOnly:forConnectivity,compactCopper:forConnectivity&&compactCopper}); const snapshot = Object.freeze({}); preparedProjects.set(snapshot, {files: files.map(file => ({path: file.path, content: file.content})), parsed, records:forConnectivity?null:records, forConnectivity}); return snapshot; } function preparedFile(snapshot, path, expectedContent) { const state = preparedProjects.get(snapshot); if (!state || !state.parsed.has(path)) throw new Error('Prepared KiCad file is unavailable.'); if (expectedContent !== undefined && !state.files.some(file => file.path === path && file.content === expectedContent)) throw new Error('Prepared KiCad file differs from source.'); return state.parsed.get(path); } function projectObjects(files, onParsed = null, snapshot = null, {forConnectivity=false,parseOnly=false,compactCopper=false} = {}) { if (snapshot) { const state = preparedProjects.get(snapshot); if (!state || !Array.isArray(files) || files.length !== state.files.length || files.some((file, index) => file?.path !== state.files[index].path || file?.content !== state.files[index].content)) { throw new Error('Prepared KiCad project differs from source.'); } if(state.forConnectivity!==forConnectivity||!state.records){ const records=[];for(const file of files)for(const record of collect(file.path,file.content,ast=>onParsed?.(file,ast),{forConnectivity},state.parsed.get(file.path)))records.push(record); return records; } for (const file of files) onParsed?.(file, state.parsed.get(file.path)); // Consumers assign IDs to records; keep those assignments isolated. return state.records.map(record => ({...record})); } if (!Array.isArray(files) || files.length > MAX_FILES) throw new Error("Too many KiCad files to compare."); const paths = new Set(), objects = []; let total = 0; for (const file of files) { if (!file || typeof file.path !== "string" || typeof file.content !== "string" || !/\.kicad_(?:sch|pcb)$/i.test(file.path) || paths.has(file.path)) { throw new Error("Invalid or duplicate KiCad file entry."); } paths.add(file.path); const size = sourceByteLength(file.content); total += size; if (size > MAX_FILE || total > MAX_PROJECT) throw new Error("KiCad project exceeds browser comparison size limits."); for (const object of collect(file.path, file.content, ast => onParsed?.(file, ast), {forConnectivity,parseOnly,compactCopper})) objects.push(object); } return objects; } function compareProjects(baseFiles, headFiles) { const base = projectObjects(baseFiles), head = projectObjects(headFiles); const grouped = new Map(); for (const record of base) { if (!grouped.has(record.key)) grouped.set(record.key, { before: [], after: [] }); grouped.get(record.key).before.push(record); } for (const record of head) { if (!grouped.has(record.key)) grouped.set(record.key, { before: [], after: [] }); grouped.get(record.key).after.push(record); } const changes = [], counts = { added: 0, removed: 0, modified: 0 }; const emit = (record, status, before, after, id) => { changes.push({ id, path: record.path, kind: record.kind, label: record.label, status, before: before?.metadata ?? null, after: after?.metadata ?? null }); counts[status]++; }; for (const [key, group] of grouped) { // Match exact duplicates first, then pair remaining objects deterministically. const before = [...group.before], after = [...group.after]; for (let i = before.length - 1; i >= 0; i--) { const j = after.findIndex((record) => record.signature === before[i].signature); if (j >= 0) { before.splice(i, 1); after.splice(j, 1); } } before.sort((a, b) => a.signature.localeCompare(b.signature)); after.sort((a, b) => a.signature.localeCompare(b.signature)); const count = Math.max(before.length, after.length); for (let i = 0; i < count; i++) { const old = before[i] || null, current = after[i] || null; const status = old && current ? "modified" : old ? "removed" : "added"; emit(current || old, status, old, current, count > 1 ? `${key}#${i + 1}` : key); } } changes.sort((a, b) => a.path.localeCompare(b.path) || a.id.localeCompare(b.id) || a.status.localeCompare(b.status)); return { changes, counts }; } root.KiCadDesignDiff = { compareProjects, projectObjects, parse, parseMetadata, sourceByteLimit, sourceByteLength, prepareProject, preparedFile, cubicBezierPoints, MAX_FILES, MAX_FILE_BYTES: MAX_FILE, MAX_PROJECT_BYTES: MAX_PROJECT, MAX_RENDER_PRIMITIVES, ruleAreaPoints }; if (typeof module === "object" && module.exports) module.exports = root.KiCadDesignDiff; })(typeof globalThis === "object" ? globalThis : this);