Files
vibemake-pcb-studio/eeschema/project_sym_lib_table.ts
T
likang 7e01147566
CI / typecheck + test + build (push) Has been cancelled
Initial commit: import VibeMake PCB Studio
2026-11-03 11:20:08 +08:00

241 lines
9.6 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.
/**
* The project's symbol library table. Counterpart: `eeschema/symbol_lib_table.cpp`
* (SYMBOL_LIB_TABLE / LIB_TABLE_ROW), the `sym-lib-table` file that maps a
* library *nickname* to a `.kicad_sym` file.
*
* SYMBOL_LIB_TABLE resolves a LIB_ID's nickname through the **project** table
* first and the global one after, so a project that ships its own symbols — as
* most of KiCad's demos do — registers them here and nowhere else:
*
* (sym_lib_table
* (lib (name "kit-dev-coldfire-xilinx_5213")(type "KiCad")
* (uri "${KIPRJMOD}/kit-dev-coldfire-xilinx_5213.kicad_sym")…))
*
* Without reading it, every symbol those projects place resolves to nothing and
* TestLibSymbolIssues reports the library as unconfigured once per symbol.
* The hosted libraries stand in for the global table, as they do for footprints.
*/
import { parse } from '@ziroeda/sexpr';
import { readSymbolLib } from './sch_io/sexpr/read-schematic.js';
import type { LibSymbol } from './types.js';
import { LIBRARY_TABLE_TYPE } from '@ziroeda/common/libraries/library_table.js';
import {
type ADD_LIBRARY_RESULT,
libraryTableOf,
parseFpLibTable,
type FpLibRow,
} from '@ziroeda/common/fp_lib_table.js';
import { findProjectFile as findProjectFileByUri } from '@ziroeda/common/project_paths.js';
/** A project file as the editor holds it. */
export interface ProjectFile {
name: string;
text: string;
}
/** Read the project's `sym-lib-table`, if it has one. The row grammar is the
* same `(lib (name …)(type …)(uri …))` as the footprint table's. */
export function projectSymLibTable(files: readonly ProjectFile[]): FpLibRow[] {
const file = files.find((f) => /(^|\/)sym-lib-table$/i.test(f.name.replace(/\\/g, '/')));
return file ? parseFpLibTable(file.text) : [];
}
/**
* The symbols each project-registered library holds.
*
* A row's URI is resolved the way LIB_TABLE_ROW does for a project table: only
* `${KIPRJMOD}` (and its legacy `$(KIPRJMOD)` spelling) is expanded, and it
* means "next to the project", so the file is matched inside the project by
* path. A row whose file is absent or unreadable is reported through
* `unloaded`, which is what `IsLibraryLoaded` false plus `GetFullURI` gives
* TestLibSymbolIssues.
*/
export function projectSymbolLibraries(files: readonly ProjectFile[]): {
/** nickname -> the symbol names it holds (the symbol library table half). */
symbolLibs: Map<string, Set<string>>;
/** "nickname:name" -> the library's copy, for the mismatch comparison. */
librarySymbols: Map<string, LibSymbol>;
/** nickname -> URI, for a registered row whose file would not load. */
unloaded: Map<string, string>;
} {
const symbolLibs = new Map<string, Set<string>>();
const librarySymbols = new Map<string, LibSymbol>();
const unloaded = new Map<string, string>();
for (const row of projectSymLibTable(files)) {
if (row.disabled) continue;
const file = findProjectFile(files, row.uri);
if (!file) {
unloaded.set(row.name, row.uri);
continue;
}
let symbols: LibSymbol[];
try {
symbols = readSymbolLib(parse(file.text));
} catch {
unloaded.set(row.name, row.uri);
continue;
}
const names = new Set<string>();
for (const sym of symbols) {
// A LIB_SYMBOL's id inside a .kicad_sym is its bare name; the nickname
// comes from the row, never from the file.
const name = sym.libId.includes(':')
? sym.libId.slice(sym.libId.indexOf(':') + 1)
: sym.libId;
names.add(name);
librarySymbols.set(`${row.name}:${name}`, sym);
}
symbolLibs.set(row.name, names);
}
return { symbolLibs, librarySymbols, unloaded };
}
/** A table row paired with the project file its URI resolves to. */
export interface ResolvedSymLib {
row: FpLibRow;
file: ProjectFile;
}
/**
* Every row of the project table that resolves to a file, disabled ones
* included — the caller decides what a disabled row means, as upstream does
* (`HasLibrary( nickname, true )` is a separate question from `FindRowByURI`).
* This is the *only* list of the project's symbol libraries: a `.kicad_sym` no
* row points at is a file, not a library.
*/
export function resolvedProjectSymLibs(files: readonly ProjectFile[]): ResolvedSymLib[] {
const out: ResolvedSymLib[] = [];
for (const row of projectSymLibTable(files)) {
const file = findProjectFile(files, row.uri);
if (file) out.push({ row, file });
}
return out;
}
/**
* SYMBOL_LIBRARY_ADAPTER::FindRowByURI, the lookup MAIL_LIB_EDIT does when the
* project manager asks the symbol editor to open a `.kicad_sym`: which table row
* points at this file? None means the file is not a library, and upstream says
* so rather than opening it anyway.
*/
export function findSymLibRowByUri(
files: readonly ProjectFile[],
path: string,
): FpLibRow | undefined {
const wanted = path.replace(/\\/g, '/').toLowerCase();
return resolvedProjectSymLibs(files).find(
({ file }) => file.name.replace(/\\/g, '/').toLowerCase() === wanted,
)?.row;
}
/** Write the rows back as a `sym-lib-table` file (LIBRARY_TABLE::Save's text). */
export function serializeSymLibTable(rows: readonly FpLibRow[]): string {
return libraryTableOf(rows, LIBRARY_TABLE_TYPE.SYMBOL).FormatForSave();
}
/** Path of the project's `sym-lib-table`, existing or to be created (it sits
* next to the `.kicad_pro`). */
export function projectSymLibTablePath(files: readonly ProjectFile[]): string {
const existing = files.find((f) => /(^|\/)sym-lib-table$/i.test(f.name.replace(/\\/g, '/')));
if (existing) return existing.name;
const pro = files.find((f) => /\.kicad_pro$/i.test(f.name))?.name.replace(/\\/g, '/');
const dir = pro?.includes('/') ? pro.slice(0, pro.lastIndexOf('/') + 1) : '';
return `${dir}sym-lib-table`;
}
/** The `.kicad_sym` file a row's URI points at, without the extension
* ("${KIPRJMOD}/proj.kicad_sym" -> "proj"). */
export function rowSymLibName(row: FpLibRow): string {
const base = row.uri.replace(/\\/g, '/').split('/').pop() ?? '';
return /\.kicad_sym$/i.test(base) ? base.replace(/\.kicad_sym$/i, '') : '';
}
/**
* The `.kicad_sym` files in the project, with the nickname (if any) each is
* registered under. This is what "Add Existing" offers — listing a file is not
* the same as resolving one, and an unregistered file stays unusable until a row
* points at it.
*/
export function projectSymbolFiles(
files: readonly ProjectFile[],
rows: readonly FpLibRow[],
): { file: string; path: string; registeredAs: string }[] {
const seen = new Map<string, string>();
for (const f of files) {
const norm = f.name.replace(/\\/g, '/');
if (!/\.kicad_sym$/i.test(norm)) continue;
const base = (norm.split('/').pop() ?? '').replace(/\.kicad_sym$/i, '');
if (base && !seen.has(base)) seen.set(base, norm);
}
return [...seen].map(([file, path]) => ({
file,
path,
registeredAs:
rows.find((r) => rowSymLibName(r).toLowerCase() === file.toLowerCase())?.name ?? '',
}));
}
/**
* The `sym-lib-table` also anchors `${KIPRJMOD}`, for a "project" that is only
* a library folder with no `.kicad_pro` in it. The expansion itself is
* `common/project_paths.ts` - one module, because upstream has one
* `ExpandEnvVarSubstitutions`.
*/
const SYM_LIB_TABLE_ANCHOR = /(^|\/)sym-lib-table$/i;
function findProjectFile(files: readonly ProjectFile[], uri: string): ProjectFile | undefined {
return findProjectFileByUri(files, uri, SYM_LIB_TABLE_ANCHOR);
}
/**
* `SYMBOL_EDIT_FRAME::AddLibraryFile` (symbol_edit_frame.cpp:1180) then
* `SYMBOL_LIBRARY_MANAGER::addLibrary` (symbol_library_manager.cpp:748), for a `.kicad_sym` read
* off the computer: the file copied into the project beside the `sym-lib-table`, and the project
* table given a KiCad row for it at `${KIPRJMOD}/<file>`. The nickname is the file's name less
* the extension (`fn.GetName()`), refused as upstream refuses it when any table already has it
* ("Library '%s' already exists.") - \a aOtherNicknames are the global table's.
*
* Web delta: upstream points the row at the file where it lies, which a page cannot, so the file
* is copied - and refused rather than written over a different file of the same name.
*/
export function AddSymbolLibraryToProject(
aProjectFiles: readonly ProjectFile[],
aFile: { name: string; text: string },
aOtherNicknames: readonly string[] = [],
): ADD_LIBRARY_RESULT {
const leaf = aFile.name.replace(/\\/g, '/').split('/').pop() ?? '';
const nickname = leaf.replace(/\.kicad_sym$/i, '');
if (!/\.kicad_sym$/i.test(leaf) || nickname === '')
return { ok: false, error: `'${leaf}' is not a KiCad symbol library (*.kicad_sym).` };
const rows = projectSymLibTable(aProjectFiles);
if ([...rows.map((r) => r.name), ...aOtherNicknames].includes(nickname))
return { ok: false, error: `Library '${nickname}' already exists.` };
const tablePath = projectSymLibTablePath(aProjectFiles);
const name = `${tablePath.slice(0, tablePath.lastIndexOf('/') + 1)}${leaf}`;
const existing = aProjectFiles.find((f) => f.name.toLowerCase() === name.toLowerCase());
if (existing && existing.text !== aFile.text)
return { ok: false, error: `The project already has a different '${leaf}'.` };
const table = serializeSymLibTable([
...rows,
{ name: nickname, type: 'KiCad', uri: `\${KIPRJMOD}/${leaf}`, options: '', descr: '' },
]);
return {
ok: true,
nickname,
files: [...(existing ? [] : [{ name, text: aFile.text }]), { name: tablePath, text: table }],
};
}