Improve terminal node naming within building blocks to ensure no duplicates by adding a name of the nested component as a prefix

This commit is contained in:
Bane Stojkovic
2026-09-14 13:04:03 +02:00
parent 69bb77d307
commit 51698ef8af
5 changed files with 314 additions and 29 deletions
@@ -28,8 +28,12 @@ import java.awt.Stroke;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.diylc.components.AbstractComponent;
import org.diylc.components.AbstractTransparentComponent;
@@ -83,6 +87,7 @@ public class CompositeComponent extends AbstractTransparentComponent<String> {
// serialized (transient).
private transient int[] childOf;
private transient int[] pointOf;
private transient String[] nodeNameOf;
/**
* Required no-arg constructor, used reflectively by {@code ComponentProcessor} and XStream.
@@ -111,8 +116,77 @@ public class CompositeComponent extends AbstractTransparentComponent<String> {
idx++;
}
}
childOf = newChildOf;
nodeNameOf = buildNodeNames(newChildOf, newPointOf);
pointOf = newPointOf;
// assigned last, it is what marks the index as built
childOf = newChildOf;
}
/**
* Resolves the node names the composite exposes. A child's own node name is kept unchanged
* whenever it is unique, so the pads of a custom board read "VCC" rather than "Pad3.VCC" - the
* pad's component name is an arbitrary leftover from the project the block was saved in.
* Clashing names are resolved in two passes: pins of multi-point children are qualified with the
* child's name ("R1.1", "R2.1"), then whatever still clashes, typically several pads sharing a
* name, gets a numeric suffix in save order ("GND_1", "GND_2").
*
* <p>Only sticky, named points take part. Non-sticky points never become netlist nodes, and a
* board's corner points would otherwise force a rename on a pad that shares their default
* numeric name.
*/
private String[] buildNodeNames(int[] newChildOf, int[] newPointOf) {
String[] names = new String[newChildOf.length];
boolean[] terminal = new boolean[newChildOf.length];
for (int i = 0; i < names.length; i++) {
IDIYComponent<?> child = childComponents.get(newChildOf[i]);
names[i] = child.getControlPointNodeName(newPointOf[i]);
terminal[i] = names[i] != null && child.isControlPointSticky(newPointOf[i]);
}
Set<String> clashing = findClashingNames(names, terminal);
for (int i = 0; i < names.length; i++) {
IDIYComponent<?> child = childComponents.get(newChildOf[i]);
String childName = child.getName();
if (terminal[i] && clashing.contains(names[i]) && child.getControlPointCount() > 1
&& childName != null && !childName.trim().isEmpty()) {
names[i] = childName.trim() + "." + names[i];
}
}
clashing = findClashingNames(names, terminal);
if (clashing.isEmpty()) {
return names;
}
Set<String> taken = new HashSet<String>();
for (int i = 0; i < names.length; i++) {
if (terminal[i] && !clashing.contains(names[i])) {
taken.add(names[i]);
}
}
Map<String, Integer> nextSuffix = new HashMap<String, Integer>();
for (int i = 0; i < names.length; i++) {
if (terminal[i] && clashing.contains(names[i])) {
int suffix = nextSuffix.getOrDefault(names[i], 1);
while (taken.contains(names[i] + "_" + suffix)) {
suffix++;
}
nextSuffix.put(names[i], suffix + 1);
names[i] = names[i] + "_" + suffix;
taken.add(names[i]);
}
}
return names;
}
private static Set<String> findClashingNames(String[] names, boolean[] terminal) {
Set<String> seen = new HashSet<String>();
Set<String> clashing = new HashSet<String>();
for (int i = 0; i < names.length; i++) {
if (terminal[i] && !seen.add(names[i])) {
clashing.add(names[i]);
}
}
return clashing;
}
/**
@@ -179,7 +253,7 @@ public class CompositeComponent extends AbstractTransparentComponent<String> {
@Override
public String getControlPointNodeName(int index) {
buildIndexIfNeeded();
return childComponents.get(childOf[index]).getControlPointNodeName(pointOf[index]);
return nodeNameOf[index];
}
/**
@@ -164,10 +164,10 @@ public class BuildingBlockManager {
return clones;
}
// COMPOSITE mode: clone components keeping their saved names. Those names are namespaced
// under the composite's own name in the netlist (e.g. "ARD1.PH1.3"), so running them through
// createUniqueName against the whole project would produce meaningless drift and break
// netlist labels between two instances of the same block.
// COMPOSITE mode: clone components keeping their saved names. Those names surface in the
// composite's terminal names when pins clash (e.g. "BLK1.R1.1"), so running them through
// createUniqueName against the whole project would produce meaningless drift and make two
// instances of the same block resolve different netlist labels.
List<IDIYComponent<?>> childClones = new ArrayList<IDIYComponent<?>>();
for (IDIYComponent<?> c : components) {
try {
@@ -24,17 +24,20 @@ package org.diylc.components.composite;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.UUID;
import org.diylc.common.Percentage;
import org.diylc.core.IDIYComponent;
import org.diylc.netlist.Node;
import org.diylc.serialization.ProjectFileManager;
import org.diylc.testcomponents.OnePointTestComponent;
import org.diylc.testcomponents.TwoPointTestComponent;
import org.junit.Test;
@@ -55,6 +58,32 @@ public class CompositeComponentTest {
return composite;
}
private CompositeComponent customBoard(IDIYComponent<?>... children) {
CompositeComponent composite = new CompositeComponent();
composite.setName("BLK1");
composite.initBlockName("Custom Board");
composite.getChildComponents().addAll(Arrays.asList(children));
return composite;
}
private OnePointTestComponent pad(String name, String nodeName) {
return new OnePointTestComponent(name, nodeName, new Point2D.Double(0, 0));
}
// Stands in for a blank board: its corner points keep the default "1" and "2" node names but
// are not sticky.
private TwoPointTestComponent blankBoard() {
TwoPointTestComponent board = new TwoPointTestComponent("Board1", new Point2D.Double(0, 0),
new Point2D.Double(100, 100));
board.setSticky(0, false);
board.setSticky(1, false);
return board;
}
private TwoPointTestComponent twoPoint(String name) {
return new TwoPointTestComponent(name, new Point2D.Double(0, 0), new Point2D.Double(10, 0));
}
@Test
public void controlPointCountIsSumOverChildren() {
CompositeComponent composite = twoChildComposite();
@@ -103,18 +132,94 @@ public class CompositeComponentTest {
}
@Test
public void nodeNamingProducesHierarchicalNetlistLabels() {
// Design decision D3: Node.toString() should read "<composite>.<child>.<local point name>"
public void clashingPinsOfMultiPointChildrenAreQualifiedWithTheChildName() {
CompositeComponent composite = twoChildComposite();
Node r1FirstPoint = new Node(composite, 0);
Node r2FirstPoint = new Node(composite, 2);
Node r2SecondPoint = new Node(composite, 3);
assertEquals("BLK1.1", r1FirstPoint.toString());
assertEquals("BLK1.1", r2FirstPoint.toString());
assertEquals("R1.1", composite.getControlPointNodeName(0));
assertEquals("R1.2", composite.getControlPointNodeName(1));
assertEquals("BLK1.R2.1", new Node(composite, 2).toString());
// local point index must reset per child, not keep growing with the flat composite index
assertEquals("BLK1.2", r2SecondPoint.toString());
assertEquals("BLK1.R2.2", new Node(composite, 3).toString());
}
@Test
public void uniquePadNamesPassThroughWithoutThePadName() {
CompositeComponent composite =
customBoard(blankBoard(), pad("Pad3", "VCC"), pad("Pad7", "SDA"));
assertEquals("VCC", composite.getControlPointNodeName(2));
assertEquals("SDA", composite.getControlPointNodeName(3));
assertEquals("BLK1.VCC", new Node(composite, 2).toString());
}
@Test
public void nonStickyPointsDoNotForceARename() {
CompositeComponent composite = customBoard(blankBoard(), pad("Pad1", "1"));
assertEquals("1", composite.getControlPointNodeName(2));
}
@Test
public void padsSharingANameGetNumericSuffixesInSaveOrder() {
CompositeComponent composite = customBoard(blankBoard(), pad("Pad1", "GND"),
pad("Pad2", "VCC"), pad("Pad3", "GND"), pad("Pad4", "GND"));
assertEquals("GND_1", composite.getControlPointNodeName(2));
assertEquals("VCC", composite.getControlPointNodeName(3));
assertEquals("GND_2", composite.getControlPointNodeName(4));
assertEquals("GND_3", composite.getControlPointNodeName(5));
}
@Test
public void suffixesSkipNamesThatAreAlreadyTaken() {
CompositeComponent composite =
customBoard(pad("Pad1", "GND"), pad("Pad2", "GND_1"), pad("Pad3", "GND"));
assertEquals("GND_2", composite.getControlPointNodeName(0));
assertEquals("GND_1", composite.getControlPointNodeName(1));
assertEquals("GND_3", composite.getControlPointNodeName(2));
}
@Test
public void padClashingWithAPinOfAMultiPointChildKeepsItsName() {
CompositeComponent composite = customBoard(pad("Pad1", "1"), twoPoint("R1"));
assertEquals("1", composite.getControlPointNodeName(0));
assertEquals("R1.1", composite.getControlPointNodeName(1));
assertEquals("2", composite.getControlPointNodeName(2));
}
@Test
public void childrenSharingANameAreStillDistinguished() {
// renaming in the property editor does not enforce uniqueness, so a block can hold two "R1"s
CompositeComponent composite = customBoard(twoPoint("R1"), twoPoint("R1"));
assertEquals("R1.1_1", composite.getControlPointNodeName(0));
assertEquals("R1.2_1", composite.getControlPointNodeName(1));
assertEquals("R1.1_2", composite.getControlPointNodeName(2));
assertEquals("R1.2_2", composite.getControlPointNodeName(3));
}
@Test
public void unnamedPointsAreNotTerminals() {
CompositeComponent composite =
customBoard(pad("Pad1", null), pad("Pad2", null), pad("Pad3", "VCC"));
assertNull(composite.getControlPointNodeName(0));
assertNull(composite.getControlPointNodeName(1));
assertEquals("VCC", composite.getControlPointNodeName(2));
}
@Test
public void instancesOfTheSameBlockResolveIdenticalNames() throws Exception {
CompositeComponent original = customBoard(blankBoard(), pad("Pad1", "GND"),
pad("Pad2", "GND"), twoPoint("R1"), twoPoint("R2"));
CompositeComponent clone = (CompositeComponent) original.clone();
for (int i = 0; i < original.getControlPointCount(); i++) {
assertEquals(original.getControlPointNodeName(i), clone.getControlPointNodeName(i));
}
}
@Test
@@ -204,7 +309,7 @@ public class CompositeComponentTest {
assertEquals(original.getBlockName(), reloaded.getBlockName());
for (int i = 0; i < original.getControlPointCount(); i++)
assertEquals(original.getControlPoint(i), reloaded.getControlPoint(i));
assertEquals("BLK1.2", new Node(reloaded, 3).toString());
assertEquals("BLK1.R2.2", new Node(reloaded, 3).toString());
}
@Test
@@ -0,0 +1,107 @@
/*
DIY Layout Creator (DIYLC).
Copyright (c) 2009-2025 held jointly by the individual authors.
This file is part of DIYLC.
DIYLC is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
DIYLC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with DIYLC. If not, see <http://www.gnu.org/licenses/>.
*/
package org.diylc.testcomponents;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import org.diylc.components.AbstractComponent;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.ComponentDescriptor;
/**
* Minimal single-point, sticky component with a settable node name, standing in for a solder pad
* or turret when testing how {@code CompositeComponent} resolves the terminal names of a custom
* board. A {@code null} node name marks the point as not being a netlist node, like a pad whose
* Node Name is left blank.
*/
@ComponentDescriptor(name = "One Point Test", category = "Test", author = "Test",
description = "test", instanceNamePrefix = "OP", zOrder = IDIYComponent.COMPONENT)
public class OnePointTestComponent extends AbstractComponent<Void> {
private static final long serialVersionUID = 1L;
private Point2D point;
private String nodeName;
public OnePointTestComponent() {
this("", null, new Point2D.Double(0, 0));
}
public OnePointTestComponent(String name, String nodeName, Point2D point) {
setName(name);
this.nodeName = nodeName;
this.point = point;
}
@Override
public int getControlPointCount() {
return 1;
}
@Override
public Point2D getControlPoint(int index) {
return point;
}
@Override
public void setControlPoint(Point2D point, int index) {
this.point = point;
}
@Override
public boolean isControlPointSticky(int index) {
return true;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.ALWAYS;
}
@Override
public String getControlPointNodeName(int index) {
return nodeName;
}
@Override
public Void getValue() {
return null;
}
@Override
public void setValue(Void value) {
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode,
Project project, IDrawingObserver drawingObserver) {
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
}
}
+12 -13
View File
@@ -26,7 +26,7 @@ click; group mode costs one extra click.
|---|---|---|---|
| D1 | Where child definitions live | Embedded in the instance, serialized into the `.diy` file | Projects stay portable; a file opens correctly on a machine that does not have the block in its local config. Blocks in config remain the *template*, not a live dependency. |
| D2 | Which control points are exposed | All of them, delegated straight through to children | No curation UI needed, and `isControlPointSticky` / `getControlPointVisibilityPolicy` come along for free with correct per-child semantics. |
| D3 | Terminal naming | `getSectionNames(i)` returns the child's name; `getControlPointNodeName(i)` returns the child's node name | `Node.toString()` already renders `component.getName() + "." + section + "." + nodeName`, so a netlist node reads `ARD1.PH1.3` with no changes to the netlist code. |
| D3 | Terminal naming | A child's node name is exposed unchanged when it is unique within the composite. Clashes are resolved by qualifying pins of multi-point children with the child's name (`R1.1`), then numbering whatever still clashes in save order (`GND_1`, `GND_2`) | Blocks are also used to build custom maker boards from a blank board and solder pads, where the pad's Node Name is the terminal name and its component name (`Pad3`) is an arbitrary leftover of the project the block was saved in. Children are frozen (D8), so every instance of a block resolves identical names. `Node.toString()` prefixes the composite's name, so a netlist node reads `BLK1.VCC` or `BLK1.R1.1`. |
| D4 | Geometry | Rigid — `canPointMoveFreely(i)` returns `false` for every index | This is already a first-class concept used by ~60 components (`DIL_IC`, `Breadboard`, `TubeSocket`…). No new plumbing. |
| D5 | Type identity | One shared `ComponentType`; the instance carries a `blockName` field, and the handful of type-name consumers prefer it | `ComponentProcessor` caches `ComponentType` per Java class, so per-block types would mean changing the cache key of a widely used singleton. The field approach has a much smaller blast radius. |
| D6 | Electrical modelling | The composite is **not** `IContinuity` and **not** `ISwitch` | A composite is a footprint that exposes terminals, not a circuit model. Internal point-to-point continuity and internal switching are explicitly out of scope. |
@@ -67,10 +67,10 @@ components by translating *every* control point by the same delta via
child. Rigidity is enforced by `canPointMoveFreely`, never by `setControlPoint`
refusing a write.
**Node naming.** `Node.getDisplayName()` prefixes the node name with
`getSectionNames(pointIndex)[0]` when there is exactly one section, and
`Node.toString()` prefixes that with the component name. Returning the child's
name as the section gives hierarchical netlist labels for free.
**Node naming.** `Node.toString()` prefixes the node name with the component
name, so whatever the composite returns from `getControlPointNodeName` reads as
`BLK1.<name>` in the netlist with no changes to the netlist code. Only resolving
clashes between children's names is new (D3).
Three things do *not* come for free and are the substance of the work: type
identity (D5), palette visibility (§4.2), and a correct deep `clone()` (§7).
@@ -131,8 +131,7 @@ deserialization, which the lazy getter handles.
| `isControlPointSticky(i)` | Delegate |
| `canControlPointOverlap(i)` | Delegate |
| `getControlPointVisibilityPolicy(i)` | Delegate |
| `getControlPointNodeName(i)` | Child's node name, prefixed with the child's own section name when it has exactly one |
| `getSectionNames(i)` | `new String[] { child.getName() }` |
| `getControlPointNodeName(i)` | Resolved once alongside the index arrays (D3). Only sticky, named points take part in clash detection, so a board's non-sticky corner points never force a pad to be renamed |
| `canPointMoveFreely(i)` | `false` (D4) |
| `createdIn(project)` | Forward to every child |
@@ -202,10 +201,10 @@ left behind.
- `GROUP` — exactly today's behaviour.
- `COMPOSITE` — clone the stored components with fresh UUIDs but **keep their
saved names unchanged**. Child names are namespaced under the composite's name
saved names unchanged**. Child names surface in terminal names when pins clash
(D3), so running them through `createUniqueName` against the project would
produce meaningless drift (`R1` becoming `R37`) and break netlist labels
between two instances of the same block. Then wrap them in a
produce meaningless drift (`R1` becoming `R37`) and make two instances of the
same block resolve different netlist labels. Then wrap them in a
`CompositeComponent`, set `blockName`, and give the composite itself a
project-unique name via `createUniqueName`.
@@ -312,7 +311,7 @@ selections.
**Naming collisions.** Two instances of the same block deliberately carry
identically named children (§4.4). Netlist labels stay unique because they are
prefixed with the composite's own name (`ARD1.PH1.3` vs `ARD2.PH1.3`). Any code
prefixed with the composite's own name (`ARD1.R1.1` vs `ARD2.R1.1`). Any code
that assumes component names are globally unique across the project would be
affected — none is known, but worth watching.
@@ -320,8 +319,8 @@ affected — none is known, but worth watching.
- **Unit** — point count equals the sum over children; `getControlPoint(i)`
tracks the child after the child moves; `canPointMoveFreely` is false for
every index; `getSectionNames`/`getControlPointNodeName` produce
`ARD1.PH1.3` through `Node.toString()`.
every index; `getControlPointNodeName` passes unique names through, qualifies
clashing pins of multi-point children and numbers the remaining clashes (D3).
- **Clone isolation** — clone a composite, move the clone, assert the original's
points did not move.
- **Round trip** — save a project containing a composite, reload it, assert the