From 42e0d83403ff94e32b712dc5ce8b3dd78f0671b3 Mon Sep 17 00:00:00 2001 From: Eyck Jentzsch Date: Fri, 20 Nov 2026 21:08:27 +0100 Subject: [PATCH] added combined bit vectors --- README.md | 22 ++ .../src/asciidoc/Reference.adoc | 21 ++ .../database/ui/BitVectorComposition.java | 44 ++++ .../scviewer/database/ui/BitWaveform.java | 3 + .../ui/swt/internal/WaveformView.java | 4 +- .../database/CombinedBitVectorWaveform.java | 213 ++++++++++++++++++ .../minres/scviewer/database/IWaveform.java | 3 + .../toc.xml | 3 +- .../Application.e4xmi | 4 + .../handlers/CombineBitsHandler.java | 114 ++++++++++ .../internal/util/ViewerSettings.java | 100 +++++++- .../e4/application/parts/WaveformViewer.java | 87 ++++++- .../database/test/CombinedBitVectorTest.java | 144 ++++++++++++ .../handlers/CommandHandlersTest.java | 33 +++ .../parts/BitVectorExpansionTest.java | 2 +- .../parts/CombinedVectorSettingsTest.java | 136 +++++++++++ .../application/parts/WaveformScrollTest.java | 147 ++++++++++++ 17 files changed, 1066 insertions(+), 14 deletions(-) create mode 100644 plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitVectorComposition.java create mode 100644 plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/CombinedBitVectorWaveform.java create mode 100644 plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/handlers/CombineBitsHandler.java create mode 100644 tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/CombinedBitVectorTest.java create mode 100644 tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/CombinedVectorSettingsTest.java diff --git a/README.md b/README.md index d539e7c1..7f67914d 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,28 @@ bit 0 denoting the least significant position. Click again to collapse the bits. Bit tracks show binary values, including unknown (`x`) and high-impedance (`z`) states. Settings files preserve the expansion state and individual bit tracks. +Combining single bits +===================== + +Select at least two single-bit signal tracks, including individual bits expanded +from buses, and choose **Combine bits…** from the Edit menu or the track context +menu. Enter a vector name and use **Move up** / **Move down** to arrange its bits. +The dialog shows the destination bit index; the top entry becomes the most +significant bit. The default order follows the tracks' display order. + +The new bus is created at the top level after the last selected bit in display +order. For a bit inside a group or expanded bus, it appears after that bit's +top-level container. The source tracks remain available. The new bus supports +normal value formats and bit expansion. Inputs retain `0`, `1`, `x`, and `z`; an +input without a sample yet contributes `x`. Changes at the same timestamp are +combined into one value, and unchanged values do not create extra transitions. + +Settings files preserve the bus definition, bit order, name, and expansion state. +Combining bits from another combined vector resolves them to the original recorded +signals. Removing a source track from the view does not remove its recorded data +or invalidate the bus. If a recording or source bit is missing when settings are +loaded, the affected bus is skipped and reported while other tracks are restored. + Embedded Help ============= diff --git a/doc/com.minres.scviewer.doc/src/asciidoc/Reference.adoc b/doc/com.minres.scviewer.doc/src/asciidoc/Reference.adoc index a6e697de..5f33a678 100644 --- a/doc/com.minres.scviewer.doc/src/asciidoc/Reference.adoc +++ b/doc/com.minres.scviewer.doc/src/asciidoc/Reference.adoc @@ -12,6 +12,27 @@ bit 0 denoting the least significant position. Click again to collapse the bits. Bit tracks show binary values, including unknown (`x`) and high-impedance (`z`) states. Settings files preserve the expansion state and individual bit tracks. +=== Combining single bits + +Select at least two single-bit signal tracks and choose *Combine bits…* from the +Edit menu or the track context menu. Bits expanded from existing buses can also +be selected. Name the new vector and reorder the inputs with *Move up* and +*Move down*. The displayed destination indices run from the most significant bit +at the top to bit 0 at the bottom. The initial order follows the waveform list. + +The combined bus is created at the top level after the last selected bit in +display order. If that bit is inside a group or expanded bus, the new bus appears +after its top-level container. The source tracks remain visible, and the combined bus supports normal value +formats and expansion. Unknown and high-impedance values are preserved. An input +without an initial sample contributes `x`. Simultaneous changes produce one +combined value; unchanged values do not produce extra transitions. + +Saved settings retain the composition, bit order, name, and expansion state. +Source references use the original recorded signals, including when combining +bits from another combined vector. Removing a track from the view does not +invalidate its data. Missing recordings or source bits cause the affected bus +to be skipped and reported when loading settings; other tracks are restored. + [#_keybindings] === Key Shortcuts diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitVectorComposition.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitVectorComposition.java new file mode 100644 index 00000000..36d499b7 --- /dev/null +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitVectorComposition.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2026 MINRES Technologies GmbH and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * MINRES Technologies GmbH - initial API and implementation + *******************************************************************************/ +package com.minres.scviewer.database.ui; + +import java.util.List; +import com.minres.scviewer.database.BitVector; +import com.minres.scviewer.database.CombinedBitVectorWaveform.SourceBit; +import com.minres.scviewer.database.EventEntry; +import com.minres.scviewer.database.WaveformType; + +/** Selection and source normalization shared by the combine action and viewer. */ +public final class BitVectorComposition { + private BitVectorComposition() { } + + public static boolean isSingleBit(TrackEntry track) { + if (track.waveform == null || track.waveform.getType() != WaveformType.SIGNAL + || track.waveform.getWidth() != 1) return false; + EventEntry first = track.waveform.getEvents().firstEntry(); + return first == null || (first.events != null && first.events.length > 0 + && first.events[first.events.length - 1] instanceof BitVector); + } + + public static List selectedBits(List roots, List selection) { + List ordered = TrackEntry.visibleTracks(roots).stream() + .filter(track -> selection.stream().anyMatch(selected -> selected == track)).toList(); + return ordered.size() >= 2 && ordered.size() == selection.size() && ordered.stream().allMatch(BitVectorComposition::isSingleBit) + ? ordered : List.of(); + } + + public static List sources(List tracks) { + if (tracks.size() < 2 || !tracks.stream().allMatch(BitVectorComposition::isSingleBit)) + throw new IllegalArgumentException("Select at least two single-bit signals"); + return tracks.stream().map(track -> track.waveform instanceof BitWaveform bit + ? new SourceBit(bit.getSource(), bit.getBitIndex()) : new SourceBit(track.waveform, 0)).toList(); + } +} diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitWaveform.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitWaveform.java index 50ef334c..30dc1b1b 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitWaveform.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitWaveform.java @@ -38,6 +38,9 @@ public final class BitWaveform extends HierNode implements IWaveform { } @Override public String getFullName() { return source.getFullName() + getName(); } + @Override public String getDisplayName() { return source.getDisplayName() + getName(); } + public IWaveform getSource() { return source; } + public int getBitIndex() { return bit; } @Override public DirectionType getDirection() { return source.getDirection(); } @Override public long getId() { return source.getId(); } @Override public WaveformType getType() { return WaveformType.SIGNAL; } diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/WaveformView.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/WaveformView.java index 8c1d5f52..4856c8b5 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/WaveformView.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/WaveformView.java @@ -648,7 +648,7 @@ public class WaveformView implements IWaveformView { for (TrackEntry entry : TrackEntry.visibleTracks(streams)) { addPainter(even, entry); trackVerticalOffset.put(tracksVerticalHeight, entry); - tl.setText(entry.waveform.getFullName()); + tl.setText(entry.waveform.getDisplayName()); nameMaxWidth = Math.max(nameMaxWidth, tl.getBounds().width + nameIndent(entry) + (entry.hierState == HierState.NONE && nameIndent(entry) == 0 ? 5 : 18)); tracksVerticalHeight += entry.height; @@ -1261,7 +1261,7 @@ public class WaveformView implements IWaveformView { protected void drawName(GC gc, Rectangle subArea, Integer firstKey, TrackEntry entry) { IWaveform w = entry.waveform; subArea.height = w.getRowCount() * styleProvider.getTrackHeight(); - drawTextFormat(gc, subArea, firstKey, w.getFullName(), entry.selected, entry.hierState, nameIndent(entry)); + drawTextFormat(gc, subArea, firstKey, w.getDisplayName(), entry.selected, entry.hierState, nameIndent(entry)); } protected void drawValue(GC gc, Rectangle subArea, Integer yOffset, String value, boolean highlite) { diff --git a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/CombinedBitVectorWaveform.java b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/CombinedBitVectorWaveform.java new file mode 100644 index 00000000..f904119a --- /dev/null +++ b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/CombinedBitVectorWaveform.java @@ -0,0 +1,213 @@ +/******************************************************************************* + * Copyright (c) 2015-2026 MINRES Technologies GmbH and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * MINRES Technologies GmbH - initial API and implementation + *******************************************************************************/ +package com.minres.scviewer.database; + +import java.util.AbstractCollection; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.UUID; + +/** An immutable composition of recorded bits, listed from MSB to LSB. + * Recording event lists must be immutable after loading. Range views merge lazily; + * only a bounded set of sampled values is cached, never the entire merged timeline. + */ +public final class CombinedBitVectorWaveform extends HierNode implements IWaveform { + public record SourceBit(IWaveform waveform, int bit) { + public SourceBit { + if (waveform == null || waveform.getType() != WaveformType.SIGNAL + || bit < 0 || bit >= waveform.getWidth()) + throw new IllegalArgumentException("Invalid source bit"); + } + } + + private final String identifier; + private final List sources; + private final LazyValue> events = new LazyValue<>(); + private final Map samples = new LinkedHashMap<>(32, .75f, true) { + @Override protected boolean removeEldestEntry(Map.Entry entry) { return size() > 256; } + }; + private final IEventList timeline = new Timeline(0L, true, -1L, false); + private record Seek(long time, boolean forward, boolean inclusive, long limit) { } + private final Map positions = new LinkedHashMap<>(32, .75f, true) { + @Override protected boolean removeEldestEntry(Map.Entry entry) { return size() > 256; } + }; + + public CombinedBitVectorWaveform(String name, List sources) { + this("@combined:" + UUID.randomUUID(), name, sources); + } + + public CombinedBitVectorWaveform(String identifier, String name, List sources) { + super(name); + if (identifier == null || !identifier.startsWith("@combined:") || identifier.length() <= 10 + || name == null || name.isBlank() || sources == null || sources.size() < 2) + throw new IllegalArgumentException("A combined vector needs an identity, a name and at least two bits"); + this.identifier = identifier; + List normalized = new ArrayList<>(); + for (SourceBit input : sources) { + while (input.waveform() instanceof CombinedBitVectorWaveform combined) + input = combined.sources.get(combined.getWidth() - 1 - input.bit()); + normalized.add(input); + } + this.sources = List.copyOf(normalized); + } + + public List getSources() { return sources; } + @Override public String getFullName() { return identifier; } + @Override public String getDisplayName() { return getName(); } + @Override public DirectionType getDirection() { return DirectionType.IMPLICIT; } + @Override public long getId() { return identifier.hashCode(); } + @Override public boolean isSame(IWaveform other) { + return other instanceof CombinedBitVectorWaveform combined && identifier.equals(combined.identifier); + } + @Override public WaveformType getType() { return WaveformType.SIGNAL; } + @Override public String getKind() { return "combined bitvector"; } + @Override public int getWidth() { return sources.size(); } + @Override public int getRowCount() { return 1; } + @Override public IEventList getEvents() { return timeline; } + @Override public IEvent[] getEventsAtTime(long time) { return timeline.get(time); } + @Override public IEvent[] getEventsBeforeTime(long time) { + EventEntry entry = timeline.floorEntry(time); + return entry == null ? new IEvent[0] : entry.events; + } + + private List inputs() { + return events.get(() -> sources.stream().map(bit -> bit.waveform().getEvents()).toList()); + } + + private BitValue[] sample(long time) { + synchronized (samples) { + BitValue[] cached = samples.get(time); + if (cached != null) return cached; + } + BitValue[] value = new BitValue[getWidth()]; + for (int i = 0; i < value.length; i++) { + EventEntry entry = inputs().get(i).floorEntry(time); + value[i] = BitValue.X; + if (entry != null && entry.events != null && entry.events.length > 0) { + IEvent event = entry.events[entry.events.length - 1]; + if (!(event instanceof BitVector vector)) + throw new IllegalArgumentException("Source is not a bit signal: " + sources.get(i).waveform().getFullName()); + value[i] = vector.getValue(sources.get(i).bit()); + } + } + synchronized (samples) { samples.put(time, value); } + return value; + } + + /** Find the next/previous timestamp in the union, before suppressing unchanged samples. */ + private Long candidate(long time, boolean forward, boolean inclusive) { + Long result = null; + for (IEventList input : inputs()) { + EventEntry entry = forward ? (inclusive ? input.ceilingEntry(time) : input.higherEntry(time)) + : (inclusive ? input.floorEntry(time) : input.lowerEntry(time)); + if (entry != null && (result == null || (forward + ? Long.compareUnsigned(entry.timestamp, result) < 0 + : Long.compareUnsigned(entry.timestamp, result) > 0))) result = entry.timestamp; + } + return result; + } + + private boolean changed(long time) { + Long previous = candidate(time, false, false); + return previous == null || !Arrays.equals(sample(time), sample(previous)); + } + + private Long seek(long time, boolean forward, boolean inclusive, long limit) { + Seek query = new Seek(time, forward, inclusive, limit); + synchronized (positions) { + if (positions.containsKey(query)) return positions.get(query); + } + Long next = candidate(time, forward, inclusive); + while (next != null) { + if (forward ? Long.compareUnsigned(next, limit) > 0 : Long.compareUnsigned(next, limit) < 0) { + next = null; + break; + } + if (changed(next)) break; + if (Thread.currentThread().isInterrupted()) throw new java.util.concurrent.CancellationException(); + next = candidate(next, forward, false); + } + synchronized (positions) { positions.put(query, next); } + return next; + } + + private EventEntry event(long time) { + BitVector vector = new BitVector(getWidth()); + BitValue[] value = sample(time); + for (int i = 0; i < value.length; i++) vector.setValue(value.length - i - 1, value[i]); + return new EventEntry(time, new IEvent[]{vector}); + } + + private final class Timeline implements IEventList { + private final long low, high; + private final boolean includeLow, empty; + Timeline(long low, boolean includeLow, long high, boolean empty) { + this.low = low; this.high = high; this.includeLow = includeLow; this.empty = empty; + } + private EventEntry find(long time, boolean forward, boolean inclusive) { + if (empty) return null; + if (forward && Long.compareUnsigned(time, low) < 0) { time = low; inclusive = includeLow; } + else if (forward && time == low) inclusive &= includeLow; + if (!forward && Long.compareUnsigned(time, high) > 0) { time = high; inclusive = true; } + Long next = seek(time, forward, inclusive, forward ? high : low); + return next == null || Long.compareUnsigned(next, low) < 0 || (!includeLow && next == low) + || Long.compareUnsigned(next, high) > 0 ? null : event(next); + } + @Override public EventEntry firstEntry() { return find(low, true, includeLow); } + @Override public EventEntry lastEntry() { return find(high, false, true); } + @Override public EventEntry floorEntry(long key) { return find(key, false, true); } + @Override public EventEntry ceilingEntry(long key) { return find(key, true, true); } + @Override public EventEntry lowerEntry(long key) { return find(key, false, false); } + @Override public EventEntry higherEntry(long key) { return find(key, true, false); } + @Override public boolean isEmpty() { return firstEntry() == null; } + @Override public int size() { int size = 0; for (EventEntry ignored : this) size++; return size; } + @Override public long firstKey() { + EventEntry entry = firstEntry(); if (entry == null) throw new NoSuchElementException(); return entry.timestamp; + } + @Override public long lastKey() { + EventEntry entry = lastEntry(); if (entry == null) throw new NoSuchElementException(); return entry.timestamp; + } + @Override public IEvent[] get(long key) { + EventEntry entry = ceilingEntry(key); return entry != null && entry.timestamp == key ? entry.events : null; + } + @Override public boolean containsKey(long key) { return get(key) != null; } + @Override public void put(long key, IEvent value) { throw new UnsupportedOperationException("Read-only combined vector"); } + @Override public IEventList subMap(long from, boolean inclusive, long to) { + if (Long.compareUnsigned(from, to) > 0) throw new IllegalArgumentException("Reversed time range"); + long lower = Long.compareUnsigned(from, low) > 0 ? from : low; + boolean include = (lower != from || inclusive) && (lower != low || includeLow); + long upper = Long.compareUnsigned(to, high) < 0 ? to : high; + return new Timeline(lower, include, upper, empty || Long.compareUnsigned(lower, upper) > 0); + } + @Override public Iterator iterator() { + return new Iterator<>() { + EventEntry next = firstEntry(); + @Override public boolean hasNext() { return next != null; } + @Override public EventEntry next() { + if (next == null) throw new NoSuchElementException(); + EventEntry result = next; next = higherEntry(result.timestamp); return result; + } + }; + } + @Override public Collection entrySet() { + return new AbstractCollection<>() { + @Override public int size() { return Timeline.this.size(); } + @Override public Iterator iterator() { return Timeline.this.iterator(); } + }; + } + } +} diff --git a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/IWaveform.java b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/IWaveform.java index 0e4f8a81..b9a2d603 100644 --- a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/IWaveform.java +++ b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/IWaveform.java @@ -19,6 +19,9 @@ package com.minres.scviewer.database; */ public interface IWaveform extends IHierNode { + /** User-facing label; derived waveforms may have a separate persistent identity. */ + default String getDisplayName() { return getFullName(); } + public DirectionType getDirection(); /** * Gets the id. diff --git a/plugins/com.minres.scviewer.e4.application.help/toc.xml b/plugins/com.minres.scviewer.e4.application.help/toc.xml index 58bf5ba8..dc611e1b 100644 --- a/plugins/com.minres.scviewer.e4.application.help/toc.xml +++ b/plugins/com.minres.scviewer.e4.application.help/toc.xml @@ -6,6 +6,7 @@ - + + \ No newline at end of file diff --git a/plugins/com.minres.scviewer.e4.application/Application.e4xmi b/plugins/com.minres.scviewer.e4.application/Application.e4xmi index 82a3a223..63daffbc 100644 --- a/plugins/com.minres.scviewer.e4.application/Application.e4xmi +++ b/plugins/com.minres.scviewer.e4.application/Application.e4xmi @@ -32,6 +32,7 @@ + @@ -179,6 +180,7 @@ categoryTag:General + @@ -229,6 +231,7 @@ + @@ -297,6 +300,7 @@ + diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/handlers/CombineBitsHandler.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/handlers/CombineBitsHandler.java new file mode 100644 index 00000000..e45bb972 --- /dev/null +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/handlers/CombineBitsHandler.java @@ -0,0 +1,114 @@ +/******************************************************************************* + * Copyright (c) 2026 MINRES Technologies GmbH and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * MINRES Technologies GmbH - initial API and implementation + *******************************************************************************/ +package com.minres.scviewer.e4.application.handlers; + +import java.util.ArrayList; +import java.util.List; +import org.eclipse.e4.core.di.annotations.CanExecute; +import org.eclipse.e4.core.di.annotations.Execute; +import org.eclipse.e4.ui.workbench.modeling.EPartService; +import org.eclipse.jface.dialogs.TitleAreaDialog; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; +import org.eclipse.swt.widgets.TableItem; +import org.eclipse.swt.widgets.Text; +import com.minres.scviewer.database.ui.TrackEntry; + +public class CombineBitsHandler { + public record Request(String name, List bits) { + public Request { bits = List.copyOf(bits); } + } + + @CanExecute public boolean canExecute(EPartService parts) { + var viewer = GroupTracksHandler.activeViewer(parts); + return viewer != null && viewer.canCombineSelectedBits(); + } + + @Execute public void execute(EPartService parts, Shell shell) { + var viewer = GroupTracksHandler.activeViewer(parts); + if (viewer == null || !viewer.canCombineSelectedBits()) return; + Request request = requestVector(shell, viewer.selectedBits()); + if (request != null) viewer.combineBits(request.name(), request.bits()); + } + + protected Request requestVector(Shell shell, List bits) { + CombineDialog dialog = new CombineDialog(shell, bits); + return dialog.open() == Window.OK ? dialog.getRequest() : null; + } + + public static class CombineDialog extends TitleAreaDialog { + private final List bits; + private Text name; + private Table table; + private Request request; + public Request getRequest() { return request; } + public CombineDialog(Shell shell, List bits) { + super(shell); + this.bits = new ArrayList<>(bits); + setShellStyle(getShellStyle() | SWT.RESIZE); + } + @Override protected Control createDialogArea(Composite parent) { + Composite area = (Composite) super.createDialogArea(parent); + setTitle("Combine bits"); + setMessage("Name the vector and order its bits. The top entry is the most significant bit."); + Composite form = new Composite(area, SWT.NONE); + form.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + form.setLayout(new GridLayout(2, false)); + new Label(form, SWT.NONE).setText("Vector name"); + name = new Text(form, SWT.BORDER); + name.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + name.setText("Combined vector"); + table = new Table(form, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION | SWT.V_SCROLL); + table.setHeaderVisible(true); + GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); + data.widthHint = 450; data.heightHint = 220; + table.setLayoutData(data); + TableColumn index = new TableColumn(table, SWT.NONE); index.setText("Bit"); index.setWidth(55); + TableColumn source = new TableColumn(table, SWT.NONE); source.setText("Source"); source.setWidth(380); + Composite buttons = new Composite(form, SWT.NONE); + buttons.setLayout(new GridLayout()); + Button up = new Button(buttons, SWT.PUSH); up.setText("Move up"); + Button down = new Button(buttons, SWT.PUSH); down.setText("Move down"); + up.addListener(SWT.Selection, event -> move(-1)); + down.addListener(SWT.Selection, event -> move(1)); + refresh(0); + return area; + } + private void move(int offset) { + int selected = table.getSelectionIndex(), target = selected + offset; + if (selected < 0 || target < 0 || target >= bits.size()) return; + java.util.Collections.swap(bits, selected, target); + refresh(target); + } + private void refresh(int selected) { + table.removeAll(); + for (int i = 0; i < bits.size(); i++) { + TableItem item = new TableItem(table, SWT.NONE); + item.setText(new String[]{Integer.toString(bits.size() - i - 1), bits.get(i).waveform.getDisplayName()}); + } + table.setSelection(selected); + } + @Override protected void okPressed() { + if (name.getText().isBlank()) { setErrorMessage("Enter a vector name"); return; } + request = new Request(name.getText().trim(), bits); + super.okPressed(); + } + } +} diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/ViewerSettings.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/ViewerSettings.java index c76ebf0c..36f70893 100644 --- a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/ViewerSettings.java +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/ViewerSettings.java @@ -22,6 +22,8 @@ import java.util.List; import java.util.Map; import com.minres.scviewer.database.IWaveform; +import com.minres.scviewer.database.CombinedBitVectorWaveform; +import com.minres.scviewer.database.BitVector; import com.minres.scviewer.database.IWaveformDb; import com.minres.scviewer.database.WaveformType; import com.minres.scviewer.database.EventEntry; @@ -34,7 +36,7 @@ import com.minres.scviewer.database.ui.BitWaveform; /** Validates the existing properties format before any viewer state is changed. */ public record ViewerSettings(List tracks, List cursors, Long scale, Long baseline, - Long transactionId, String transactionTrack, Boolean detailsShown, List files) { + Long transactionId, String transactionTrack, Boolean detailsShown, List files, List combinedVectors) { public static final String DATABASE_FILE = "DATABASE_FILE"; public static final String SHOWN_WAVEFORM = "SHOWN_WAVEFORM"; public static final String WAVEFORM_TYPE = ".WAVEFORM_TYPE"; @@ -59,10 +61,32 @@ public record ViewerSettings(List tracks, List cursors, Long scale, } } + public record BitSource(String waveform, int bit) { + public BitSource { + if (waveform == null || waveform.isBlank() || waveform.startsWith("@combined:") || bit < 0) + throw new IllegalArgumentException("Invalid recorded bit reference"); + } + } + public record CombinedVector(String id, String name, List bits) { + public CombinedVector { + if (id == null || !id.startsWith("@combined:") || id.length() <= 10 || name == null || name.isBlank() + || bits == null || bits.size() < 2) throw new IllegalArgumentException("Invalid combined vector definition"); + bits = List.copyOf(bits); + } + } + + public ViewerSettings(List tracks, List cursors, Long scale, Long baseline, + Long transactionId, String transactionTrack, Boolean detailsShown, List files) { + this(tracks, cursors, scale, baseline, transactionId, transactionTrack, detailsShown, files, List.of()); + } + public ViewerSettings { tracks = List.copyOf(tracks); cursors = List.copyOf(cursors); files = List.copyOf(files); + combinedVectors = List.copyOf(combinedVectors); + if (combinedVectors.stream().map(CombinedVector::id).distinct().count() != combinedVectors.size()) + throw new IllegalArgumentException("Duplicate combined vector identity"); } public static ViewerSettings read(Path path) throws IOException { @@ -81,6 +105,18 @@ public record ViewerSettings(List tracks, List cursors, Long scale, public Map toMap() { Map state = new HashMap<>(); + state.put("COMBINED_VECTORS", Integer.toString(combinedVectors.size())); + for (int i = 0; i < combinedVectors.size(); i++) { + CombinedVector vector = combinedVectors.get(i); + String key = "COMBINED_VECTOR" + i; + state.put(key + ".ID", vector.id()); + state.put(key + ".NAME", vector.name()); + state.put(key + ".BITS", Integer.toString(vector.bits().size())); + for (int bit = 0; bit < vector.bits().size(); bit++) { + state.put(key + ".BIT" + bit + ".SOURCE", vector.bits().get(bit).waveform()); + state.put(key + ".BIT" + bit + ".INDEX", Integer.toString(vector.bits().get(bit).bit())); + } + } state.put(DATABASE_FILE + "S", Integer.toString(files.size())); for (int i = 0; i < files.size(); i++) state.put(DATABASE_FILE + i, files.get(i).getAbsolutePath()); state.put(SHOWN_WAVEFORM + "S", Integer.toString(tracks.size())); @@ -113,13 +149,26 @@ public record ViewerSettings(List tracks, List cursors, Long scale, } public void replaceState(Map state) { - state.keySet().removeIf(key -> key.startsWith(DATABASE_FILE) || key.startsWith(SHOWN_WAVEFORM) + state.keySet().removeIf(key -> key.startsWith("COMBINED_VECTOR") || key.startsWith(DATABASE_FILE) || key.startsWith(SHOWN_WAVEFORM) || key.startsWith(SHOWN_CURSOR) || key.equals(SCALING_FACTOR) || key.equals(BASE_LINE_TIME) || key.equals(SELECTED_TX_ID) || key.equals(SELECTED_TRACKENTRY_NAME) || key.equals(TX_DETAILS_SHOWN)); state.putAll(toMap()); } public static ViewerSettings parse(Map state) { + List vectors = new ArrayList<>(); + for (int i = 0, n = count(state, "COMBINED_VECTORS"); i < n; i++) { + String key = "COMBINED_VECTOR" + i; + List bits = new ArrayList<>(); + for (int j = 0, m = count(state, key + ".BITS"); j < m; j++) { + String source = key + ".BIT" + j; + required(state, source + ".INDEX"); + Long bit = number(state, source + ".INDEX"); + if (bit < 0 || bit > Integer.MAX_VALUE) throw invalid(source + ".INDEX", "invalid bit index"); + bits.add(new BitSource(required(state, source + ".SOURCE"), bit.intValue())); + } + vectors.add(new CombinedVector(required(state, key + ".ID"), required(state, key + ".NAME"), bits)); + } List tracks = new ArrayList<>(); int count = count(state, SHOWN_WAVEFORM + "S"); for (int i = 0; i < count; i++) { @@ -156,7 +205,7 @@ public record ViewerSettings(List tracks, List cursors, Long scale, String track = state.get(SELECTED_TRACKENTRY_NAME); if (tx != null) required(state, SELECTED_TRACKENTRY_NAME); return new ViewerSettings(List.copyOf(tracks), List.copyOf(cursors), scale, baseline, - tx, track, bool(state, TX_DETAILS_SHOWN), List.copyOf(databaseFiles(state))); + tx, track, bool(state, TX_DETAILS_SHOWN), List.copyOf(databaseFiles(state)), vectors); } public static List databaseFiles(Map state) { @@ -166,12 +215,52 @@ public record ViewerSettings(List tracks, List cursors, Long scale, return files; } + /** Definitions only reference recorded waveforms, so reconstruction cannot create cycles. */ + public Map resolveCombinedVectors(IWaveformDb database, List missing) { + Map resolved = new HashMap<>(); + for (CombinedVector vector : combinedVectors) { + List bits = new ArrayList<>(); + for (BitSource bit : vector.bits()) { + IWaveform waveform = resolveWaveform(database, bit.waveform()); + if (waveform == null || waveform.getType() != WaveformType.SIGNAL || bit.bit() >= waveform.getWidth()) { + missing.add(vector.name() + ": " + bit.waveform() + "[" + bit.bit() + "]"); + break; + } + EventEntry first = waveform.getEvents().firstEntry(); + if (first != null && (first.events == null || first.events.length == 0 + || !(first.events[first.events.length - 1] instanceof BitVector))) { + missing.add(vector.name() + ": " + bit.waveform() + " is not a bit signal"); + break; + } + bits.add(new CombinedBitVectorWaveform.SourceBit(waveform, bit.bit())); + } + if (bits.size() == vector.bits().size()) + resolved.put(vector.id(), new CombinedBitVectorWaveform(vector.id(), vector.name(), bits)); + } + return resolved; + } + + public String displayName(String identity) { + for (CombinedVector vector : combinedVectors) { + if (identity.equals(vector.id())) return vector.name(); + if (identity.startsWith(vector.id() + "[")) return vector.name() + identity.substring(vector.id().length()); + } + return identity; + } + public static IWaveform resolveWaveform(IWaveformDb database, String name) { - IWaveform waveform = database.getStreamByName(name); + return resolveWaveform(database, name, Map.of()); + } + + public static IWaveform resolveWaveform(IWaveformDb database, String name, Map derived) { + IWaveform waveform = derived.get(name); + if (waveform == null && database != null) waveform = database.getStreamByName(name); if (waveform != null) return waveform; int bitStart = name.lastIndexOf('['); if (bitStart > 0 && name.endsWith("]")) { - IWaveform source = database.getStreamByName(name.substring(0, bitStart)); + String sourceName = name.substring(0, bitStart); + IWaveform source = derived.get(sourceName); + if (source == null && database != null) source = database.getStreamByName(sourceName); if (source != null && source.getType() == WaveformType.SIGNAL) { try { int bit = Integer.parseInt(name.substring(bitStart + 1, name.length() - 1)); @@ -179,6 +268,7 @@ public record ViewerSettings(List tracks, List cursors, Long scale, } catch (NumberFormatException e) { /* A declared signal range is not a projected bit. */ } } } + if (database == null) return null; int separator = name.lastIndexOf('.'); if (separator <= 0 || separator == name.length() - 1) return null; IWaveform parent = database.getStreamByName(name.substring(0, separator)); diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/WaveformViewer.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/WaveformViewer.java index 0dfb2cbb..b8b37896 100644 --- a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/WaveformViewer.java +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/WaveformViewer.java @@ -70,6 +70,10 @@ import org.eclipse.swt.widgets.Widget; import org.eclipse.wb.swt.SWTResourceManager; import org.osgi.service.prefs.BackingStoreException; +import com.minres.scviewer.database.CombinedBitVectorWaveform; +import com.minres.scviewer.database.ui.BitVectorComposition; +import com.minres.scviewer.database.ui.BitWaveform; +import com.minres.scviewer.e4.application.internal.util.LatestJob; import com.minres.scviewer.database.DataType; import com.minres.scviewer.database.EmptyWaveform; import com.minres.scviewer.database.IWaveform; @@ -177,6 +181,9 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene String partConfig = ""; private Path settingsFile; + private LatestJob vectorJob; + private record PreparedVector(CombinedBitVectorWaveform vector, List tracks, + IWaveformDb database, String error) { } /** The persisted state. */ Map persistedState; @@ -440,7 +447,7 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene TrackEntry te = (TrackEntry)res.get(0); final Font font = SWTResourceManager.getFont("Terminal", 10, SWT.NORMAL); final Label label = new Label(parent, SWT.NONE); - label.setText(te.waveform.getFullName()); + label.setText(te.waveform.getDisplayName()); label.setFont(font); GridData labelGridData = new GridData(); labelGridData.horizontalAlignment = GridData.FILL; @@ -460,6 +467,7 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene public void closeDatabase() { if (disposed) return; disposed = true; + if (vectorJob != null) vectorJob.close(); if (sessions != null) sessions.close(); if (observedPreferences != null) { observedPreferences.removePreferenceChangeListener(this); @@ -528,6 +536,7 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene protected void loadDatabase(final Map state, long delay) { if (disposed) return; + if (vectorJob != null) vectorJob.cancel(); setSelection(null); waveformPane.getStreamList().clear(); waveformPane.update(); @@ -649,16 +658,30 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene } } + private static void captureCombined(List entries, Map definitions) { + for (TrackEntry entry : entries) { + IWaveform source = entry.waveform instanceof BitWaveform bit ? bit.getSource() : entry.waveform; + if (source instanceof CombinedBitVectorWaveform vector) { + definitions.putIfAbsent(vector.getFullName(), new ViewerSettings.CombinedVector(vector.getFullName(), + vector.getName(), vector.getSources().stream() + .map(bit -> new ViewerSettings.BitSource(bit.waveform().getFullName(), bit.bit())).toList())); + } + if (entry.isExpandable()) captureCombined(entry.waveforms, definitions); + } + } + private ViewerSettings captureSettings() { List tracks = new ArrayList<>(); captureTracks(waveformPane.getStreamList(), null, tracks); + Map definitions = new java.util.LinkedHashMap<>(); + captureCombined(waveformPane.getStreamList(), definitions); WaveformSelection selection = WaveformSelection.from(waveformPane.getSelection()); boolean selectedTransaction = selection.transaction() != null && selection.track() != null; return new ViewerSettings(tracks, waveformPane.getCursorList().stream().map(ICursor::getTime).toList(), waveformPane.getWaveformZoom().getScale(), waveformPane.getWaveformZoom().getMinVisibleTime(), selectedTransaction ? selection.transaction().getId() : null, selectedTransaction ? selection.track().waveform.getFullName() : null, - store.getBoolean(PreferenceConstants.SHOW_TX_DETAILS, false), List.copyOf(filesToLoad)); + store.getBoolean(PreferenceConstants.SHOW_TX_DETAILS, false), List.copyOf(filesToLoad), List.copyOf(definitions.values())); } /** @@ -677,16 +700,18 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene private record ResolvedTrack(IWaveform waveform, ViewerSettings.Track settings) {} private void applySettings(ViewerSettings settings) { + if (vectorJob != null) vectorJob.cancel(); // Resolve all references before replacing the current layout. List resolved = new ArrayList<>(); List missing = new ArrayList<>(); + Map derived = settings.resolveCombinedVectors(getDatabase(), missing); ITx selectedTransaction = null; IWaveform selectedWaveform = null; for (ViewerSettings.Track track : settings.tracks()) { IWaveform waveform = track.type() == WaveformType.EMPTY ? new EmptyWaveform(track.name()) - : ViewerSettings.resolveWaveform(getDatabase(), track.name()); + : ViewerSettings.resolveWaveform(getDatabase(), track.name(), derived); if (waveform == null) { - missing.add(track.name()); + missing.add(settings.displayName(track.name())); continue; } resolved.add(new ResolvedTrack(waveform, track)); @@ -735,7 +760,7 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene waveformPane.setSelection(WaveformSelection.of(selectedTransaction, transactionTrack)); else waveformPane.setSelection(new StructuredSelection(selectedTracks)); updateAll(); - if (!missing.isEmpty() && !disposed && !myParent.isDisposed()) + if (!missing.isEmpty() && !disposed && myParent != null && !myParent.isDisposed()) MessageDialog.openWarning(myParent.getShell(), "Missing waveforms", "These waveforms are absent from the current database and were skipped:\n" + String.join("\n", missing)); } @@ -938,6 +963,58 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene updateAll(); } + public List selectedBits() { + return disposed || waveformPane == null ? List.of() : BitVectorComposition.selectedBits( + waveformPane.getStreamList(), WaveformSelection.from(getSelection()).tracks()); + } + + public boolean canCombineSelectedBits() { return !selectedBits().isEmpty(); } + + public void combineBits(String name, List ordered) { + if (disposed || name == null || name.isBlank() || waveformPane == null + || BitVectorComposition.selectedBits(waveformPane.getStreamList(), ordered).isEmpty()) return; + List snapshot = List.copyOf(ordered); + IWaveformDb database = getDatabase(); + long visibleStart = waveformPane.getWaveformZoom().getMinVisibleTime(); + long visibleEnd = waveformPane.getWaveformZoom().getMaxVisibleTime(); + long cursor = waveformPane.getCursorTime(); + if (vectorJob == null) vectorJob = new LatestJob<>(task -> sync.asyncExec(task), result -> { + if (disposed || getDatabase() != result.database()) return; + if (result.error() != null) { reportSettingsError("Cannot combine bits", result.error()); return; } + insertCombinedVector(result.vector(), result.tracks()); + }); + vectorJob.schedule("Combine bits", monitor -> { + try { + var vector = new CombinedBitVectorWaveform(name.trim(), BitVectorComposition.sources(snapshot)); + vector.getEvents().firstEntry(); // Load any lazy inputs on this worker, before painting on the UI thread. + vector.getEvents().floorEntry(visibleStart); + vector.getEvents().floorEntry(cursor); + for (var ignored : vector.getEvents().subMap(visibleStart, true, visibleEnd)) { + if (monitor.isCanceled()) return null; + } + return new PreparedVector(vector, snapshot, database, null); + } catch (RuntimeException exception) { + return new PreparedVector(null, snapshot, database, exception.toString()); + } + }); + } + + protected void insertCombinedVector(CombinedBitVectorWaveform vector, List tracks) { + List roots = waveformPane.getStreamList(); + List visible = TrackEntry.visibleTracks(roots); + if (tracks.stream().anyMatch(track -> !visible.contains(track))) return; + TrackEntry anchor = visible.stream().filter(tracks::contains).reduce((previous, current) -> current).orElse(null); + if (anchor == null) return; + // Nested bits stay in their group/bus; insert after their containing root. + int position = 0; + while (position < roots.size() && roots.get(position) != anchor + && TrackEntry.siblingsOf(List.of(roots.get(position)), anchor) == null) position++; + if (position == roots.size()) return; + TrackEntry combined = waveformPane.addWaveform(vector, position + 1); + waveformPane.update(); + waveformPane.setSelection(new StructuredSelection(combined)); + } + public boolean canGroupSelectedTracks() { return waveformPane != null && TrackEntry.groupingSiblings(waveformPane.getStreamList(), WaveformSelection.from(getSelection()).tracks()) != null; diff --git a/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/CombinedBitVectorTest.java b/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/CombinedBitVectorTest.java new file mode 100644 index 00000000..02b895c3 --- /dev/null +++ b/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/CombinedBitVectorTest.java @@ -0,0 +1,144 @@ +/******************************************************************************* + * Copyright (c) 2026 MINRES Technologies GmbH and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * MINRES Technologies GmbH - initial API and implementation + *******************************************************************************/ +package com.minres.scviewer.database.test; + +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.concurrent.atomic.AtomicInteger; +import java.lang.reflect.Proxy; +import org.junit.Test; +import com.minres.scviewer.database.*; +import com.minres.scviewer.database.CombinedBitVectorWaveform.SourceBit; + + +public class CombinedBitVectorTest { + private static class Signal extends EmptyWaveform { + private final int width; + private final IEventList values = new EventList(); + Signal(int id, String name, int width) { super(name); this.width = width; } + void addSignalChange(long time, BitVector value) { values.put(time, value); } + @Override public int getWidth() { return width; } + @Override public WaveformType getType() { return WaveformType.SIGNAL; } + @Override public IEventList getEvents() { return values; } + @Override public IEvent[] getEventsAtTime(long time) { return values.get(time); } + @Override public IEvent[] getEventsBeforeTime(long time) { + var entry = values.floorEntry(time); return entry == null ? new IEvent[0] : entry.events; + } + } + private Signal signal(String name, long[] times, String... values) { + var signal = new Signal(0, name, 1); + for (int i = 0; i < times.length; i++) signal.addSignalChange(times[i], BitVector.fromString(1, values[i])); + return signal; + } + private CombinedBitVectorWaveform combine(IWaveform a, IWaveform b) { + return new CombinedBitVectorWaveform("bus", List.of(new SourceBit(a, 0), new SourceBit(b, 0))); + } + private String value(EventEntry entry) { return entry == null ? null : entry.events[0].toString(); } + + @Test public void mergesStaggeredAndSimultaneousChangesAndSuppressesUnchangedValues() { + var a = signal("a", new long[]{5, 20, 20, 25, 30, 40}, "0", "0", "1", "1", "x", "z"); + var b = signal("b", new long[]{10, 20, 25}, "1", "0", "0"); + var bus = combine(a, b); + var map = bus.getEvents(); + assertEquals(List.of(5L, 10L, 20L, 30L, 40L), map.entrySet().stream().map(e -> e.timestamp).toList()); + assertEquals(List.of("0x", "01", "10", "x0", "z0"), map.entrySet().stream().map(this::value).toList()); + assertEquals(0, bus.getEventsBeforeTime(4).length); + assertEquals("01", bus.getEventsBeforeTime(19)[0].toString()); + assertEquals("10", bus.getEventsBeforeTime(25)[0].toString()); + assertNull(bus.getEventsAtTime(25)); + assertEquals(30, map.higherEntry(20).timestamp); + assertEquals(20, map.lowerEntry(30).timestamp); + assertEquals(20, map.floorEntry(25).timestamp); + assertEquals(30, map.ceilingEntry(25).timestamp); + assertTrue(map.containsKey(20)); + assertFalse(map.containsKey(25)); + ((BitVector) map.get(20)[0]).setValue(0, BitValue.Z); + assertEquals("10", bus.getEventsAtTime(20)[0].toString()); + assertEquals("0", b.getEventsAtTime(20)[0].toString()); + try { map.put(0, new BitVector(2)); fail(); } catch (UnsupportedOperationException expected) { } + } + + @Test public void rangesRemainBoundedAndUseUnsignedTimestamps() { + var a = signal("a", new long[]{0, Long.MAX_VALUE, Long.MIN_VALUE, -1L}, "0", "1", "x", "z"); + var b = signal("b", new long[]{0}, "1"); + var map = combine(a, b).getEvents(); + assertEquals(0, map.firstKey()); assertEquals(-1L, map.lastKey()); + assertEquals(Long.MIN_VALUE, map.higherEntry(Long.MAX_VALUE).timestamp); + assertEquals(Long.MAX_VALUE, map.lowerEntry(Long.MIN_VALUE).timestamp); + var range = map.subMap(Long.MAX_VALUE, false, -1L); + assertEquals(2, range.size()); + assertNull(range.floorEntry(Long.MAX_VALUE)); + assertEquals(Long.MIN_VALUE, range.ceilingEntry(0).timestamp); + assertEquals(-1L, range.floorEntry(-1L).timestamp); + assertNull(range.higherEntry(-1L)); + assertEquals(2, range.subMap(0, true, -1L).size()); + assertTrue(map.subMap(0, false, 0).isEmpty()); + assertTrue(range.subMap(0, true, Long.MAX_VALUE).isEmpty()); + try { map.subMap(-1L, true, 0); fail(); } catch (IllegalArgumentException expected) { } + } + + @Test public void handlesEmptyInputsAndMissingInitialValues() { + var empty = signal("empty", new long[]{}); + var other = signal("other", new long[]{7, 9}, "x", "z"); + var bus = combine(empty, other); + assertEquals("xx", value(bus.getEvents().firstEntry())); + assertEquals("xz", value(bus.getEvents().lastEntry())); + assertEquals(2, bus.getEvents().size()); + var map = combine(empty, empty).getEvents(); + assertTrue(map.isEmpty()); assertEquals(0, map.size()); + assertNull(map.firstEntry()); assertNull(map.lastEntry()); + assertNull(map.floorEntry(-1L)); assertNull(map.ceilingEntry(0)); + try { map.firstKey(); fail(); } catch (NoSuchElementException expected) { } + try { map.lastKey(); fail(); } catch (NoSuchElementException expected) { } + } + + @Test public void wideVectorsAndCompositionFlattenToRecordedInputsWithIndependentIdentity() { + var a = signal("a", new long[]{0}, "1"); + var b = signal("b", new long[]{0}, "z"); + List bits = new ArrayList<>(); + for (int i = 0; i < 80; i++) bits.add(new SourceBit(i % 2 == 0 ? a : b, 0)); + var wide = new CombinedBitVectorWaveform("wide", bits); + assertEquals("1z".repeat(40), value(wide.getEvents().firstEntry())); + var combined = new CombinedBitVectorWaveform("bus", List.of(new SourceBit(wide, 1), new SourceBit(wide, 0))); + assertSame(a, combined.getSources().get(0).waveform()); + assertSame(b, combined.getSources().get(1).waveform()); + assertEquals("1z", value(combined.getEvents().firstEntry())); + assertFalse(combined.isSame(new CombinedBitVectorWaveform("bus", bits))); + var restored = new CombinedBitVectorWaveform(combined.getFullName(), "renamed", combined.getSources()); + assertTrue(combined.isSame(restored)); assertEquals("renamed", restored.getDisplayName()); + String id = restored.getFullName(); restored.setName("another name"); assertEquals(id, restored.getFullName()); + } + + @Test public void constructionAndRangeAccessDoNotMaterializeTheRecording() { + AtomicInteger loads = new AtomicInteger(); + var delegate = signal("a", new long[]{0, 10, 20}, "0", "1", "0").getEvents(); + var source = new Signal(0, "a", 1) { + @Override public IEventList getEvents() { + loads.incrementAndGet(); + return (IEventList) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{IEventList.class}, + (proxy, method, args) -> { + if (List.of("entrySet", "iterator", "size").contains(method.getName())) + throw new AssertionError("Full source traversal is unnecessary"); + return method.invoke(delegate, args); + }); + } + }; + var bus = combine(source, source); + var range = bus.getEvents().subMap(5, true, 15); + assertEquals(0, loads.get()); + assertEquals("11", value(range.firstEntry())); + assertEquals(2, loads.get()); + assertEquals("11", value(range.lastEntry())); + assertEquals(2, loads.get()); + } +} diff --git a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/handlers/CommandHandlersTest.java b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/handlers/CommandHandlersTest.java index 5152618e..680e6797 100644 --- a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/handlers/CommandHandlersTest.java +++ b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/handlers/CommandHandlersTest.java @@ -72,6 +72,39 @@ public class CommandHandlersTest { (proxy, method, args) -> method.getName().equals("getActivePart") ? active.get() : null); } + @Test + public void combineHandlerRoutesToActiveViewerAndHonorsDialogCancellation() { + var first = new TrackEntry(waveform(WaveformType.SIGNAL), null); + var second = new TrackEntry(waveform(WaveformType.SIGNAL), null); + class CombineViewer extends Viewer { + boolean enabled = true; + CombineBitsHandler.Request request; + @Override public List selectedBits() { return enabled ? List.of(first, second) : List.of(); } + @Override public void combineBits(String name, List bits) { + request = new CombineBitsHandler.Request(name, bits); + } + } + CombineViewer viewer = new CombineViewer(); + AtomicReference active = new AtomicReference<>(); + var service = parts(active); + AtomicReference answer = new AtomicReference<>(); + CombineBitsHandler handler = new CombineBitsHandler() { + @Override protected Request requestVector(org.eclipse.swt.widgets.Shell shell, List bits) { + assertEquals(List.of(first, second), bits); return answer.get(); + } + }; + try { + assertFalse(handler.canExecute(service)); handler.execute(service, null); + active.set(part(viewer)); assertTrue(handler.canExecute(service)); + handler.execute(service, null); assertNull(viewer.request); + answer.set(new CombineBitsHandler.Request("bus", List.of(second, first))); + handler.execute(service, null); assertEquals(answer.get(), viewer.request); + viewer.enabled = false; viewer.request = null; + assertFalse(handler.canExecute(service)); handler.execute(service, null); assertNull(viewer.request); + active.set(part(new Object())); assertFalse(handler.canExecute(service)); + } finally { viewer.closeDatabase(); } + } + @Test public void groupingHandlersFollowActivePartAndGuardMissingSelection() { class GroupViewer extends Viewer { diff --git a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/BitVectorExpansionTest.java b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/BitVectorExpansionTest.java index 27fdee3b..4d74849f 100644 --- a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/BitVectorExpansionTest.java +++ b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/BitVectorExpansionTest.java @@ -172,7 +172,7 @@ public class BitVectorExpansionTest { assertEquals(5, TrackEntry.visibleTracks(List.of(restored)).size()); } - private List restore(ViewerSettings settings, IWaveformDb database) throws Exception { + List restore(ViewerSettings settings, IWaveformDb database) throws Exception { var roots = new ArrayList(); var paneType = com.minres.scviewer.database.ui.IWaveformView.class; var zoomType = com.minres.scviewer.database.ui.IWaveformZoom.class; diff --git a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/CombinedVectorSettingsTest.java b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/CombinedVectorSettingsTest.java new file mode 100644 index 00000000..89b9f314 --- /dev/null +++ b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/CombinedVectorSettingsTest.java @@ -0,0 +1,136 @@ +/******************************************************************************* + * Copyright (c) 2026 MINRES Technologies GmbH and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * MINRES Technologies GmbH - initial API and implementation + *******************************************************************************/ +package com.minres.scviewer.e4.application.parts; + +import static org.junit.Assert.*; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.junit.Test; +import com.minres.scviewer.database.*; +import com.minres.scviewer.database.CombinedBitVectorWaveform.SourceBit; +import com.minres.scviewer.database.ui.*; +import com.minres.scviewer.e4.application.internal.util.ViewerSettings; + +public class CombinedVectorSettingsTest { + private final BitVectorExpansionTest.Signal input = new BitVectorExpansionTest.Signal("top.input", 4); + private IWaveformDb database() { + return (IWaveformDb) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{IWaveformDb.class}, + (proxy, method, args) -> method.getName().equals("getStreamByName") + && input.getFullName().equals(args[0]) ? input : null); + } + private CombinedBitVectorWaveform vector() { + input.events.put(0, BitVector.fromString(4, "10xz")); + return new CombinedBitVectorWaveform("same label", List.of(new SourceBit(input, 0), new SourceBit(input, 3))); + } + private ViewerSettings capture(List roots) throws Exception { + var tracks = new ArrayList(); + Map definitions = new LinkedHashMap<>(); + var capture = WaveformViewer.class.getDeclaredMethod("captureTracks", List.class, Integer.class, List.class); + capture.setAccessible(true); capture.invoke(null, roots, null, tracks); + var combined = WaveformViewer.class.getDeclaredMethod("captureCombined", List.class, Map.class); + combined.setAccessible(true); combined.invoke(null, roots, definitions); + return new ViewerSettings(tracks, List.of(), null, null, null, null, null, List.of(), List.copyOf(definitions.values())); + } + + @Test public void eligibilityAcceptsExpandedBitsAndRejectsMixedOrUnrelatedSelections() { + var bus = new TrackEntry(vector(), null); bus.setExpanded(true); + var roots = List.of(TrackEntry.group("group", List.of(bus), null)); + var first = bus.waveforms.get(0); var second = bus.waveforms.get(1); + assertEquals(List.of(first, second), BitVectorComposition.selectedBits(roots, List.of(second, first))); + assertTrue(BitVectorComposition.selectedBits(roots, List.of(bus, first)).isEmpty()); + assertTrue(BitVectorComposition.selectedBits(roots, List.of(first)).isEmpty()); + assertTrue(BitVectorComposition.selectedBits(roots, List.of(first, new TrackEntry(input, null))).isEmpty()); + var real = new BitVectorExpansionTest.Signal("real", 1); + real.events.put(0, new DoubleVal(1.0)); + assertFalse(BitVectorComposition.isSingleBit(new TrackEntry(real, null))); + var sources = BitVectorComposition.sources(List.of(second, first)); + var combined = new CombinedBitVectorWaveform("reversed", sources); + assertEquals("1z", combined.getEventsBeforeTime(0)[0].toString()); + assertSame(input, combined.getSources().get(0).waveform()); + } + + @Test public void expandedVectorsRoundTripWithIdentitySeparateFromLabelsAndBitOrdering() throws Exception { + var vector = vector(); + var bus = new TrackEntry(vector, null); bus.setExpanded(true); + var other = new TrackEntry(new CombinedBitVectorWaveform(vector.getName(), vector.getSources()), null); + var settings = capture(List.of(TrackEntry.group("group", List.of(bus, other), null))); + var parsed = ViewerSettings.parse(settings.toMap()); + assertEquals(settings, parsed); + assertEquals(2, parsed.combinedVectors().size()); + assertEquals("same label", parsed.combinedVectors().get(0).name()); + assertNotEquals(parsed.combinedVectors().get(0).id(), parsed.combinedVectors().get(1).id()); + var roots = new BitVectorExpansionTest().restore(parsed, database()); + var restored = roots.get(0).waveforms.get(0); + assertEquals(TrackEntry.HierState.OPENED, restored.hierState); + assertEquals(2, restored.waveforms.size()); + assertEquals("same label", restored.waveform.getDisplayName()); + assertEquals("z1", restored.waveform.getEventsBeforeTime(0)[0].toString()); + assertEquals("same label[1]", restored.waveforms.get(0).waveform.getDisplayName()); + assertEquals("z", restored.waveforms.get(0).waveform.getEventsBeforeTime(0)[0].toString()); + assertEquals(2, roots.get(0).waveforms.size()); + } + + @Test public void survivingBitRetainsDefinitionWhenOriginalBusWasDeleted() throws Exception { + var bit = new TrackEntry(new BitWaveform(vector(), 1), null); + var settings = capture(List.of(bit)); + assertEquals(1, settings.combinedVectors().size()); + var restored = new BitVectorExpansionTest().restore(settings, database()); + assertEquals(1, restored.size()); + assertEquals("z", restored.get(0).waveform.getEventsBeforeTime(0)[0].toString()); + } + + @Test public void missingInputsSkipWholeBusAndLeaveOtherTracksIntact() throws Exception { + var bus = new TrackEntry(vector(), null); bus.setExpanded(true); + var settings = capture(List.of(bus, new TrackEntry(input, null))); + var map = new HashMap<>(settings.toMap()); + map.put("COMBINED_VECTOR0.BIT0.SOURCE", "missing.source"); + settings = ViewerSettings.parse(map); + List missing = new ArrayList<>(); + assertTrue(settings.resolveCombinedVectors(database(), missing).isEmpty()); + assertTrue(missing.get(0).contains("missing.source")); + var roots = new BitVectorExpansionTest().restore(settings, database()); + assertEquals(1, roots.size()); assertSame(input, roots.get(0).waveform); + map.put("COMBINED_VECTOR0.BIT0.SOURCE", input.getFullName()); + map.put("COMBINED_VECTOR0.BIT0.INDEX", "99"); + assertTrue(ViewerSettings.parse(map).resolveCombinedVectors(database(), new ArrayList<>()).isEmpty()); + } + + @Test public void validatesDefinitionsAndRemovesObsoleteDefinitionsWhenReplacingState() throws Exception { + var settings = capture(List.of(new TrackEntry(vector(), null))); + for (Map.Entry invalid : Map.of( + "COMBINED_VECTOR0.BIT0.INDEX", "-1", + "COMBINED_VECTOR0.BIT1.INDEX", "99999999999", + "COMBINED_VECTOR0.BIT0.SOURCE", settings.combinedVectors().get(0).id(), + "COMBINED_VECTOR0.BITS", "1", + "COMBINED_VECTOR0.NAME", " ").entrySet()) { + var map = new HashMap<>(settings.toMap()); map.put(invalid.getKey(), invalid.getValue()); + try { ViewerSettings.parse(map); fail("Accepted " + invalid); } catch (IllegalArgumentException expected) { } + } + var map = new HashMap<>(settings.toMap()); + ViewerSettings legacy = ViewerSettings.parse(Map.of()); + legacy.replaceState(map); + assertEquals(legacy, ViewerSettings.parse(map)); + assertFalse(map.containsKey("COMBINED_VECTOR0.ID")); + assertTrue(ViewerSettings.parse(Map.of()).combinedVectors().isEmpty()); + var duplicate = new HashMap<>(settings.toMap()); + duplicate.put("COMBINED_VECTORS", "2"); + settings.toMap().forEach((key, value) -> { + if (key.startsWith("COMBINED_VECTOR0.")) + duplicate.put(key.replace("COMBINED_VECTOR0.", "COMBINED_VECTOR1."), value); + }); + try { ViewerSettings.parse(duplicate); fail("Accepted duplicate identities"); } + catch (IllegalArgumentException expected) { } + } +} diff --git a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/WaveformScrollTest.java b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/WaveformScrollTest.java index 93fb6a2c..3e467c32 100644 --- a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/WaveformScrollTest.java +++ b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/WaveformScrollTest.java @@ -123,6 +123,153 @@ public class WaveformScrollTest { } finally { gc.dispose(); image.dispose(); } } + private WaveformViewer compositionViewer(java.util.function.Consumer dispatch) throws Exception { + WaveformViewer viewer = new WaveformViewer(); + var pane = WaveformViewer.class.getDeclaredField("waveformPane"); + pane.setAccessible(true); pane.set(viewer, view); + var synchronizer = WaveformViewer.class.getDeclaredField("sync"); + synchronizer.setAccessible(true); + synchronizer.set(viewer, new org.eclipse.e4.ui.di.UISynchronize() { + @Override public void asyncExec(Runnable runnable) { dispatch.accept(runnable); } + @Override public void syncExec(Runnable runnable) { display.syncExec(runnable); } + @Override protected boolean isUIThread(Thread thread) { return thread == display.getThread(); } + @Override protected void showBusyWhile(Runnable runnable) { runnable.run(); } + @Override protected boolean dispatchEvents() { return display.readAndDispatch(); } + }); + return viewer; + } + + private List scalarInputs() { + var a = new BitVectorExpansionTest.Signal("a", 1); + var b = new BitVectorExpansionTest.Signal("b", 1); + a.events.put(0, com.minres.scviewer.database.BitVector.fromString(1, "0")); + b.events.put(0, com.minres.scviewer.database.BitVector.fromString(1, "1")); + TrackEntry first = view.addWaveform(a, -1), second = view.addWaveform(b, -1); + view.update(); + return List.of(first, second); + } + + private void waitUntil(java.util.function.BooleanSupplier condition) throws Exception { + long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); + while (!condition.getAsBoolean()) { + drainEvents(); + if (System.nanoTime() > deadline) fail("Timed out waiting for the combine job"); + Thread.sleep(5); + } + } + + @Test + public void combinesInRequestedOrderWithoutRemovingSourcesAndSupportsExpansion() throws Exception { + var inputs = scalarInputs(); + TrackEntry tail = view.addWaveform(new EmptyWaveform("tail"), -1); + view.setSelection(new StructuredSelection(List.of(inputs.get(1), inputs.get(0)))); + WaveformViewer viewer = compositionViewer(display::asyncExec); + try { + assertEquals(inputs, viewer.selectedBits()); + assertTrue(viewer.canCombineSelectedBits()); + viewer.combineBits("bus", List.of(inputs.get(1), inputs.get(0))); + waitUntil(() -> view.getStreamList().size() == 4); + TrackEntry bus = view.getStreamList().get(2); + assertEquals("bus", bus.waveform.getDisplayName()); + assertEquals("10", bus.waveform.getEventsBeforeTime(0)[0].toString()); + assertEquals(List.of(inputs.get(0), inputs.get(1), bus, tail), view.getStreamList()); + assertSame(bus, ((StructuredSelection) view.getSelection()).getFirstElement()); + view.setGroupExpanded(bus, true); + assertEquals(6, TrackEntry.visibleTracks(view.getStreamList()).size()); + assertEquals("b'1", bus.waveforms.get(0).currentValue); + assertEquals("b'0", bus.waveforms.get(1).currentValue); + view.setGroupExpanded(bus, false); + assertEquals(4, TrackEntry.visibleTracks(view.getStreamList()).size()); + view.deleteSelectedTracks(); drainEvents(); + assertEquals(List.of(inputs.get(0), inputs.get(1), tail), view.getStreamList()); + } finally { viewer.closeDatabase(); } + } + + @Test + public void combinedVectorsAreTopLevelAfterLastSelectedBitsContainingRoot() throws Exception { + var inputs = scalarInputs(); + var source = new BitVectorExpansionTest.Signal("original bus", 2); + source.events.put(0, com.minres.scviewer.database.BitVector.fromString(2, "10")); + TrackEntry bus = new TrackEntry(source, null); + bus.setExpanded(true); + var originalBits = List.copyOf(bus.waveforms); + TrackEntry inner = TrackEntry.group("inner", List.of(bus, inputs.get(1)), null); + TrackEntry outer = TrackEntry.group("outer", List.of(inner), null); + TrackEntry tail = new TrackEntry(new EmptyWaveform("tail"), null); + view.getStreamList().clear(); + view.getStreamList().addAll(List.of(inputs.get(0), outer, tail)); + view.update(); + WaveformViewer viewer = compositionViewer(display::asyncExec); + try { + viewer.combineBits("from bus", List.of(originalBits.get(1), originalBits.get(0))); + waitUntil(() -> view.getStreamList().size() == 4); + TrackEntry combined = view.getStreamList().get(2); + assertEquals("from bus", combined.waveform.getDisplayName()); + assertEquals(List.of(inputs.get(0), outer, combined, tail), view.getStreamList()); + assertEquals(List.of(bus, inputs.get(1)), inner.waveforms); + assertEquals(originalBits, bus.waveforms); + viewer.combineBits("mixed", List.of(originalBits.get(0), inputs.get(0))); + waitUntil(() -> view.getStreamList().size() == 5); + TrackEntry mixed = view.getStreamList().get(2); + assertEquals("mixed", mixed.waveform.getDisplayName()); + assertEquals("10", mixed.waveform.getEventsBeforeTime(0)[0].toString()); + assertEquals(List.of(inputs.get(0), outer, mixed, combined, tail), view.getStreamList()); + assertEquals(originalBits, bus.waveforms); + } finally { viewer.closeDatabase(); } + } + + @Test + public void closingViewerRejectsACombineResultAlreadyQueuedForPublication() throws Exception { + var inputs = scalarInputs(); + var pending = new java.util.concurrent.CopyOnWriteArrayList(); + WaveformViewer viewer = compositionViewer(pending::add); + viewer.combineBits("bus", inputs); + waitUntil(() -> !pending.isEmpty()); + viewer.closeDatabase(); + pending.forEach(Runnable::run); + assertEquals(inputs, view.getStreamList()); + assertFalse(viewer.canCombineSelectedBits()); + } + + private List descendants(org.eclipse.swt.widgets.Composite parent) { + var controls = new ArrayList(); + for (var child : parent.getChildren()) { + controls.add(child); + if (child instanceof org.eclipse.swt.widgets.Composite composite) controls.addAll(descendants(composite)); + } + return controls; + } + + @Test + public void combineDialogLabelsDestinationBitsAndAllowsReorderingAndNameValidation() { + var inputs = scalarInputs(); + class Dialog extends com.minres.scviewer.e4.application.handlers.CombineBitsHandler.CombineDialog { + Dialog() { super(shell, inputs); } + void accept() { okPressed(); } + } + Dialog dialog = new Dialog(); + dialog.create(); + try { + var controls = descendants(dialog.getShell()); + var table = (org.eclipse.swt.widgets.Table) controls.stream() + .filter(org.eclipse.swt.widgets.Table.class::isInstance).findFirst().orElseThrow(); + assertEquals("1", table.getItem(0).getText(0)); + assertEquals("a", table.getItem(0).getText(1)); + var down = (org.eclipse.swt.widgets.Button) controls.stream() + .filter(control -> control instanceof org.eclipse.swt.widgets.Button button + && button.getText().equals("Move down")).findFirst().orElseThrow(); + down.notifyListeners(SWT.Selection, new Event()); + assertEquals("b", table.getItem(0).getText(1)); + var name = (org.eclipse.swt.widgets.Text) controls.stream() + .filter(org.eclipse.swt.widgets.Text.class::isInstance).findFirst().orElseThrow(); + name.setText(" "); dialog.accept(); + assertNull(dialog.getRequest()); assertFalse(dialog.getShell().isDisposed()); + name.setText("ordered"); dialog.accept(); + assertEquals("ordered", dialog.getRequest().name()); + assertEquals(List.of(inputs.get(1), inputs.get(0)), dialog.getRequest().bits()); + } finally { if (dialog.getShell() != null && !dialog.getShell().isDisposed()) dialog.close(); } + } + @Test public void bitvectorDisclosureUpdatesAllPanesAndCursorValues() { var source = new BitVectorExpansionTest.Signal("bus", 4);