buildLibraryDocument function
The library document of catalog. Deterministic: handles ascend in
catalog order (a definition, its leaves, the next definition). Every leaf
is on layer 0 with BYBLOCK linetype, colour, lineweight and transparency
and no flag (K3 rule 14). The caller disposes the document.
Throws a component's ArgumentError for a value spec K2 refuses, and whatever a shape's payload throws (the document is then disposed).
Implementation
DraftDocument buildLibraryDocument(Catalog catalog) {
// Every component is constructed, and so validated, before the document
// exists: a value K2 refuses throws here and leaves nothing to dispose.
final library = LibraryComponent(kit: catalog.kit);
final symbols = [
for (final s in catalog.symbols)
SymbolComponent(
key: s.key,
version: s.version,
name: s.name,
category: s.category,
tags: s.tags,
attachTo: s.attachTo,
family: s.family,
retired: s.retired,
),
];
final units = [
for (final s in catalog.symbols)
if (s.unit case final unit?)
UnitComponent(
kind: unit.kind, capacity: unit.capacity, labelling: unit.labelling)
else
null,
];
final doc = DraftDocument.empty();
// A payload can still throw once the document exists (an empty closed
// polyline has no first point): the document is disposed, the error
// goes on.
try {
registerKitComponents(doc.components);
doc.header.units = DrawingUnits.millimeters;
final commands = <DraftCommand>[
SetComponentCommand<LibraryComponent>(doc.rootHandle, library),
];
for (var i = 0; i < catalog.symbols.length; i++) {
final s = catalog.symbols[i];
final def = doc.handleSeed.next();
commands
..add(AddDefinitionCommand(Definition(
handle: def,
name: s.id,
basePoint: Vector2(s.base.$1, s.base.$2),
children: const [],
)))
..add(SetComponentCommand<SymbolComponent>(def, symbols[i]));
final unit = units[i];
if (unit != null) {
commands.add(SetComponentCommand<UnitComponent>(def, unit));
}
for (final shape in s.shapes) {
commands.add(AddEntityCommand(
record: EntityRecord(
handle: doc.handleSeed.next(),
owner: def,
kind: _kindOf(shape),
layer: ReservedHandles.layerZero,
linetype: ReservedHandles.byBlockLinetype,
linetypeScale: 1.0,
geomIndex: 0,
color: const ByBlockColor(),
lineweight: kByBlock,
transparency: kByBlock,
flags: 0,
),
payload: _payloadOf(shape),
));
}
}
doc.commands.execute(CompoundCommand(commands, label: 'Symbol library'));
doc.commands.clearHistory();
return doc;
} catch (_) {
unawaited(doc.dispose());
rethrow;
}
}