Files
likang 7e01147566
CI / typecheck + test + build (push) Has been cancelled
Initial commit: import VibeMake PCB Studio
2026-11-03 11:20:08 +08:00

202 lines
7.9 KiB
TypeScript

// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `LIB_TREE_ITEM` (include/lib_tree_item.h:40-88) — everything the library tree
* asks a symbol for, and nothing else:
*
* GetLIB_ID GetName GetLibNickname GetDesc GetChooserFields
* GetSearchTerms IsRoot IsPowerSymbol GetFootprint GetPinCount
* GetSubUnitCount
*
* Upstream's `LIB_SYMBOL` implements this on the resident symbol, because in
* KiCad the whole library set is already in memory: `SYMBOL_TREE_MODEL_ADAPTER`
* holds `LIB_SYMBOL*` and the tree calls straight through.
*
* We cannot. A parsed `.kicad_sym` retains **21.1x** its source text as JS
* objects (measured over 35 libraries with `--expose-gc`, qa/perf), so the 230 MB
* hosted set would be about 4.9 GB resident — past what V8 gives a tab, which is
* why keeping every library made the preload thrash rather than merely take a
* while. So the preload keeps the interface and drops the symbol: this is the
* projection, it is what crosses back from the parse worker, and the full
* `LIB_SYMBOL` is fetched one at a time by `loadSymbol` when something actually
* needs to draw or place it.
*
* `GetSearchTerms` is not a field here. It is *derived* — nickname 4, name 8,
* LIB_ID 16, each keyword token 4, the keyword string 1, the description 1 and
* the footprint 1 (eeschema/lib_symbol.cpp:160-183) — so carrying `keywords`
* and letting the tree build the terms is the same data without the duplication.
*/
// Straight from the declaring modules, not ./index.js: the barrel pulls in the tools and the
// frames, and through project_sch -> symbol_library_adapter this file is reached while
// SCH_BASE_FRAME is still being defined.
import { readSymbolLib } from './sch_io/sexpr/read-schematic.js';
import type { LibSymbol } from './types.js';
import { parse, type PruneOptions } from '@ziroeda/sexpr';
import { symbolChooserFields } from './lib_symbol.js';
import { LIB_ID } from '@ziroeda/common/lib_id.js';
import { type SearchTerm, searchTerm } from '@ziroeda/common/eda_pattern_match.js';
/** One symbol, reduced to what `LIB_TREE_ITEM` exposes. */
export interface LibTreeItem {
/** `GetName()`, the item half of the LIB_ID. */
name: string;
/** `GetDesc()`, the `Description` property. */
description: string;
/** `ki_keywords`, which `GetSearchTerms` tokenises. */
keywords: string;
/** `GetFootprint()`, the `Footprint` property. */
footprint: string;
/** `IsPowerSymbol()`. */
isPower: boolean;
/** `IsRoot()` — false for a symbol that `extends` another. */
isRoot: boolean;
/** `GetPinCount()`. */
pinCount: number;
/** `GetSubUnitCount()`. */
unitCount: number;
/** `GetChooserFields()`, the `(show_in_chooser yes)` properties. */
chooserFields: [string, string][];
}
/** A symbol's `(property ...)` value, or '' — `LIB_SYMBOL::GetDescription` etc. */
export function symbolProperty(sym: LibSymbol, key: string): string {
return sym.properties.find((p) => p.key === key)?.value ?? '';
}
/** `LIB_SYMBOL::GetPinCount`, the unit-1 (or common) graphical pins. */
export function libSymbolPinCount(sym: LibSymbol): number {
return sym.units.reduce((n, u) => n + (u.unit === 0 || u.unit === 1 ? u.pins.length : 0), 0);
}
/** `LIB_SYMBOL::GetSubUnitCount`, the distinct numbered units. */
export function libSymbolUnitCount(sym: LibSymbol): number {
return new Set(sym.units.map((u) => u.unit).filter((u) => u > 0)).size;
}
/**
* Project a parsed symbol onto the interface above.
*
* `name` is the bare item name: a symbol read straight out of a `.kicad_sym`
* carries its own name in `libId` with no nickname, and one that has already
* been through `loadLibrary` carries "Nickname:Name".
*/
export function libTreeItem(sym: LibSymbol): LibTreeItem {
// NOT gated on `show_in_chooser`. `SCH_FIELD::m_showInChooser` is initialised
// true, `SetShowInChooser` has no callers, and the token does not exist in
// KiCad 10.0.5 at all - so `cacheChooserFields` takes every field, and the
// shown columns each contribute a weight-4 term through
// `RebuildSearchTerms`. Gating here emptied that list and cost the chooser
// its ranking; the reasoning lives beside `symbolChooserFields` in
// ./lib_symbol.ts, which is where the rule is written once.
const chooserFields: [string, string][] = [...symbolChooserFields(sym)];
return {
name: sym.libId.includes(':') ? sym.libId.slice(sym.libId.indexOf(':') + 1) : sym.libId,
description: symbolProperty(sym, 'Description'),
keywords: symbolProperty(sym, 'ki_keywords'),
footprint: symbolProperty(sym, 'Footprint'),
isPower: sym.isPower,
isRoot: !sym.extends,
pinCount: libSymbolPinCount(sym),
unitCount: libSymbolUnitCount(sym),
chooserFields,
};
}
/**
* What the parser may leave out of a library that is only being read for its
* `LibTreeItem`s.
*
* A symbol library is almost entirely what a tree item never looks at: the
* body graphics and, inside each pin and property, the placement and text
* effects. Built whole, MCU_ST_STM32H7 (14.8 MB) is a 198 MB tree, and the
* preload parses four such libraries at once -- measured at 1.5 GB of renderer
* footprint on a project open, which is where a "Chrome ran out of memory" on
* a laptop came from. Pruned, `readSymbolLib` sees `(pin passive line)` and
* `(property "Key" "Value")` with nothing under them and reads exactly the
* fields `libTreeItem` projects: every reader it goes through defaults what
* is missing. `symbol` stays whole because a unit's pins are counted, and
* `extends`/`power` stay because inheritance is resolved before projection.
*/
export const LIB_TREE_PRUNE: PruneOptions = {
drop: new Set([
'polyline',
'rectangle',
'circle',
'arc',
'bezier',
'text',
'text_box',
'embedded_fonts',
'embedded_files',
]),
shallow: new Set(['pin', 'property']),
};
/**
* `SYMBOL_LIBRARY_ADAPTER::AsyncLoad`'s per-library task, from the file's text
* to the tree items: the one function the preload worker and its inline
* fallback both run. The result is the same list `readSymbolLib` on the full
* tree would give `libTreeItem`, at a fraction of the memory.
*/
export function readLibTreeItems(text: string): LibTreeItem[] {
return readSymbolLib(parse(text, LIB_TREE_PRUNE)).map(libTreeItem);
}
/**
* `LIB_SYMBOL::cacheSearchTerms` (lib_symbol.cpp:160-183) over a {@link LibTreeItem}: the library
* nickname, the name, the LIB_ID, each keyword, the keywords whole, the description and the
* footprint, at the weights upstream gives them. One list for the chooser's tree and the
* library browser alike.
*/
export function libTreeItemSearchTerms(aNickname: string, aItem: LibTreeItem): SearchTerm[] {
const keywords = aItem.keywords;
const terms = [
searchTerm(aNickname, 4),
searchTerm(aItem.name, 8, true),
searchTerm(`${aNickname}:${aItem.name}`, 16, true),
...keywords
.split(/\s+/)
.filter(Boolean)
.map((kw) => searchTerm(kw, 4)),
searchTerm(keywords, 1),
searchTerm(aItem.description, 1),
];
if (aItem.footprint) terms.push(searchTerm(aItem.footprint, 1));
return terms;
}
/**
* A {@link LibTreeItem} as the `LIB_TREE_ITEM` LIB_SYMBOL is: what SYMBOL_VIEWER_FRAME's
* ReCreateSymbolList asks a symbol for, for a library whose symbols the program keeps as items
* rather than parsed (a hosted one, see `loadedLibraries` in symbol_library_adapter.ts).
*/
export class LIB_TREE_ITEM_SYMBOL {
constructor(
private readonly m_nickname: string,
private readonly m_item: LibTreeItem,
) {}
GetName(): string {
return this.m_item.name;
}
GetSearchTerms(): SearchTerm[] {
return libTreeItemSearchTerms(this.m_nickname, this.m_item);
}
GetPinCount(): number {
return this.m_item.pinCount;
}
GetLibId(): LIB_ID {
return new LIB_ID(this.m_nickname, this.m_item.name);
}
IsPower(): boolean {
return this.m_item.isPower;
}
}