applies concurrency fixes

This commit is contained in:
eyck committed 2026-11-20 22:31:48 +01:00
1 parent 42e0d83403
commit 28eb1b673e
56 files changed
+1416 -326

No files matched your search

+113
View File
@@ -0,0 +1,113 @@
# Working on SCViewer
## Project layout
SCViewer is an Eclipse RCP application and a set of Eclipse plug-ins for viewing
waveforms and transaction recordings. The root Maven reactor uses Tycho; this is
not a conventional Maven `src/main/java` project. Java sources generally live in
each plug-in's `src/` directory.
- `plugins/com.minres.scviewer.database`: shared waveform, event, and transaction
interfaces, data structures, and database services.
- `plugins/com.minres.scviewer.database.{vcd,fst,ftr,text,sqlite}`: format loaders.
- `plugins/com.minres.scviewer.database.ui.swt`: SWT waveform rendering and controls.
- `plugins/com.minres.scviewer.e4.application`: standalone e4 application, handlers,
views, application model, and settings.
- `plugins/com.minres.scviewer.ui`: Eclipse workbench integration.
- `tests/`: database and application test bundles.
- `features/`: Eclipse feature definitions and their bundle inclusions.
- `releng/com.minres.scviewer.target`: shared PDE/Tycho target platform.
- `releng/com.minres.scviewer.updateSite`: p2 repository configuration and categories.
- `products/com.minres.scviewer.e4.product`: product definition and platform archives.
- `doc/com.minres.scviewer.doc`: AsciiDoc sources and documentation generation.
- `plugins/com.minres.scviewer.e4.application.help`: embedded help bundle, including
generated documentation.
## Building and checking changes
Run commands from the repository root:
```sh
mvn -version
mvn verify
```
Maven itself must run on JDK 21. Check the Java version in `mvn -version`; changing
the target platform's JRE or a bundle manifest does not change Maven's JVM. For
Eclipse Maven launches, select JDK 21 in the launch configuration's JRE tab.
Maven 3.9.16 with JDK 21 is a validated combination for this repository.
The Tycho version is centralized in the root POM's `tycho-version` property.
`.mvn/jvm.config` opens `sun.nio.ch` for JRuby used by documentation generation;
preserve this option when changing Maven JVM configuration.
`mvn verify` generates documentation, compiles the bundles, runs Tycho Surefire
tests, assembles the p2 repository, and packages Linux, Windows, and macOS x86_64
products. Network access is needed for uncached Maven and p2 dependencies.
Product archives are under
`products/com.minres.scviewer.e4.product/target/products/`; the update site is under
`releng/com.minres.scviewer.updateSite/target/repository/`.
For code or build changes, run the relevant checks and use the full reactor to
validate integration and packaging. Avoid treating a standalone module build as
equivalent: Tycho also needs the reactor's target-definition artifact and bundle
dependencies. For documentation-only instruction changes, a build is unnecessary.
Report the command, result, and any remaining warnings or untested behavior.
## Tests
- Tests use JUnit 4 (`org.junit.Test`) inside `eclipse-test-plugin` modules, with
sources under `tests/<bundle>/src/`.
- Database tests cover loaders, indexing, concurrency, and resource lifecycles;
recording fixtures live under `tests/com.minres.scviewer.database.test/inputs/`.
- Application tests cover handlers, filtering, settings, selection, grouping,
background jobs, and viewer lifecycles. The application test bundle is a fragment
of the application bundle and uses a headless Tycho harness; tests that create
SWT controls may still need a display.
- Add focused regression tests for behavior changes. Preserve deterministic event
ordering, lazy-loading semantics, and compatibility with existing recordings and
settings files.
- Inspect each test module's `target/surefire-reports/` on failure. Eclipse runtime
diagnostics may also appear in `target/work/data/.metadata/.log`.
## Implementation conventions
- Follow the surrounding Java formatting and existing package structure; avoid
unrelated reformatting. Preserve license headers.
- Respect OSGi bundle boundaries. When adding dependencies or resources, update
`META-INF/MANIFEST.MF`, `build.properties`, `plugin.xml`, or `OSGI-INF` declarations
as appropriate; a Java import or Maven dependency alone may not be sufficient.
- Keep database code independent of SWT/e4. Put rendering and UI behavior in the
appropriate UI bundle. Keep implementation packages internal unless a public API
change is intentional.
- Perform SWT widget operations on the UI thread. Keep expensive loading and
querying off it; dispose resources, detach listeners, and cancel background work
when their owning view or database closes.
- Preserve compatibility with the selected Eclipse platform. It currently uses
`javax.inject`; introducing `jakarta.inject` requires a coordinated platform
migration rather than an isolated import replacement.
- FST native sources and CMake scripts live under
`plugins/com.minres.scviewer.database.fst/csrc/fst/`. Native builds are separate
from the Java reactor; rebuild platform libraries only when the change requires
it and explain which platforms were validated.
## Build and documentation maintenance
- Keep the target definition, bundle execution environments, product JRE, and
Maven build JDK compatible. Check dependency resolution after target changes.
- The Orbit repository selection avoids an obsolete Felix SCR provider that
conflicts with Eclipse's Declarative Services API. Preserve that compatibility
when changing repository versions.
- Publish source bundles using `plugin-source` and the update site's
`includeAllSources`; do not reintroduce the deprecated `feature-source` goal or
generated source-feature references in `category.xml`.
- Keep the parent UTF-8 source encoding. Asciidoctor syntax-highlighter settings
belong under `<attributes>` as `<source-highlighter>`.
- Edit help content in `doc/com.minres.scviewer.doc/src/asciidoc/`. The documentation
build copies DocBook intermediates into `src/docbkx/` and generates files inside
the help bundle; review resulting diffs rather than hand-editing generated HTML.
- Read `README.md` for launch guidance, including the embedded-help configuration
directory restriction on spaces and percent escapes.
- Preserve existing user changes and local recording fixtures. Do not include
unrelated untracked inputs, generated `target/` contents, or rebuilt native
binaries in a change.
@@ -81,7 +81,7 @@ public class FstDbLoader implements IWaveformDbLoader, IFstDatabaseBuilder {
pcs.firePropertyChange(IWaveformDbLoader.LOADING_FINISHED, null, null);
}
public void dispose() {
public synchronized void dispose() {
if(parser!=null) {
parser.close();
parser=null;
@@ -183,7 +183,9 @@ public class FstDbLoader implements IWaveformDbLoader, IFstDatabaseBuilder {
pcs.removePropertyChangeListener(l);
}
public void getEvents(int id, int width, IEventList values) {
public synchronized void getEvents(int id, int width, IEventList values) {
com.minres.scviewer.database.ReadCancellation.check();
if (parser == null) throw new IllegalStateException("FST recording is closed");
if(values instanceof EventList)
parser.getValueChanges(id, width, timeScaleFactor, (EventList) values);
}
@@ -30,9 +30,9 @@ class FstFileParser {
this.file=file;
}
public boolean open(IFstDatabaseBuilder builder) {
public synchronized boolean open(IFstDatabaseBuilder builder) {
fst = FstLibrary.fstReaderOpen(file.getAbsolutePath());
if(!fst.equals(Pointer.NULL)) {
if(fst != null && !fst.equals(Pointer.NULL)) {
// String version = FstLibrary.fstReaderGetVersionString(fst);
long endTime = FstLibrary.fstReaderGetEndTime(fst);
byte timeScale = FstLibrary.fstReaderGetTimescale(fst);
@@ -76,7 +76,8 @@ class FstFileParser {
return false;
}
public void getValueChanges(final int id, final int width, long timeScale, final EventList values) {
public synchronized void getValueChanges(final int id, final int width, long timeScale, final EventList values) {
if (fst == null) throw new IllegalStateException("FST reader is closed");
FstLibrary.fstReaderClrFacProcessMaskAll(fst);
FstLibrary.fstReaderSetFacProcessMask(fst, id);
FstLibrary.iterateValueChanges(fst, new ValueChangeCallback() {
@@ -86,8 +87,11 @@ class FstFileParser {
}
});
}
public void close() {
public synchronized void close() {
if (fst != null) {
FstLibrary.fstReaderClose(fst);
fst = null;
}
}
}
@@ -35,7 +35,7 @@ abstract class AbstractTxStream extends HierNode implements IWaveform, ITransact
@Override
public List<ITx> getTransactionList() {
return transactionList.get(() -> TransactionLists.fromEvents(getEvents(), () -> false));
return transactionList.get(() -> TransactionLists.fromEvents(getEvents(), () -> { com.minres.scviewer.database.ReadCancellation.check(); return false; }));
}
@Override
@@ -132,7 +132,9 @@ abstract class AbstractTxStream extends HierNode implements IWaveform, ITransact
public RelationType getRelationType(String name) {
RelationType relType=RelationTypeFactory.create(name);
if(!usedRelationsList.contains(relType)) usedRelationsList.add(relType);
synchronized (usedRelationsList) {
if (!usedRelationsList.contains(relType)) usedRelationsList.add(relType);
}
return relType;
}
@@ -106,37 +106,39 @@ public class Tx implements ITx {
}
@Override
public Collection<ITxRelation> getIncomingRelations() {
public synchronized Collection<ITxRelation> getIncomingRelations() {
if(incoming==null){
SQLiteDatabaseSelectHandler<ScvTxRelation> handler = new SQLiteDatabaseSelectHandler<>(
ScvTxRelation.class, database, "sink="+scvTx.getId());
try {
incoming = new ArrayList<>();
for(ScvTxRelation scvRelation:handler.selectObjects()){
incoming.add(createRelation(scvRelation, false));
ITxRelation relation = createRelation(scvRelation, false);
if (relation != null) incoming.add(relation);
}
} catch (SecurityException | IllegalArgumentException | InstantiationException | IllegalAccessException
| InvocationTargetException | SQLException | IntrospectionException | NoSuchMethodException e) {
}
}
return incoming;
return List.copyOf(incoming);
}
@Override
public Collection<ITxRelation> getOutgoingRelations() {
public synchronized Collection<ITxRelation> getOutgoingRelations() {
if(outgoing==null){
SQLiteDatabaseSelectHandler<ScvTxRelation> handler = new SQLiteDatabaseSelectHandler<>(
ScvTxRelation.class, database, "src="+scvTx.getId());
try {
outgoing = new ArrayList<>();
for(ScvTxRelation scvRelation:handler.selectObjects()){
outgoing.add(createRelation(scvRelation, true));
ITxRelation relation = createRelation(scvRelation, true);
if (relation != null) outgoing.add(relation);
}
} catch (SecurityException | IllegalArgumentException | InstantiationException | IllegalAccessException
| InvocationTargetException | SQLException | IntrospectionException | NoSuchMethodException e) {
}
}
return outgoing;
return List.copyOf(outgoing);
}
private ITxRelation createRelation(ScvTxRelation rel, boolean outgoing) {
@@ -36,7 +36,7 @@ abstract class AbstractTxStream extends HierNode implements IWaveform, ITransact
@Override
public List<ITx> getTransactionList() {
return transactionList.get(() -> TransactionLists.fromEvents(getEvents(), () -> false));
return transactionList.get(() -> TransactionLists.fromEvents(getEvents(), () -> { com.minres.scviewer.database.ReadCancellation.check(); return false; }));
}
@Override
@@ -0,0 +1,85 @@
/*******************************************************************************
* 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.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import com.minres.scviewer.database.ReadCancellation;
import com.minres.scviewer.database.WaveformAccess;
import com.minres.scviewer.database.tx.ITx;
import com.minres.scviewer.database.tx.ITxAttribute;
import com.minres.scviewer.database.tx.ITxRelation;
/** UI-owned, bounded snapshots. Accessors never call recording code on the UI thread. */
public final class AsyncTransactionData implements AutoCloseable {
public record Snapshot(List<ITxAttribute> attributes, List<ITxRelation> incoming, List<ITxRelation> outgoing) { }
private static final Snapshot EMPTY = new Snapshot(List.of(), List.of(), List.of());
private final Map<ITx, Snapshot> values = new IdentityHashMap<>();
private final Map<ITx, Job> jobs = new IdentityHashMap<>();
private final java.util.ArrayDeque<ITx> order = new java.util.ArrayDeque<>();
private final boolean relations;
private final Consumer<Runnable> dispatch;
private final Consumer<ITx> changed;
private volatile boolean closed;
public AsyncTransactionData(Consumer<Runnable> dispatch, Consumer<ITx> changed) {
this(dispatch, changed, true);
}
public AsyncTransactionData(Consumer<Runnable> dispatch, Consumer<ITx> changed, boolean relations) {
this.relations = relations;
this.dispatch = dispatch; this.changed = changed;
}
public Snapshot get(ITx tx) {
if (closed || tx == null) return EMPTY;
Snapshot value = values.get(tx);
if (value != null) return value;
if (!jobs.containsKey(tx)) {
Job job = new Job("Load transaction details") {
@Override protected IStatus run(org.eclipse.core.runtime.IProgressMonitor monitor) {
try {
Snapshot loaded = ReadCancellation.with(() -> closed || monitor.isCanceled(),
() -> WaveformAccess.read(tx.getStream(), () -> new Snapshot(List.copyOf(tx.getAttributes()),
relations ? List.copyOf(tx.getIncomingRelations()) : List.of(),
relations ? List.copyOf(tx.getOutgoingRelations()) : List.of())));
dispatch.accept(() -> {
if (closed || jobs.get(tx) != this) return;
jobs.remove(tx);
if (values.size() >= 512) values.remove(order.removeFirst());
values.put(tx, loaded); order.addLast(tx);
changed.accept(tx);
});
return Status.OK_STATUS;
} catch (java.util.concurrent.CancellationException e) {
dispatch.accept(() -> { if (!closed && jobs.get(tx) == this) jobs.remove(tx); });
return Status.CANCEL_STATUS;
} catch (RuntimeException e) {
dispatch.accept(() -> {
if (!closed && jobs.get(tx) == this) { jobs.remove(tx); values.put(tx, EMPTY); order.addLast(tx); changed.accept(tx); }
});
return new Status(IStatus.ERROR, "com.minres.scviewer.database.ui.swt", "Cannot load transaction details", e);
} finally { monitor.done(); }
}
};
jobs.put(tx, job); job.setSystem(true); job.schedule();
}
return EMPTY;
}
public boolean isReady(ITx tx) { return values.containsKey(tx); }
@Override public void close() {
closed = true;
jobs.values().forEach(Job::cancel);
jobs.clear(); values.clear(); order.clear();
}
}
@@ -11,9 +11,7 @@
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. */
@@ -23,9 +21,7 @@ public final class 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);
return track.waveform.isBitVector();
}
public static List<TrackEntry> selectedBits(List<TrackEntry> roots, List<TrackEntry> selection) {
@@ -39,6 +39,7 @@ public final class BitWaveform extends HierNode implements IWaveform {
@Override public String getFullName() { return source.getFullName() + getName(); }
@Override public String getDisplayName() { return source.getDisplayName() + getName(); }
@Override public java.util.List<IWaveform> getReadSources() { return java.util.List.of(source); }
public IWaveform getSource() { return source; }
public int getBitIndex() { return bit; }
@Override public DirectionType getDirection() { return source.getDirection(); }
@@ -16,8 +16,6 @@ import java.util.List;
import com.minres.scviewer.database.EmptyWaveform;
import com.minres.scviewer.database.IWaveform;
import com.minres.scviewer.database.BitVector;
import com.minres.scviewer.database.EventEntry;
import com.minres.scviewer.database.WaveformType;
public class TrackEntry {
@@ -94,9 +92,7 @@ public class TrackEntry {
}
private static boolean isBitVector(IWaveform waveform) {
if (waveform == null || waveform.getType() != WaveformType.SIGNAL || waveform.getWidth() <= 1) return false;
EventEntry first = waveform.getEvents().firstEntry();
return first != null && first.events != null && first.events.length > 0 && first.events[0] instanceof BitVector;
return waveform != null && waveform.getWidth() > 1 && waveform.isBitVector();
}
public boolean isExpandable() {
@@ -0,0 +1,25 @@
/*******************************************************************************
* 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 org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.widgets.Display;
/** Enqueue against a captured display, tolerating disposal during submission. */
public final class UiDispatch {
private UiDispatch() { }
public static void async(Display display, Runnable action) {
if (display.isDisposed()) return;
try { display.asyncExec(() -> { if (!display.isDisposed()) action.run(); }); }
catch (SWTException e) { if (e.code != SWT.ERROR_DEVICE_DISPOSED) throw e; }
}
}
@@ -80,7 +80,7 @@ public class ArrowPainter implements IPainter {
}
private int getConcurrencyIndex(ITx tx) {
IEvent[] eventList = tx.getStream().getEventsBeforeTime(tx.getBeginTime());
IEvent[] eventList = waveCanvas.value(tx.getStream(), tx.getBeginTime());
Optional<Integer> res = Arrays.stream(eventList).filter(e -> ((ITxEvent)e).getTransaction()== tx).map(e -> ((ITxEvent)e).getRowIndex()).findFirst();
if(res.isPresent() && res.get()>0) {
return res.get();
@@ -89,10 +89,10 @@ public class ArrowPainter implements IPainter {
}
private Rectangle getBoundingBox(IWaveformPainter painter, ITx itx, IWaveform stream) {
int laneHeight = painter.getHeight() / stream.getRowCount();
int laneHeight = painter.getHeight() / waveCanvas.rows(stream);
//TODO: it needs to take the concurrency index within the current waveform (stream or generator) into account
int concIdx=getConcurrencyIndex(itx);
int laneOffset = laneHeight * (concIdx>=stream.getRowCount()?stream.getRowCount()-1:concIdx);
int laneOffset = laneHeight * (concIdx>=waveCanvas.rows(stream)?waveCanvas.rows(stream)-1:concIdx);
int rulerHeight = waveCanvas.rulerHeight;
Rectangle bb = new Rectangle((int) (itx.getBeginTime() / scaleFactor),
rulerHeight + painter.getVerticalOffset() + laneOffset,
@@ -115,8 +115,8 @@ public class ArrowPainter implements IPainter {
}
Rectangle bb = getBoundingBox(painter, tx, painter instanceof StreamPainter? ((StreamPainter)painter).getStream() : tx.getStream());
txRectangle = bb;
deriveGeom(tx.getIncomingRelations(), iRect, false);
deriveGeom(tx.getOutgoingRelations(), oRect, true);
deriveGeom(waveCanvas.transactionData.get(tx).incoming(), iRect, false);
deriveGeom(waveCanvas.transactionData.get(tx).outgoing(), oRect, true);
return false;
}
@@ -103,18 +103,18 @@ public class SignalPainter extends TrackPainter {
long beginTime = beginPos*scaleFactor;
long endTime = beginTime + area.width*scaleFactor;
EventEntry first = signal.getEvents().floorEntry(beginTime);
EventEntry first = waveCanvas.events(signal).floorEntry(beginTime);
if (first == null)
first = signal.getEvents().firstEntry();
first = waveCanvas.events(signal).firstEntry();
if (first == null || Long.compareUnsigned(first.timestamp, endTime) > 0) return;
beginTime = first.timestamp;
proj.setForeground(this.waveCanvas.styleProvider.getColor(WaveformColors.LINE));
proj.setLineStyle(SWT.LINE_SOLID);
proj.setLineWidth(1);
IEventList entries = signal.getEvents().subMap(beginTime, true, endTime);
IEventList entries = waveCanvas.events(signal).subMap(beginTime, true, endTime);
if (entries.isEmpty()) return;
SignalChange left = new SignalChange(entries.firstEntry());
SignalChange right = new SignalChange(entries.size() > 1 ? entries.higherEntry(left.time) : entries.firstEntry());
SignalChange right = new SignalChange(entries.higherEntry(left.time) != null ? entries.higherEntry(left.time) : entries.firstEntry());
maxPosX = area.x + area.width;
yOffsetT = this.waveCanvas.styleProvider.getTrackHeight() / 5 + area.y;
yOffsetM = this.waveCanvas.styleProvider.getTrackHeight() / 2 + area.y;
@@ -18,7 +18,6 @@ import org.eclipse.swt.graphics.Rectangle;
import com.minres.scviewer.database.EventKind;
import com.minres.scviewer.database.IEvent;
import com.minres.scviewer.database.IEventList;
import com.minres.scviewer.database.IWaveform;
import com.minres.scviewer.database.tx.ITx;
import com.minres.scviewer.database.tx.ITxEvent;
@@ -35,9 +34,6 @@ public class StreamPainter extends TrackPainter{
private IWaveform stream;
private int txBase;
private int txHeight;
private TxIntervalIndex intervalIndex;
private IEventList indexedEvents;
private int indexedSize = -1;
public StreamPainter(WaveformCanvas waveCanvas, boolean even, TrackEntry trackEntry) {
super(trackEntry, even);
@@ -46,8 +42,8 @@ public class StreamPainter extends TrackPainter{
}
public void paintArea(Projection proj, Rectangle area) {
int trackHeight=trackEntry.height/stream.getRowCount();
if(stream.getEvents().size()==0) {
int trackHeight=trackEntry.height/waveCanvas.rows(stream);
if(waveCanvas.events(stream).size()==0) {
proj.setFillRule(SWT.FILL_EVEN_ODD);
proj.setLineStyle(SWT.LINE_SOLID);
proj.setLineWidth(1);
@@ -79,7 +75,9 @@ public class StreamPainter extends TrackPainter{
for( int y1=area.y+trackHeight/2; y1<area.y+trackEntry.height; y1+=trackHeight)
proj.drawLine(area.x, y1, area.x+area.width, y1);
ITxEvent highlighted = null;
for (ITxEvent event : getIntervalIndex().overlapping(beginTime, endTime)) {
TxIntervalIndex index = getIntervalIndex();
if (index == null) return;
for (ITxEvent event : index.overlapping(beginTime, endTime)) {
ITx tx = event.getTransaction();
drawTx(proj, area, tx, event.getRowIndex(), false);
if (waveCanvas.currentSelectedTx != null && waveCanvas.currentSelectedTx.getId() == tx.getId())
@@ -91,16 +89,7 @@ public class StreamPainter extends TrackPainter{
}
}
private TxIntervalIndex getIntervalIndex() {
stream.getRowCount();
IEventList events = stream.getEvents();
if (intervalIndex == null || indexedEvents != events || indexedSize != events.size()) {
intervalIndex = new TxIntervalIndex(events);
indexedEvents = events;
indexedSize = events.size();
}
return intervalIndex;
}
private TxIntervalIndex getIntervalIndex() { return waveCanvas.intervals(stream); }
protected void drawTx(Projection proj, Rectangle area, ITx tx, int concurrencyIndex, boolean highlighted ) {
// compute colors
@@ -140,7 +129,9 @@ public class StreamPainter extends TrackPainter{
long time = (long) point.x * scale;
long low = Math.max(0L, (long) point.x - 5) * scale;
long high = ((long) point.x + 5) * scale;
for (ITxEvent event : getIntervalIndex().overlapping(low, high)) {
TxIntervalIndex index = getIntervalIndex();
if (index == null) return null;
for (ITxEvent event : index.overlapping(low, high)) {
if (event.getRowIndex() != lane) continue;
ITx tx = event.getTransaction();
if (event.getKind() == EventKind.SINGLE ||
@@ -155,8 +146,6 @@ public class StreamPainter extends TrackPainter{
public void setStream(IWaveform stream) {
this.stream = stream;
intervalIndex = null;
indexedEvents = null;
}
protected ITx getTxFromEntry(int lane, int offset, IEvent[] firstTx) {
@@ -51,6 +51,32 @@ import com.minres.scviewer.database.ui.swt.Constants;
import com.minres.scviewer.database.ui.swt.internal.slider.ZoomBar;
public class WaveformCanvas extends Canvas implements IWaveformZoom{
private final WaveformData data;
final org.eclipse.swt.widgets.Display uiDisplay;
final com.minres.scviewer.database.ui.AsyncTransactionData transactionData;
Runnable dataChanged = () -> redraw();
com.minres.scviewer.database.IEventList events(IWaveform waveform) {
return data.events(waveform, Math.max(0, getMinVisibleTime()), getMaxVisibleTime(), Math.max(1, getScale()));
}
com.minres.scviewer.database.IEvent[] value(IWaveform waveform, long time) {
EventEntry entry = data.events(waveform, time, time, 1).floorEntry(time);
return entry == null ? new IEvent[0] : entry.events;
}
void retainData(List<TrackEntry> tracks) {
java.util.Set<IWaveform> retained = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>());
collectWaveforms(tracks, retained);
data.retain(retained);
}
private void collectWaveforms(List<TrackEntry> tracks, java.util.Set<IWaveform> retained) {
for (TrackEntry track : tracks) {
if (track.waveform != null) retained.add(track.waveform);
collectWaveforms(track.waveforms, retained);
}
}
int rows(IWaveform waveform) { return data.rows(waveform); }
com.minres.scviewer.database.tx.TxIntervalIndex intervals(IWaveform waveform) { return data.intervals(waveform); }
public static final long ZOOM_FIT = -2;
@@ -106,6 +132,14 @@ public class WaveformCanvas extends Canvas implements IWaveformZoom{
public WaveformCanvas(final Composite parent, int style, IWaveformStyleProvider styleProvider, ZoomBar.IProvider scrollbarProvider) {
super(parent, (style & ~SWT.H_SCROLL) | SWT.DOUBLE_BUFFERED | SWT.NO_BACKGROUND | SWT.V_SCROLL );
var display = parent.getDisplay();
uiDisplay = display;
java.util.function.Consumer<Runnable> dispatch = task -> com.minres.scviewer.database.ui.UiDispatch.async(display, task);
data = new WaveformData(dispatch, () -> { if (!isDisposed()) dataChanged.run(); });
transactionData = new com.minres.scviewer.database.ui.AsyncTransactionData(dispatch, tx -> {
if (!isDisposed()) { if (arrowPainter != null) arrowPainter.updateSelection(); redraw(); }
});
addDisposeListener(event -> { data.close(); transactionData.close(); });
this.styleProvider=styleProvider;
addControlListener(new ControlAdapter() { /* resize listener. */
@Override
@@ -321,7 +355,7 @@ public class WaveformCanvas extends Canvas implements IWaveformZoom{
setScalingFactor(factor, lowerTime+time_diff/2);
} else {
origin.x = -(int) (lowerTime/getScale());
WaveformCanvas.this.getDisplay().asyncExec(() -> {redraw();});
WaveformCanvas.this.getDisplay().asyncExec(() -> { if (!isDisposed()) redraw(); });
}
lastHorSelection=sel;
}
@@ -339,7 +373,7 @@ public class WaveformCanvas extends Canvas implements IWaveformZoom{
if (!painterList.isEmpty()) {
origin.y=-vertical.getSelection();
fireSelectionEvent();
WaveformCanvas.this.getDisplay().asyncExec(() -> {redraw();});
WaveformCanvas.this.getDisplay().asyncExec(() -> { if (!isDisposed()) redraw(); });
}
}
});
@@ -475,20 +509,21 @@ public class WaveformCanvas extends Canvas implements IWaveformZoom{
setOrigin(size.x - higher, origin.y);
}
if(currentSelectedTrack != null) {
EventEntry entry = currentSelectedTrack.waveform.getEvents().floorEntry(tx.getBeginTime());
EventEntry entry = events(currentSelectedTrack.waveform).floorEntry(tx.getBeginTime());
IWaveformPainter painter = trackAreaPainter.getPainterFor(currentSelectedTrack);
if (painter != null && painter instanceof StreamPainter)
reveal(tx, size, painter, entry);
} else
for (IWaveformPainter painter : wave2painterMap.values()) {
if (painter instanceof StreamPainter && ((StreamPainter) painter).getStream() == tx.getStream()) {
EventEntry entry = tx.getStream().getEvents().floorEntry(tx.getBeginTime());
EventEntry entry = events(tx.getStream()).floorEntry(tx.getBeginTime());
reveal(tx, size, painter, entry);
}
}
}
private void reveal(ITx tx, Point size, IWaveformPainter painter, EventEntry entry) {
if (entry == null) return;
Optional<IEvent> res = Arrays.stream(entry.events).filter(e -> ((ITxEvent)e).getTransaction().equals(tx)).findFirst();
if(res.isPresent()) {
int top = painter.getVerticalOffset() + styleProvider.getTrackHeight() * ((ITxEvent)res.get()).getRowIndex();
@@ -0,0 +1,145 @@
/*******************************************************************************
* 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.swt.internal;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import com.minres.scviewer.database.*;
import com.minres.scviewer.database.ui.BitWaveform;
import com.minres.scviewer.database.tx.TxIntervalIndex;
/** UI-owned snapshots of recording data. Painting never triggers a lazy read. */
final class WaveformData implements AutoCloseable {
private record Request(IWaveform waveform, long from, long to, long step) { }
private record Snapshot(IEventList events, int rows, TxIntervalIndex intervals) { }
private static final IEventList EMPTY = new EventList();
private final Map<Request, Snapshot> values = new LinkedHashMap<>(32, .75f, true);
private final Map<Request, Job> jobs = new LinkedHashMap<>();
private final Consumer<Runnable> dispatch;
private final Runnable changed;
private volatile boolean closed;
WaveformData(Consumer<Runnable> dispatch, Runnable changed) { this.dispatch = dispatch; this.changed = changed; }
private static boolean derived(IWaveform waveform) {
while (waveform instanceof BitWaveform bit) waveform = bit.getSource();
return waveform instanceof CombinedBitVectorWaveform;
}
IEventList events(IWaveform waveform, long from, long to, long step) {
Snapshot value = request(waveform, from, to, step);
return value == null ? EMPTY : value.events();
}
int rows(IWaveform waveform) {
if (!waveform.getType().isTransaction()) return 1;
Snapshot value = request(waveform, 0, -1L, 0);
return value == null ? 1 : Math.max(1, value.rows());
}
TxIntervalIndex intervals(IWaveform waveform) {
Snapshot value = request(waveform, 0, -1L, 0);
return value == null ? null : value.intervals();
}
private Snapshot request(IWaveform waveform, long from, long to, long step) {
if (closed) return null;
boolean sample = derived(waveform);
if (!sample) { from = 0; to = -1L; step = 0; }
// Metadata callers do not request an unbounded derived timeline.
else if (step == 0) return null;
Request request = new Request(waveform, from, to, Math.max(0, step));
Snapshot value = values.get(request);
if (value != null) return value;
if (!jobs.containsKey(request)) {
// Supersede obsolete ranges and cursor samples independently.
if (sample) {
var stale = jobs.entrySet().iterator();
while (stale.hasNext()) {
var entry = stale.next();
if (entry.getKey().waveform() == waveform
&& (entry.getKey().from() == entry.getKey().to()) == (request.from() == request.to())) {
entry.getValue().cancel(); stale.remove();
}
}
}
Job job = new Job("Prepare waveform") {
@Override protected IStatus run(IProgressMonitor monitor) {
try {
Snapshot loaded = ReadCancellation.with(() -> closed || monitor.isCanceled(),
() -> WaveformAccess.read(waveform, () -> {
IEventList events = waveform.getEvents();
IEventList ready = sample ? sample(events, request) : events;
int rows = waveform.getRowCount();
return new Snapshot(ready, rows, waveform.getType().isTransaction() ? new TxIntervalIndex(ready) : null);
}));
if (closed || monitor.isCanceled()) return Status.CANCEL_STATUS;
dispatch.accept(() -> {
if (closed || jobs.get(request) != this) return;
jobs.remove(request);
values.put(request, loaded);
if (sample) {
long count = values.keySet().stream().filter(key -> key.waveform() == waveform).count();
var old = values.keySet().iterator();
while (count > 8 && old.hasNext()) {
if (old.next().waveform() == waveform) { old.remove(); count--; }
}
}
changed.run();
});
return Status.OK_STATUS;
} catch (java.util.concurrent.CancellationException e) {
dispatch.accept(() -> { if (!closed && jobs.get(request) == this) jobs.remove(request); });
return Status.CANCEL_STATUS;
} catch (RuntimeException e) {
dispatch.accept(() -> {
if (!closed && jobs.get(request) == this) { jobs.remove(request); values.put(request, new Snapshot(EMPTY, 1, null)); changed.run(); }
});
return new Status(IStatus.ERROR, "com.minres.scviewer.database.ui.swt", "Cannot prepare waveform", e);
} finally { monitor.done(); }
}
};
jobs.put(request, job); job.setSystem(true); job.schedule();
}
return null;
}
/** At most a few samples per pixel, preserving boundaries and dense-change markers. */
private static IEventList sample(IEventList input, Request request) {
EventList result = new EventList();
add(result, input.floorEntry(request.from()));
for (long time = request.from(); Long.compareUnsigned(time, request.to()) <= 0;) {
ReadCancellation.check();
add(result, input.floorEntry(time));
add(result, input.ceilingEntry(time));
long next = time + Math.max(1, request.step());
if (Long.compareUnsigned(next, time) <= 0) break;
time = next;
}
add(result, input.floorEntry(request.to()));
return result;
}
private static void add(EventList result, EventEntry entry) {
if (entry != null && entry.events != null && !result.containsKey(entry.timestamp))
for (IEvent event : entry.events) result.put(entry.timestamp, event);
}
void retain(java.util.Set<IWaveform> waveforms) {
values.keySet().removeIf(request -> !waveforms.contains(request.waveform()));
var pending = jobs.entrySet().iterator();
while (pending.hasNext()) {
var entry = pending.next();
if (!waveforms.contains(entry.getKey().waveform())) { entry.getValue().cancel(); pending.remove(); }
}
}
@Override public void close() {
closed = true;
jobs.values().forEach(Job::cancel); jobs.clear(); values.clear();
}
}
@@ -311,11 +311,11 @@ public class WaveformView implements IWaveformView {
EventEntry ceilEntry = null;
if (o instanceof TrackEntry) {
TrackEntry entry = (TrackEntry) o;
IEventList map = entry.waveform.getEvents();
IEventList map = waveformCanvas.events(entry.waveform);
floorEntry = map.floorEntry(time);
ceilEntry = map.ceilingEntry(time);
} else if (o instanceof ITx) {
IEventList map = ((ITx) o).getStream().getEvents();
IEventList map = waveformCanvas.events(((ITx) o).getStream());
floorEntry = map.floorEntry(time);
ceilEntry = map.ceilingEntry(time);
}
@@ -512,6 +512,7 @@ public class WaveformView implements IWaveformView {
valueFill = createFill(valuePane);
waveformCanvas.setMaxTime(1);
waveformCanvas.dataChanged = this::update;
waveformCanvas.addPaintListener(waveformMouseListener);
waveformCanvas.addListener(SWT.MouseDown, waveformMouseListener);
waveformCanvas.addListener(SWT.MouseUp, waveformMouseListener);
@@ -632,6 +633,7 @@ public class WaveformView implements IWaveformView {
public void update() {
if (waveformCanvas.isDisposed()) return;
updateQueued = false;
waveformCanvas.retainData(streams);
setStreamDropLocation(null);
int scrollY = -waveformCanvas.getOrigin().y;
layoutInProgress = true;
@@ -728,7 +730,7 @@ public class WaveformView implements IWaveformView {
streamEntry.vOffset = tracksVerticalHeight;
if (streamEntry.waveform.getType().isTransaction()) {
streamEntry.currentValue = "";
streamEntry.height *= streamEntry.waveform.getRowCount();
streamEntry.height *= waveformCanvas.rows(streamEntry.waveform);
IWaveformPainter painter = new StreamPainter(waveformCanvas, even, streamEntry);
waveformCanvas.addWaveformPainter(painter, false);
} else if (streamEntry.waveform.getType() == WaveformType.SIGNAL) {
@@ -756,7 +758,7 @@ public class WaveformView implements IWaveformView {
final Long time = getCursorTime();
TrackEntry.visibleTracks(streams).stream().forEach(entry -> {
if (entry.waveform.getType() == WaveformType.SIGNAL) {
IEvent[] value = entry.waveform.getEventsBeforeTime(time);
IEvent[] value = waveformCanvas.value(entry.waveform, time);
if (value == null || value.length == 0) {
entry.currentValue = "---";
return;
@@ -788,8 +790,8 @@ public class WaveformView implements IWaveformView {
entry.currentValue = Double.toString(val);
}
} else if (entry.waveform.getType().isTransaction()) {
ITx[] resultsList = new ITx[entry.waveform.getRowCount()];
EventEntry firstTx = entry.waveform.getEvents().floorEntry(time);
ITx[] resultsList = new ITx[waveformCanvas.rows(entry.waveform)];
EventEntry firstTx = waveformCanvas.events(entry.waveform).floorEntry(time);
if (firstTx != null) {
do {
for (IEvent e : firstTx.events) {
@@ -802,7 +804,7 @@ public class WaveformView implements IWaveformView {
resultsList[evt.getRowIndex()] = evt.getTransaction();
}
}
firstTx = entry.waveform.getEvents().lowerEntry(firstTx.timestamp);
firstTx = waveformCanvas.events(entry.waveform).lowerEntry(firstTx.timestamp);
} while (firstTx != null && !isArrayFull(resultsList));
boolean separator = false;
StringBuilder sb = new StringBuilder();
@@ -1028,11 +1030,13 @@ public class WaveformView implements IWaveformView {
return;
TrackEntry selectedWaveform = currentWaveformSelection.size() == 1 ? currentWaveformSelection.get(0)
: getEntryFor(currentTxSelection);
if (selectedWaveform == null) return;
if (selectedWaveform.waveform.getType().isTransaction() && currentTxSelection != null) {
if (relationType.equals(IWaveformView.NEXT_PREV_IN_STREAM)) {
ITx transaction = null;
if (direction == GotoDirection.NEXT) {
IEvent[] eventsList = selectedWaveform.waveform.getEvents().get(currentTxSelection.getBeginTime());
IEvent[] eventsList = waveformCanvas.events(selectedWaveform.waveform).get(currentTxSelection.getBeginTime());
if (eventsList == null) return;
boolean meFound = false;
for (IEvent evt : eventsList) {
if (evt instanceof ITxEvent && evt.getKind() == EventKind.BEGIN
@@ -1045,7 +1049,7 @@ public class WaveformView implements IWaveformView {
}
}
if (transaction == null) {
EventEntry entry = selectedWaveform.waveform.getEvents()
EventEntry entry = waveformCanvas.events(selectedWaveform.waveform)
.higherEntry(currentTxSelection.getBeginTime());
if (entry != null)
do {
@@ -1057,11 +1061,12 @@ public class WaveformView implements IWaveformView {
}
}
if (transaction == null)
entry = selectedWaveform.waveform.getEvents().higherEntry(entry.timestamp);
entry = waveformCanvas.events(selectedWaveform.waveform).higherEntry(entry.timestamp);
} while (entry != null && transaction == null);
}
} else if (direction == GotoDirection.PREV) {
IEvent[] eventsList = selectedWaveform.waveform.getEvents().get(currentTxSelection.getBeginTime());
IEvent[] eventsList = waveformCanvas.events(selectedWaveform.waveform).get(currentTxSelection.getBeginTime());
if (eventsList == null) return;
boolean meFound = false;
for (IEvent evt : Lists.reverse(Arrays.asList(eventsList))) {
if (evt instanceof ITxEvent
@@ -1074,7 +1079,7 @@ public class WaveformView implements IWaveformView {
}
}
if (transaction == null) {
EventEntry entry = selectedWaveform.waveform.getEvents()
EventEntry entry = waveformCanvas.events(selectedWaveform.waveform)
.lowerEntry(currentTxSelection.getBeginTime());
if (entry != null)
do {
@@ -1086,7 +1091,7 @@ public class WaveformView implements IWaveformView {
}
}
if (transaction == null)
entry = selectedWaveform.waveform.getEvents().lowerEntry(entry.timestamp);
entry = waveformCanvas.events(selectedWaveform.waveform).lowerEntry(entry.timestamp);
} while (entry != null && transaction == null);
}
}
@@ -1096,12 +1101,12 @@ public class WaveformView implements IWaveformView {
} else {
ITxRelation tx = null;
if (direction == GotoDirection.NEXT) {
Collection<ITxRelation> outRel = currentTxSelection.getOutgoingRelations();
Collection<ITxRelation> outRel = waveformCanvas.transactionData.get(currentTxSelection).outgoing();
tx = selectTxToNavigateTo(outRel, relationType, true);
if (tx != null)
setSelection(new StructuredSelection(tx.getTarget()), true);
} else if (direction == GotoDirection.PREV) {
Collection<ITxRelation> inRel = currentTxSelection.getIncomingRelations();
Collection<ITxRelation> inRel = waveformCanvas.transactionData.get(currentTxSelection).incoming();
tx = selectTxToNavigateTo(inRel, relationType, false);
if (tx != null)
setSelection(new StructuredSelection(tx.getSource()), true);
@@ -1152,7 +1157,7 @@ public class WaveformView implements IWaveformView {
long time = getCursorTime();
IEventList map = null;
if (sel.waveform.getType().isTransaction() || sel.waveform.getType() == WaveformType.SIGNAL) {
map = sel.waveform.getEvents();
map = waveformCanvas.events(sel.waveform);
}
if (map != null) {
EventEntry entry = direction == GotoDirection.PREV ? map.lowerEntry(time) : map.higherEntry(time);
@@ -1242,13 +1247,13 @@ public class WaveformView implements IWaveformView {
if (lastKey.equals(firstKey)) {
TrackEntry trackEntry = trackVerticalOffset.get(firstKey);
IWaveform w = trackEntry.waveform;
subArea.height = w.getRowCount() * styleProvider.getTrackHeight();
subArea.height = waveformCanvas.rows(w) * styleProvider.getTrackHeight();
drawValue(gc, subArea, firstKey, trackEntry.currentValue, trackEntry.selected);
} else {
for (Entry<Integer, TrackEntry> entry : trackVerticalOffset.subMap(firstKey, true, lastKey, true)
.entrySet()) {
IWaveform w = entry.getValue().waveform;
subArea.height = w.getRowCount() * styleProvider.getTrackHeight();
subArea.height = waveformCanvas.rows(w) * styleProvider.getTrackHeight();
drawValue(gc, subArea, entry.getKey(), entry.getValue().currentValue,
entry.getValue().selected);
}
@@ -1260,7 +1265,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();
subArea.height = waveformCanvas.rows(w) * styleProvider.getTrackHeight();
drawTextFormat(gc, subArea, firstKey, w.getDisplayName(), entry.selected, entry.hierState, nameIndent(entry));
}
@@ -1709,7 +1714,9 @@ public class WaveformView implements IWaveformView {
}
public void asyncUpdate(Widget widget) {
widget.getDisplay().asyncExec(() -> {
if (widget.isDisposed()) return;
com.minres.scviewer.database.ui.UiDispatch.async(waveformCanvas.uiDisplay, () -> {
if (widget.isDisposed() || waveformCanvas.isDisposed()) return;
waveformCanvas.redraw();
updateValueList();
});
@@ -19,6 +19,7 @@ public class ActionTimer implements Runnable {
private final Display display;
private final TimerAction timerAction;
private boolean active;
public interface TimerAction extends Runnable {
boolean isEnabled();
@@ -30,16 +31,22 @@ public class ActionTimer implements Runnable {
}
public void activate() {
if( timerAction.isEnabled() ) {
if (!display.isDisposed() && timerAction.isEnabled()) {
active = true;
display.timerExec( INITIAL_DELAY, this );
}
}
public void cancel() {
active = false;
if (!display.isDisposed()) display.timerExec(-1, this);
}
@Override
public void run() {
if( timerAction.isEnabled() ) {
if (active && !display.isDisposed() && timerAction.isEnabled()) {
timerAction.run();
display.timerExec( FAST_DELAY, this );
if (active && !display.isDisposed() && timerAction.isEnabled()) display.timerExec(FAST_DELAY, this);
}
}
}
@@ -46,11 +46,13 @@ public class ImageButton extends Composite
}
@Override
public boolean isEnabled() {
return pressed;
return !isDisposed() && pressed;
}
};
actionTimer = new ActionTimer(timerAction, this.getDisplay() );
addListener(SWT.Dispose, event -> {
pressed = false;
actionTimer.cancel();
if (hoverImage != null) hoverImage.dispose();
if (normalImage != null) normalImage.dispose();
if (pressedImage != null) pressedImage.dispose();
@@ -87,6 +89,7 @@ public class ImageButton extends Composite
@Override
public void mouseUp(MouseEvent e) {
pressed=false;
actionTimer.cancel();
redraw();
}
});
@@ -22,7 +22,9 @@ public class ActionScheduler {
this.action = action;
}
public void cancel() { if (!display.isDisposed()) display.timerExec(-1, action); }
public void schedule( int delay ) {
display.timerExec( delay, action );
if (!display.isDisposed()) display.timerExec(delay, action);
}
}
@@ -42,6 +42,7 @@ class ClickControl extends ControlAdapter implements ViewComponent, MouseDownAct
this.control.addMouseTrackListener( this );
this.control.addMouseListener( this );
this.control.addControlListener( this );
control.addDisposeListener(event -> { buttonClick.disarm(); mouseDownActionTimer.cancel(); });
}
@Override
@@ -73,7 +74,7 @@ class ClickControl extends ControlAdapter implements ViewComponent, MouseDownAct
@Override
public boolean isEnabled() {
return true;
return !control.isDisposed() && control.isEnabled();
}
@Override
@@ -18,6 +18,7 @@ public class MouseDownActionTimer implements Runnable {
public static final int FAST_DELAY = 50;
private final ActionScheduler scheduler;
private boolean active;
private final TimerAction timerAction;
private final ButtonClick mouseClick;
@@ -33,15 +34,18 @@ public class MouseDownActionTimer implements Runnable {
public void activate() {
if( timerAction.isEnabled() ) {
active = true;
scheduler.schedule( INITIAL_DELAY );
}
}
public void cancel() { active = false; scheduler.cancel(); }
@Override
public void run() {
if( mouseClick.isArmed() && timerAction.isEnabled() ) {
if( active && mouseClick.isArmed() && timerAction.isEnabled() ) {
timerAction.run();
scheduler.schedule( FAST_DELAY );
if (active && timerAction.isEnabled()) scheduler.schedule(FAST_DELAY);
}
}
}
@@ -65,6 +65,7 @@ public final class CombinedBitVectorWaveform extends HierNode implements IWavefo
this.sources = List.copyOf(normalized);
}
@Override public List<IWaveform> getReadSources() { return sources.stream().map(SourceBit::waveform).toList(); }
public List<SourceBit> getSources() { return sources; }
@Override public String getFullName() { return identifier; }
@Override public String getDisplayName() { return getName(); }
@@ -95,6 +96,7 @@ public final class CombinedBitVectorWaveform extends HierNode implements IWavefo
}
BitValue[] value = new BitValue[getWidth()];
for (int i = 0; i < value.length; i++) {
ReadCancellation.check();
EventEntry entry = inputs().get(i).floorEntry(time);
value[i] = BitValue.X;
if (entry != null && entry.events != null && entry.events.length > 0) {
@@ -112,6 +114,7 @@ public final class CombinedBitVectorWaveform extends HierNode implements IWavefo
private Long candidate(long time, boolean forward, boolean inclusive) {
Long result = null;
for (IEventList input : inputs()) {
ReadCancellation.check();
EventEntry entry = forward ? (inclusive ? input.ceilingEntry(time) : input.higherEntry(time))
: (inclusive ? input.floorEntry(time) : input.lowerEntry(time));
if (entry != null && (result == null || (forward
@@ -138,7 +141,7 @@ public final class CombinedBitVectorWaveform extends HierNode implements IWavefo
break;
}
if (changed(next)) break;
if (Thread.currentThread().isInterrupted()) throw new java.util.concurrent.CancellationException();
ReadCancellation.check();
next = candidate(next, forward, false);
}
synchronized (positions) { positions.put(query, next); }
@@ -22,10 +22,10 @@ import java.util.List;
public class HierNode implements IHierNode {
/** The name. */
protected String name;
protected volatile String name;
/** The parent. */
protected IHierNode parent = null;
protected volatile IHierNode parent = null;
/** The childs. */
protected List<IHierNode> childNodes = Collections.synchronizedList(new ArrayList<>());
@@ -139,7 +139,7 @@ public class HierNode implements IHierNode {
*/
@Override
public List<IHierNode> getChildNodes() {
return Collections.unmodifiableList(childNodes);
synchronized (childNodes) { return List.copyOf(childNodes); }
}
/**
@@ -149,9 +149,11 @@ public class HierNode implements IHierNode {
*/
@Override
public void addChild(IHierNode child) {
synchronized (childNodes) {
if (!childNodes.contains(child)) {
childNodes.add(child);
child.setParent(this);
childNodes.add(child);
}
}
}
@@ -19,6 +19,13 @@ package com.minres.scviewer.database;
*/
public interface IWaveform extends IHierNode {
/** Recorded inputs used to coordinate derived reads with database closure. */
default java.util.List<IWaveform> getReadSources() { return java.util.List.of(this); }
/** Signal metadata; real-valued loaders override this without reading events. */
default boolean isBitVector() { return getType() == WaveformType.SIGNAL && getWidth() > 0; }
/** User-facing label; derived waveforms may have a separate persistent identity. */
default String getDisplayName() { return getFullName(); }
@@ -10,31 +10,45 @@
*******************************************************************************/
package com.minres.scviewer.database;
import java.util.concurrent.CancellationException;
import java.util.function.Supplier;
/** Publishes one complete value, including empty values, and preserves loading failures. */
/** Single-flight lazy initialization. Waiters can cancel without cancelling the owner. */
public final class LazyValue<T> {
private enum State { UNLOADED, LOADING, LOADED, FAILED }
private State state = State.UNLOADED;
private Thread owner;
private T value;
private Throwable failure;
public synchronized T get(Supplier<T> supplier) {
public T get(Supplier<T> supplier) {
synchronized (this) {
while (state == State.LOADING) {
if (owner == Thread.currentThread()) throw new IllegalStateException("Recursive lazy loading");
ReadCancellation.check();
try { wait(50); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CancellationException(); }
}
ReadCancellation.check();
if (state == State.LOADED) return value;
if (state == State.FAILED) {
if (failure instanceof Error) throw (Error) failure;
if (failure instanceof Error error) throw error;
throw (RuntimeException) failure;
}
if (state == State.LOADING) throw new IllegalStateException("Recursive lazy loading");
owner = Thread.currentThread();
state = State.LOADING;
}
try {
T loaded = supplier.get();
value = loaded;
state = State.LOADED;
synchronized (this) { value = loaded; state = State.LOADED; owner = null; notifyAll(); }
return loaded;
} catch (RuntimeException | Error e) {
failure = e;
state = State.FAILED;
synchronized (this) {
if (e instanceof CancellationException) state = State.UNLOADED;
else { failure = e; state = State.FAILED; }
owner = null;
notifyAll();
}
throw e;
}
}
@@ -0,0 +1,32 @@
/*******************************************************************************
* 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;
import java.util.concurrent.CancellationException;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
/** Cancellation context for nested lazy reads without depending on Eclipse jobs. */
public final class ReadCancellation {
private static final ThreadLocal<BooleanSupplier> CURRENT = new ThreadLocal<>();
private ReadCancellation() { }
public static void check() {
BooleanSupplier cancelled = CURRENT.get();
if (Thread.currentThread().isInterrupted() || (cancelled != null && cancelled.getAsBoolean()))
throw new CancellationException();
}
public static <T> T with(BooleanSupplier cancelled, Supplier<T> query) {
BooleanSupplier previous = CURRENT.get();
CURRENT.set(() -> cancelled.getAsBoolean() || (previous != null && previous.getAsBoolean()));
try { check(); return query.get(); }
finally { if (previous == null) CURRENT.remove(); else CURRENT.set(previous); }
}
}
@@ -10,7 +10,7 @@
*******************************************************************************/
package com.minres.scviewer.database;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
/**
* A factory for creating RelationType objects.
@@ -24,14 +24,7 @@ public class RelationTypeFactory {
* @return the relation type
*/
public static RelationType create(String name) {
if (registry.containsKey(name)) {
return registry.get(name);
} else {
RelationType relType = new RelationType(name);
registry.put(name, relType);
return relType;
}
return registry.computeIfAbsent(name, RelationType::new);
}
/**
@@ -41,6 +34,6 @@ public class RelationTypeFactory {
}
/** The registry. */
private static HashMap<String, RelationType> registry = new HashMap<>();
private static ConcurrentHashMap<String, RelationType> registry = new ConcurrentHashMap<>();
}
@@ -0,0 +1,89 @@
/*******************************************************************************
* 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;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Supplier;
/** Coordinates background consumers with database closure. Owners are weakly keyed:
* stale waveform references retain a closed scope and cannot reopen a recording.
*/
public final class WaveformAccess {
private static final Map<IWaveform, Scope> OWNERS = new WeakHashMap<>();
private static final AtomicLong IDS = new AtomicLong();
private WaveformAccess() { }
public static final class Scope {
private final long id = IDS.incrementAndGet();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
private volatile boolean closing;
public void register(Collection<IWaveform> waveforms) {
synchronized (OWNERS) { for (IWaveform waveform : waveforms) OWNERS.put(waveform, this); }
}
/** Must run on a worker: waits for existing leases, rejecting new ones. */
public void close(Runnable cleanup) {
closing = true;
lock.writeLock().lock();
try { cleanup.run(); }
finally { lock.writeLock().unlock(); }
}
private void acquire() {
try {
while (!closing) {
ReadCancellation.check();
if (lock.readLock().tryLock(50, TimeUnit.MILLISECONDS)) {
if (!closing) return;
lock.readLock().unlock();
}
}
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
throw new CancellationException("Database is closing");
}
}
public static <T> T read(IWaveform waveform, Supplier<T> query) {
return read(waveform == null ? List.of() : List.of(waveform), query);
}
public static <T> T read(Collection<IWaveform> waveforms, Supplier<T> query) {
Map<Scope, Boolean> scopes = new IdentityHashMap<>();
synchronized (OWNERS) {
for (IWaveform waveform : waveforms) collect(waveform, scopes);
}
List<Scope> ordered = new ArrayList<>(scopes.keySet());
ordered.sort(Comparator.comparingLong(scope -> scope.id));
int acquired = 0;
try {
for (Scope scope : ordered) { scope.acquire(); acquired++; }
ReadCancellation.check();
return query.get();
} finally {
for (int i = acquired - 1; i >= 0; i--) ordered.get(i).lock.readLock().unlock();
}
}
private static void collect(IWaveform waveform, Map<Scope, Boolean> scopes) {
Scope scope = OWNERS.get(waveform);
if (scope != null) scopes.put(scope, Boolean.TRUE);
else {
List<IWaveform> sources = waveform.getReadSources();
if (sources != null) for (IWaveform source : sources) if (source != null && source != waveform) collect(source, scopes);
}
}
}
@@ -17,6 +17,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantLock;
import java.util.List;
import java.util.Map;
@@ -30,6 +31,7 @@ import com.minres.scviewer.database.IWaveformDb;
import com.minres.scviewer.database.IWaveformDbLoader;
import com.minres.scviewer.database.IWaveformDbLoaderFactory;
import com.minres.scviewer.database.RelationType;
import com.minres.scviewer.database.WaveformAccess;
/**
* The Class WaveformDb.
@@ -39,6 +41,9 @@ public class WaveformDb extends HierNode implements IWaveformDb, PropertyChangeL
/** The loaders. */
private static final CopyOnWriteArrayList<IWaveformDbLoaderFactory> loaderFactories = new CopyOnWriteArrayList<>();
private final ReentrantLock lifecycle = new ReentrantLock();
private WaveformAccess.Scope readScope = new WaveformAccess.Scope();
private List<IWaveformDbLoader> activeLoader = new ArrayList<>();
/** The loaded. */
private volatile boolean loaded;
@@ -122,9 +127,10 @@ public class WaveformDb extends HierNode implements IWaveformDb, PropertyChangeL
public boolean load(File inp) {
List<PropertyChangeEvent> notifications = new ArrayList<>();
boolean result;
synchronized (this) {
result = loadLocked(inp, notifications);
}
lifecycle.lock();
try {
synchronized (this) { result = loadLocked(inp, notifications); }
} finally { lifecycle.unlock(); }
// A listener may wait for the UI, which in turn may need close().
// Never invoke external listeners while holding the database lock.
notifications.forEach(pcs::firePropertyChange);
@@ -132,6 +138,7 @@ public class WaveformDb extends HierNode implements IWaveformDb, PropertyChangeL
}
private boolean loadLocked(File inp, List<PropertyChangeEvent> notifications) {
if (activeLoader.isEmpty()) readScope = new WaveformAccess.Scope();
for (IWaveformDbLoaderFactory factory : getLoaders()) {
if (!factory.canLoad(inp)) continue;
IWaveformDbLoader loader = factory.getLoader();
@@ -161,6 +168,7 @@ public class WaveformDb extends HierNode implements IWaveformDb, PropertyChangeL
for (PropertyChangeEvent event : pending) applyWaveform(event);
if (!pending.isEmpty()) addWaveformNotifications(notifications);
}
readScope.register(getAllWaves());
loaded = true;
notifications.add(new PropertyChangeEvent(this, IHierNode.LOADING_FINISHED, null, Boolean.TRUE));
return true;
@@ -170,7 +178,13 @@ public class WaveformDb extends HierNode implements IWaveformDb, PropertyChangeL
}
@Override
public synchronized void close() {
public void close() {
lifecycle.lock();
try { readScope.close(this::closeLocked); }
finally { lifecycle.unlock(); }
}
private synchronized void closeLocked() {
for (IWaveformDbLoader loader : activeLoader) {
try { loader.dispose(); }
catch (RuntimeException e) { LOG.warn("Cannot dispose database loader", e); }
@@ -264,8 +278,8 @@ public class WaveformDb extends HierNode implements IWaveformDb, PropertyChangeL
* @return the all relation types
*/
@Override
public List<RelationType> getAllRelationTypes() {
return relationTypes;
public synchronized List<RelationType> getAllRelationTypes() {
return List.copyOf(relationTypes);
}
}
@@ -27,9 +27,11 @@ public final class TransactionLists {
public static List<ITx> fromEvents(IEventList events, BooleanSupplier cancelled) {
List<ITx> transactions = new ArrayList<>();
for (EventEntry entry : events.entrySet()) {
com.minres.scviewer.database.ReadCancellation.check();
if (cancelled.getAsBoolean()) throw new java.util.concurrent.CancellationException();
if (entry.events == null) continue;
for (IEvent event : entry.events) {
com.minres.scviewer.database.ReadCancellation.check();
if (cancelled.getAsBoolean()) throw new java.util.concurrent.CancellationException();
if (event instanceof ITxEvent tx && (event.getKind() == EventKind.BEGIN || event.getKind() == EventKind.SINGLE))
transactions.add(tx.getTransaction());
@@ -40,7 +42,8 @@ public final class TransactionLists {
public static List<ITx> sorted(java.util.Collection<ITx> transactions) {
List<ITx> sorted = new ArrayList<>(transactions);
sorted.sort(Comparator.comparingLong(ITx::getBeginTime).thenComparingLong(ITx::getId));
Comparator<ITx> order = Comparator.comparingLong(ITx::getBeginTime).thenComparingLong(ITx::getId);
sorted.sort((left, right) -> { com.minres.scviewer.database.ReadCancellation.check(); return order.compare(left, right); });
return List.copyOf(sorted);
}
}
@@ -26,6 +26,7 @@ public final class TxIntervalIndex {
final Node left, right;
Node(List<ITxEvent> events, int from, int to) {
com.minres.scviewer.database.ReadCancellation.check();
int mid = (from + to) >>> 1;
event = events.get(mid);
ITx tx = event.getTransaction();
@@ -52,10 +53,12 @@ public final class TxIntervalIndex {
public TxIntervalIndex(IEventList events) {
List<ITxEvent> starts = new ArrayList<>();
for (EventEntry entry : events)
for (EventEntry entry : events) {
com.minres.scviewer.database.ReadCancellation.check();
for (IEvent event : entry.events)
if (event instanceof ITxEvent && event.getKind() != EventKind.END)
starts.add((ITxEvent) event);
}
// EventList already orders buckets by timestamp, including same-time starts.
root = starts.isEmpty() ? null : new Node(starts, 0, starts.size());
}
@@ -35,25 +35,29 @@ import com.minres.scviewer.e4.application.Messages;
public class UpdateHandler {
boolean cancelled = false;
private final java.util.concurrent.atomic.AtomicBoolean updating = new java.util.concurrent.atomic.AtomicBoolean();
@Execute
public void execute(IProvisioningAgent agent, UISynchronize sync, IWorkbench workbench) {
if (!updating.compareAndSet(false, true)) return;
java.util.concurrent.atomic.AtomicBoolean scheduled = new java.util.concurrent.atomic.AtomicBoolean();
IRunnableWithProgress runnable = new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
update(agent, monitor, sync, workbench);
update(agent, monitor, sync, workbench, scheduled);
}
};
try {
new ProgressMonitorDialog(null).run(true, true, runnable);
} catch (InvocationTargetException | InterruptedException e) {
if (e instanceof InterruptedException) Thread.currentThread().interrupt();
e.printStackTrace();
}
} finally { if (!scheduled.get()) updating.set(false); }
}
private IStatus update(IProvisioningAgent agent, IProgressMonitor monitor, UISynchronize sync,
IWorkbench workbench) {
IWorkbench workbench, java.util.concurrent.atomic.AtomicBoolean scheduled) {
java.util.concurrent.atomic.AtomicBoolean cancelled = new java.util.concurrent.atomic.AtomicBoolean();
ProvisioningSession session = new ProvisioningSession(agent);
UpdateOperation operation = new UpdateOperation(session);
try {
@@ -80,8 +84,9 @@ public class UpdateHandler {
provisioningJob.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
updating.set(false);
if (event.getResult().isOK()) {
sync.syncExec(new Runnable() {
sync.asyncExec(new Runnable() {
@Override
public void run() {
@@ -93,17 +98,17 @@ public class UpdateHandler {
}
});
} else {
sync.syncExec(() -> {
sync.asyncExec(() -> {
MessageDialog.openInformation(null, Messages.UpdateHandler_11,
event.getResult().getMessage());
});
cancelled = true;
}
}
});
scheduled.set(true);
provisioningJob.schedule();
} else {
cancelled = true;
cancelled.set(true);
}
}
});
@@ -118,11 +123,10 @@ public class UpdateHandler {
MessageDialog.openInformation(null, Messages.UpdateHandler_11, Messages.UpdateHandler_9);
});
}
cancelled = true;
cancelled.set(true);
}
}
if (cancelled) {
cancelled = false;
if (cancelled.get()) {
return Status.CANCEL_STATUS;
}
return Status.OK_STATUS;
@@ -471,12 +471,14 @@ public class HeapStatus extends Composite {
* Gc.
*/
private void gc() {
var display = getDisplay();
gcRunning(true);
Thread t = new Thread() {
@Override
public void run() {
busyGC();
getDisplay().asyncExec(() -> {
if (display.isDisposed()) return;
com.minres.scviewer.database.ui.UiDispatch.async(display, () -> {
if (!isDisposed())
gcRunning(false);
});
@@ -0,0 +1,43 @@
/*******************************************************************************
* Copyright (c) 2015-2021 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.internal.status;
import org.eclipse.core.runtime.NullProgressMonitor;
/** Per-job cancellation and progress state. Only immutable snapshots reach SWT. */
public final class JobProgress extends NullProgressMonitor {
public record Snapshot(String name, int total, double work, boolean done) { }
private final Runnable changed;
private String name = "";
private int total;
private double work;
private boolean done;
public JobProgress(Runnable changed) { this.changed = changed; }
@Override public void beginTask(String name, int totalWork) {
synchronized (this) { this.name = name; total = totalWork; work = 0; done = false; }
changed.run();
}
@Override public void setTaskName(String name) {
synchronized (this) { this.name = name; }
changed.run();
}
@Override public void subTask(String name) { setTaskName(name); }
@Override public void worked(int work) { internalWorked(work); }
@Override public void internalWorked(double amount) {
synchronized (this) { work += amount; }
changed.run();
}
@Override public void done() {
synchronized (this) { done = true; }
changed.run();
}
public synchronized Snapshot snapshot() { return new Snapshot(name, total, work, done); }
}
@@ -15,7 +15,6 @@ import javax.annotation.PreDestroy;
import javax.inject.Inject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
@@ -45,14 +44,15 @@ public class StatusBarControl {
/** The osgi preverences. */
@Inject @Optional PreferencesService osgiPreverences;
/** The sync. */
private final UISynchronize sync;
/** The manager. */
protected StatusLineManager manager;
/** The monitor. */
private SyncedProgressMonitor monitor;
private final java.util.Set<JobProgress> monitors = java.util.concurrent.ConcurrentHashMap.newKeySet();
private final java.util.concurrent.atomic.AtomicBoolean updatePending = new java.util.concurrent.atomic.AtomicBoolean();
private static StatusBarControl providerOwner;
private volatile boolean disposed;
private org.eclipse.swt.widgets.Display display;
/**
* Instantiates a new status bar control.
@@ -61,7 +61,6 @@ public class StatusBarControl {
*/
@Inject
public StatusBarControl(UISynchronize sync) {
this.sync=sync;
manager = new StatusLineManager();
manager.update(true);
}
@@ -86,6 +85,12 @@ public class StatusBarControl {
*/
@PreDestroy
void destroy() {
disposed = true;
if (providerOwner == this) {
Job.getJobManager().setProgressProvider(null);
providerOwner = null;
}
monitors.clear();
if (manager != null) {
manager.dispose();
manager = null;
@@ -101,14 +106,24 @@ public class StatusBarControl {
private void createStatusLine(Composite parent, MToolControl toolControl) {
// IEclipseContext context = modelService.getContainingContext(toolControl);
manager.createControl(parent);
monitor=new SyncedProgressMonitor(manager.getProgressMonitor());
display = parent.getDisplay();
manager.setCancelEnabled(false);
providerOwner = this;
Job.getJobManager().setProgressProvider(new ProgressProvider() {
@Override
public IProgressMonitor createMonitor(Job job) {
return monitor.addJob(job);
@Override public IProgressMonitor createMonitor(Job job) {
JobProgress monitor = new JobProgress(StatusBarControl.this::requestProgressUpdate);
if (disposed) return monitor;
monitors.add(monitor);
job.addJobChangeListener(new JobChangeAdapter() {
@Override public void done(IJobChangeEvent event) {
monitors.remove(monitor);
requestProgressUpdate();
event.getJob().removeJobChangeListener(this);
}
});
return monitor;
}
});
}
/**
@@ -124,118 +139,20 @@ public class StatusBarControl {
}
}
/**
* The Class SyncedProgressMonitor.
*/
private final class SyncedProgressMonitor extends NullProgressMonitor {
/** The progress bar. */
private IProgressMonitor progressBar;
/**
* Instantiates a new synced progress monitor.
*
* @param iProgressMonitor the progress bar
*/
public SyncedProgressMonitor(IProgressMonitor iProgressMonitor) {
super();
this.progressBar = iProgressMonitor;
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.NullProgressMonitor#beginTask(java.lang.String, int)
*/
@Override
public void beginTask(final String name, final int totalWork) {
sync.asyncExec(new Runnable() {
@Override
public void run() {
progressBar.beginTask(name, totalWork);
}
private void requestProgressUpdate() {
if (disposed || !updatePending.compareAndSet(false, true)) return;
com.minres.scviewer.database.ui.UiDispatch.async(display, () -> {
updatePending.set(false);
if (disposed || manager == null || manager.getControl().isDisposed()) return;
var snapshots = monitors.stream().map(JobProgress::snapshot).filter(p -> !p.done()).toList();
IProgressMonitor bar = manager.getProgressMonitor();
if (snapshots.isEmpty()) { bar.done(); return; }
String title = snapshots.get(0).name();
if (snapshots.size() > 1) title += " (+" + (snapshots.size() - 1) + " tasks)";
bar.beginTask(title, 1000);
int work = (int) snapshots.stream().mapToDouble(p -> p.total() > 0
? Math.min(1, p.work() / p.total()) * 1000 : 0).average().orElse(0);
bar.worked(work);
});
}
/**
* This implementation does nothing.
* Subclasses may override this method to do something
* with the name of the task.
*
* @see IProgressMonitor#setTaskName(String)
*/
@Override
public void setTaskName(String name) {
sync.asyncExec(new Runnable() {
@Override
public void run() {
progressBar.setTaskName(name);
}
});
}
/**
* This implementation does nothing.
* Subclasses may override this method to do interesting
* processing when a subtask begins.
*
* @see IProgressMonitor#subTask(String)
*/
@Override
public void subTask(String name) {
sync.asyncExec(new Runnable() {
@Override
public void run() {
progressBar.subTask(name);
}
});
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.NullProgressMonitor#worked(int)
*/
@Override
public void worked(final int work) {
sync.asyncExec(new Runnable() {
@Override
public void run() {
progressBar.worked(work);
}
});
}
@Override
public void done() {
sync.asyncExec(new Runnable() {
@Override
public void run() {
progressBar.done();
}
});
}
/**
* Adds the job.
*
* @param job the job
* @return the i progress monitor
*/
public IProgressMonitor addJob(Job job){
if(job != null){
job.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(final IJobChangeEvent event) {
sync.asyncExec(new Runnable() {
@Override
public void run() {
if(event.getResult()==null) return;
if(!event.getResult().isOK())
progressBar.done();
}
});
// clean-up
event.getJob().removeJobChangeListener(this);
}
});
}
return this;
}
}
}
@@ -10,24 +10,39 @@
*******************************************************************************/
package com.minres.scviewer.e4.application.internal.util;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.Function;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
/** Publishes only the latest request, including when older results are already queued. */
import com.minres.scviewer.database.ReadCancellation;
/** Owns background requests and rejects stale results, including queued UI callbacks. */
public final class LatestJob<T> implements AutoCloseable {
private final AtomicLong generation = new AtomicLong();
private final Consumer<Runnable> dispatch;
private final Consumer<T> publish;
private Job job;
private final Set<Job> jobs = ConcurrentHashMap.newKeySet();
private final boolean latestOnly;
private volatile boolean closed;
public LatestJob(Consumer<Runnable> dispatch, Consumer<T> publish) {
this(dispatch, publish, true);
}
/** latestOnly=false preserves additive commands until cancel/close. */
public LatestJob(Consumer<Runnable> dispatch, Consumer<T> publish, boolean latestOnly) {
this.latestOnly = latestOnly;
this.dispatch = dispatch;
this.publish = publish;
}
@@ -35,31 +50,38 @@ public final class LatestJob<T> implements AutoCloseable {
/** Called by the owning UI thread, as are cancel() and close(). */
public void schedule(String name, Function<IProgressMonitor, T> query) {
if (closed) return;
cancel();
if (latestOnly) cancel();
final long request = generation.get();
job = new Job(name) {
@Override
protected IStatus run(IProgressMonitor monitor) {
if (monitor.isCanceled()) return Status.CANCEL_STATUS;
T result = query.apply(monitor);
Job job = new Job(name) {
@Override protected IStatus run(IProgressMonitor monitor) {
try {
T result = ReadCancellation.with(
() -> monitor.isCanceled() || closed || generation.get() != request,
() -> query.apply(monitor));
if (monitor.isCanceled() || closed || generation.get() != request) return Status.CANCEL_STATUS;
dispatch.accept(() -> {
if (!closed && generation.get() == request) publish.accept(result);
if (result != null && !closed && generation.get() == request) publish.accept(result);
});
return Status.OK_STATUS;
} catch (CancellationException | OperationCanceledException e) {
return Status.CANCEL_STATUS;
} finally { jobs.remove(this); monitor.done(); }
}
};
jobs.add(job);
job.addJobChangeListener(new JobChangeAdapter() {
@Override public void done(IJobChangeEvent event) { jobs.remove(event.getJob()); }
});
job.setSystem(true);
job.schedule();
}
public void cancel() {
generation.incrementAndGet();
if (job != null) job.cancel();
for (Job job : jobs) job.cancel();
}
@Override
public void close() {
@Override public void close() {
closed = true;
cancel();
}
@@ -30,40 +30,47 @@ public final class TransactionQuery {
public record Attribute(String name, DataType type) {}
private final IWaveform waveform;
private volatile List<ITx> transactions;
private List<Attribute> attributes;
private volatile List<Attribute> attributes;
public TransactionQuery(IWaveform waveform) { this.waveform = waveform; }
public List<ITx> transactions(BooleanSupplier cancelled) {
return cancellable(cancelled,
() -> com.minres.scviewer.database.WaveformAccess.read(waveform, () -> {
check(cancelled);
List<ITx> result = transactions;
if (result == null) {
synchronized (this) {
result = transactions;
if (result == null) {
try {
result = waveform instanceof ITransactionProvider indexed ? indexed.getTransactionList()
: TransactionLists.fromEvents(waveform.getEvents(), cancelled);
} catch (java.util.concurrent.CancellationException e) { throw new OperationCanceledException(); }
check(cancelled);
transactions = result;
}
synchronized (this) {
if (transactions == null) transactions = result;
result = transactions;
}
}
check(cancelled);
return result;
}));
}
public List<ITx> filter(Predicate<ITx> predicate, BooleanSupplier cancelled) {
return cancellable(cancelled,
() -> com.minres.scviewer.database.WaveformAccess.read(waveform, () -> {
List<ITx> result = new ArrayList<>();
for (ITx transaction : transactions(cancelled)) {
check(cancelled);
if (predicate.test(transaction)) result.add(transaction);
}
return List.copyOf(result);
}));
}
public synchronized List<Attribute> discoverAttributes(BooleanSupplier cancelled) {
public List<Attribute> discoverAttributes(BooleanSupplier cancelled) {
return cancellable(cancelled,
() -> com.minres.scviewer.database.WaveformAccess.read(waveform, () -> discover(cancelled)));
}
private List<Attribute> discover(BooleanSupplier cancelled) {
check(cancelled);
if (attributes != null) return attributes;
Map<String, DataType> types = new TreeMap<>();
@@ -72,8 +79,13 @@ public final class TransactionQuery {
transaction.getAttributes().forEach(attribute -> types.putIfAbsent(attribute.getName(), attribute.getDataType()));
}
check(cancelled);
attributes = types.entrySet().stream().map(e -> new Attribute(e.getKey(), e.getValue())).toList();
return attributes;
List<Attribute> result = types.entrySet().stream().map(e -> new Attribute(e.getKey(), e.getValue())).toList();
synchronized (this) { if (attributes == null) attributes = result; return attributes; }
}
private static <T> T cancellable(BooleanSupplier cancelled, java.util.function.Supplier<T> query) {
try { return com.minres.scviewer.database.ReadCancellation.with(cancelled, query); }
catch (java.util.concurrent.CancellationException e) { throw new OperationCanceledException(); }
}
private static void check(BooleanSupplier cancelled) {
@@ -23,7 +23,6 @@ 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;
@@ -226,9 +225,7 @@ public record ViewerSettings(List<Track> tracks, List<Long> cursors, Long scale,
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))) {
if (!waveform.isBitVector()) {
missing.add(vector.name() + ": " + bit.waveform() + " is not a bit signal");
break;
}
@@ -88,6 +88,7 @@ public class TransactionDetails {
/** The tree viewer. */
private TreeViewer treeViewer;
private com.minres.scviewer.e4.application.internal.util.LatestJob<ITx> inputJob;
/** The col3. */
private TreeViewerColumn col1;
@@ -290,6 +291,39 @@ public class TransactionDetails {
HashMap<Integer, ViewSettings> settings = new HashMap<>();
public void setInput(Object object) {
if (treeViewer == null || treeViewer.getControl().isDisposed()) return;
if (inputJob == null) {
var display = treeViewer.getControl().getDisplay();
inputJob = new com.minres.scviewer.e4.application.internal.util.LatestJob<>(
task -> com.minres.scviewer.database.ui.UiDispatch.async(display, task), tx -> {
if (!treeViewer.getControl().isDisposed()) setPreparedInput(tx);
});
treeViewer.getControl().addDisposeListener(event -> inputJob.close());
}
inputJob.cancel();
if (object instanceof ITx tx) {
// Drop stale details immediately; remember layout only for completed inputs.
rememberInput();
treeViewer.setInput(null);
inputJob.schedule("Load selected transaction", monitor ->
com.minres.scviewer.database.WaveformAccess.read(tx.getStream(), () -> {
tx.getAttributes();
tx.getIncomingRelations();
tx.getOutgoingRelations();
return tx;
}));
} else treeViewer.setInput(null);
}
private void rememberInput() {
Object oldInput = treeViewer.getInput();
if (oldInput != null) {
settings.put(getAttrNameHash(oldInput), new ViewSettings(
getTopItemHier(treeViewer.getTree().getTopItem()), treeViewer.getExpandedTreePaths()));
}
}
private void setPreparedInput(Object object) {
if(object instanceof ITx){
Object oldInput = treeViewer.getInput();
if(oldInput!=null) {
@@ -93,13 +93,13 @@ public class TransactionList extends Composite {
column("Property Value", 180, valueProvider);
Display display = getDisplay();
rowsJob = new LatestJob<>(task -> { if (!display.isDisposed()) display.asyncExec(task); }, result -> {
rowsJob = new LatestJob<>(task -> com.minres.scviewer.database.ui.UiDispatch.async(display, task), result -> {
if (isDisposed()) return;
rows = result;
tableViewer.setInput(rows);
tableViewer.setItemCount(rows.size());
});
attributesJob = new LatestJob<>(task -> { if (!display.isDisposed()) display.asyncExec(task); }, result -> {
attributesJob = new LatestJob<>(task -> com.minres.scviewer.database.ui.UiDispatch.async(display, task), result -> {
if (isDisposed()) return;
if (result.error() != null) {
MessageDialog.openError(getShell(), "Cannot load properties", result.error().toString());
@@ -216,6 +216,7 @@ public class TransactionList extends Composite {
getDisplay().timerExec(-1, applyFilter);
rowsJob.cancel();
attributesJob.cancel();
valueProvider.reset();
stream = requestedStream;
query = stream == null ? null : new TransactionQuery(stream);
rows = List.of();
@@ -175,6 +175,7 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
/** The my parent. */
private Composite myParent;
private Display uiDisplay;
/** The files to load. */
ArrayList<File> filesToLoad = new ArrayList<>();
@@ -182,6 +183,17 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
String partConfig = "";
private Path settingsFile;
private LatestJob<PreparedVector> vectorJob;
private LatestJob<PreparedSettings> settingsJob;
private com.minres.scviewer.database.ui.AsyncTransactionData transactionSnapshots;
private com.minres.scviewer.database.ui.AsyncTransactionData.Snapshot transactionSnapshot(ITx tx) {
if (transactionSnapshots == null) transactionSnapshots = new com.minres.scviewer.database.ui.AsyncTransactionData(
this::dispatchSettings, changed -> { if (!disposed && eventBroker != null) eventBroker.post(ACTIVE_WAVEFORMVIEW, this); });
return transactionSnapshots.get(tx);
}
private record SettingsWrite(long request, ViewerSettings settings, Path file) { }
private final java.util.Queue<SettingsWrite> settingsWriteQueue = new java.util.concurrent.ConcurrentLinkedQueue<>();
private final java.util.concurrent.atomic.AtomicBoolean writingSettings = new java.util.concurrent.atomic.AtomicBoolean();
private final java.util.concurrent.atomic.AtomicLong settingsWrites = new java.util.concurrent.atomic.AtomicLong();
private record PreparedVector(CombinedBitVectorWaveform vector, List<TrackEntry> tracks,
IWaveformDb database, String error) { }
@@ -225,9 +237,10 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
myPart = part;
myParent = parent;
uiDisplay = parent.getDisplay();
store=prefs;
showHover=hover;
sessions = new DatabaseSessionManager(dbFactory, task -> sync.asyncExec(task),
sessions = new DatabaseSessionManager(dbFactory, this::dispatchSettings,
db -> { if (!isViewerDisposed()) waveformPane.setMaxTime(db.getMaxTime()); },
db -> { if (!isViewerDisposed() && confirmReload()) reloadDatabase(); }, 60000);
parent.setLayout(new FillLayout(SWT.HORIZONTAL));
@@ -417,7 +430,7 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
final TableColumn valueCol = new TableColumn(table, SWT.LEFT);
valueCol.setText("Value");
for (ITxAttribute iTxAttribute : tx.getAttributes()) {
for (ITxAttribute iTxAttribute : transactionSnapshot(tx).attributes()) {
String value = iTxAttribute.getValue().toString();
if((DataType.UNSIGNED == iTxAttribute.getDataType() || DataType.INTEGER==iTxAttribute.getDataType()) && !"0".equals(value)) {
try {
@@ -468,6 +481,8 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
if (disposed) return;
disposed = true;
if (vectorJob != null) vectorJob.close();
if (settingsJob != null) settingsJob.close();
if (transactionSnapshots != null) transactionSnapshots.close();
if (sessions != null) sessions.close();
if (observedPreferences != null) {
observedPreferences.removePreferenceChangeListener(this);
@@ -537,6 +552,8 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
protected void loadDatabase(final Map<String, String> state, long delay) {
if (disposed) return;
if (vectorJob != null) vectorJob.cancel();
if (settingsJob != null) settingsJob.cancel();
if (transactionSnapshots != null) { transactionSnapshots.close(); transactionSnapshots = null; }
setSelection(null);
waveformPane.getStreamList().clear();
waveformPane.update();
@@ -609,23 +626,79 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
public void saveState(String fileName) {
try {
Path file = Path.of(fileName).toAbsolutePath().normalize();
captureSettings().write(file);
settingsFile = file;
settingsWriteQueue.add(new SettingsWrite(settingsWrites.incrementAndGet(), captureSettings(), file));
scheduleSettingsWrites();
} catch (IllegalArgumentException e) { reportSettingsError("Cannot save settings", fileName + ": " + e.getMessage()); }
}
catch (IOException | IllegalArgumentException e) {
reportSettingsError("Cannot save settings", fileName + ": " + e.getMessage());
private void scheduleSettingsWrites() {
if (!writingSettings.compareAndSet(false, true)) return;
var save = new org.eclipse.core.runtime.jobs.Job("Save waveform settings") {
@Override protected org.eclipse.core.runtime.IStatus run(org.eclipse.core.runtime.IProgressMonitor monitor) {
try {
SettingsWrite pending;
while ((pending = settingsWriteQueue.poll()) != null) {
SettingsWrite current = pending;
try {
current.settings().write(current.file());
dispatchSettings(() -> {
if (!disposed && current.request() == settingsWrites.get()) settingsFile = current.file();
});
} catch (IOException | IllegalArgumentException e) {
dispatchSettings(() -> {
if (!disposed) reportSettingsError("Cannot save settings", current.file() + ": " + e.getMessage());
});
}
}
return org.eclipse.core.runtime.Status.OK_STATUS;
} finally {
writingSettings.set(false);
if (!settingsWriteQueue.isEmpty()) scheduleSettingsWrites();
monitor.done();
}
}
};
save.setSystem(true); save.schedule();
}
public void loadState(String fileName) {
try {
Path file = Path.of(fileName).toAbsolutePath().normalize();
applySettings(ViewerSettings.read(file));
settingsFile = file;
requestSettings(() -> ViewerSettings.read(file), file);
} catch (IllegalArgumentException e) { reportSettingsError("Cannot load settings", fileName + ": " + e.getMessage()); }
}
@FunctionalInterface private interface SettingsReader { ViewerSettings read() throws IOException; }
private void dispatchSettings(Runnable runnable) {
if (disposed) return;
if (uiDisplay != null) com.minres.scviewer.database.ui.UiDispatch.async(uiDisplay, runnable);
else if (sync != null) sync.asyncExec(runnable);
else runnable.run();
}
private void requestSettings(SettingsReader reader, Path file) {
IWaveformDb database = getDatabase();
List<IWaveform> sources = database == null ? List.of() : database.getAllWaves();
if (sync == null) {
// Headless callers have no SWT owner; retain synchronous validation.
try { applyPreparedSettings(prepareSettings(reader.read(), database, file)); }
catch (IOException | IllegalArgumentException e) { reportSettingsError("Cannot load settings", e.getMessage()); }
return;
}
if (settingsJob == null) settingsJob = new LatestJob<>(this::dispatchSettings, prepared -> {
if (disposed || getDatabase() != prepared.database()) return;
if (prepared.error() != null) { reportSettingsError("Cannot load settings", prepared.error()); return; }
applyPreparedSettings(prepared);
});
settingsJob.schedule("Prepare waveform settings", monitor -> {
try {
ViewerSettings settings = reader.read();
return com.minres.scviewer.database.WaveformAccess.read(sources,
() -> prepareSettings(settings, database, file));
} catch (java.util.concurrent.CancellationException e) { throw e; }
catch (IOException | IllegalArgumentException e) {
reportSettingsError("Cannot load settings", fileName + ": " + e.getMessage());
return new PreparedSettings(null, List.of(), List.of(), null, null, database, file, e.getMessage());
}
});
}
/** Last successfully loaded or saved settings file for this viewer. */
@@ -699,17 +772,22 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
private record ResolvedTrack(IWaveform waveform, ViewerSettings.Track settings) {}
private void applySettings(ViewerSettings settings) {
if (vectorJob != null) vectorJob.cancel();
private record PreparedSettings(ViewerSettings settings, List<ResolvedTrack> resolved, List<String> missing,
ITx selectedTransaction, IWaveform selectedWaveform, IWaveformDb database, Path file, String error) { }
private void applySettings(ViewerSettings settings) { requestSettings(() -> settings, null); }
private PreparedSettings prepareSettings(ViewerSettings settings, IWaveformDb database, Path file) {
// Resolve all references before replacing the current layout.
List<ResolvedTrack> resolved = new ArrayList<>();
List<String> missing = new ArrayList<>();
Map<String, IWaveform> derived = settings.resolveCombinedVectors(getDatabase(), missing);
Map<String, IWaveform> derived = settings.resolveCombinedVectors(database, missing);
ITx selectedTransaction = null;
IWaveform selectedWaveform = null;
for (ViewerSettings.Track track : settings.tracks()) {
com.minres.scviewer.database.ReadCancellation.check();
IWaveform waveform = track.type() == WaveformType.EMPTY ? new EmptyWaveform(track.name())
: ViewerSettings.resolveWaveform(getDatabase(), track.name(), derived);
: ViewerSettings.resolveWaveform(database, track.name(), derived);
if (waveform == null) {
missing.add(settings.displayName(track.name()));
continue;
@@ -721,6 +799,18 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
selectedWaveform = waveform;
}
}
return new PreparedSettings(settings, List.copyOf(resolved), List.copyOf(missing), selectedTransaction,
selectedWaveform, database, file, null);
}
private void applyPreparedSettings(PreparedSettings prepared) {
if (vectorJob != null) vectorJob.cancel();
ViewerSettings settings = prepared.settings();
List<ResolvedTrack> resolved = prepared.resolved();
List<String> missing = prepared.missing();
ITx selectedTransaction = prepared.selectedTransaction();
IWaveform selectedWaveform = prepared.selectedWaveform();
if (prepared.file() != null) settingsFile = prepared.file();
waveformPane.setSelection(StructuredSelection.EMPTY);
waveformPane.getStreamList().clear();
List<TrackEntry> selectedTracks = new ArrayList<>();
@@ -978,21 +1068,24 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
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 (vectorJob == null) vectorJob = new LatestJob<>(this::dispatchSettings, result -> {
if (disposed || getDatabase() != result.database()) return;
if (result.error() != null) { reportSettingsError("Cannot combine bits", result.error()); return; }
insertCombinedVector(result.vector(), result.tracks());
});
}, false);
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.
return com.minres.scviewer.database.WaveformAccess.read(vector, () -> {
vector.getEvents().firstEntry(); // Load lazy inputs while holding a recording lease.
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 (java.util.concurrent.CancellationException exception) { throw exception;
} catch (RuntimeException exception) {
return new PreparedVector(null, snapshot, database, exception.toString());
}
@@ -1125,9 +1218,9 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
res.add(IWaveformView.NEXT_PREV_IN_STREAM);
ITx transaction = WaveformSelection.from(waveformPane.getSelection()).transaction();
if (transaction != null) {
for (ITxRelation relation : transaction.getIncomingRelations())
for (ITxRelation relation : transactionSnapshot(transaction).incoming())
if (!res.contains(relation.getRelationType())) res.add(relation.getRelationType());
for (ITxRelation relation : transaction.getOutgoingRelations())
for (ITxRelation relation : transactionSnapshot(transaction).outgoing())
if (!res.contains(relation.getRelationType())) res.add(relation.getRelationType());
}
return res;
@@ -28,6 +28,19 @@ import com.minres.scviewer.e4.application.parts.WaveformViewer;
* The Class AttributeLabelProvider.
*/
public class AttributeLabelProvider extends LabelProvider implements IStyledLabelProvider {
private com.minres.scviewer.database.ui.AsyncTransactionData data;
private List<ITxAttribute> attributes(ITx tx) {
var display = org.eclipse.swt.widgets.Display.getCurrent();
// Headless consumers are already on a worker and can read synchronously.
if (display == null) return tx.getAttributes();
if (data == null) data = new com.minres.scviewer.database.ui.AsyncTransactionData(
task -> com.minres.scviewer.database.ui.UiDispatch.async(display, task),
changed -> fireLabelProviderChanged(new org.eclipse.jface.viewers.LabelProviderChangedEvent(this, changed)), false);
return data.get(tx).attributes();
}
public void reset() { if (data != null) data.close(); data = null; }
@Override public void dispose() { reset(); super.dispose(); }
/**
*
@@ -84,14 +97,14 @@ public class AttributeLabelProvider extends LabelProvider implements IStyledLabe
return new StyledString(waveformViewerPart.getScaledTime(iTx.getBeginTime()));
case TYPE:
if(showProp!=null){
List<ITxAttribute> res = iTx.getAttributes().stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
List<ITxAttribute> res = attributes(iTx).stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
if(res.size()==1)
return new StyledString(res.get(0).getDataType().toString());
}
return new StyledString("");
case VALUE:
if(showProp!=null){
List<ITxAttribute> res = iTx.getAttributes().stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
List<ITxAttribute> res = attributes(iTx).stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
if(res.size()==1)
return getAttrValueAsStyledString(res.get(0));
}
@@ -115,7 +128,7 @@ public class AttributeLabelProvider extends LabelProvider implements IStyledLabe
if(element instanceof TransactionTreeNode) {
if(showProp!=null){
ITx iTx = ((TransactionTreeNode) element).element;
List<ITxAttribute> res = iTx.getAttributes().stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
List<ITxAttribute> res = attributes(iTx).stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
if(res.size()==1)
return new StyledString(res.get(0).getDataType().toString());
}
@@ -137,7 +150,7 @@ public class AttributeLabelProvider extends LabelProvider implements IStyledLabe
if(element instanceof TransactionTreeNode) {
if(showProp!=null){
ITx iTx = ((TransactionTreeNode) element).element;
List<ITxAttribute> res = iTx.getAttributes().stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
List<ITxAttribute> res = attributes(iTx).stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
if(res.size()==1)
return getAttrValueAsStyledString(res.get(0));
}
@@ -56,15 +56,19 @@ import com.minres.scviewer.ui.views.TxOutlinePage;
public class TxEditorPart extends EditorPart implements ITabbedPropertySheetPageContributor {
private static IWaveformDbFactory waveformDbFactory;
private static volatile IWaveformDbFactory waveformDbFactory;
private PropertyChangeListener databaseListener;
private org.eclipse.swt.widgets.Display display;
private volatile boolean disposed;
public synchronized void bind(IWaveformDbFactory factory){
waveformDbFactory=factory;
public void bind(IWaveformDbFactory factory){
synchronized (TxEditorPart.class) { waveformDbFactory=factory; }
}
public synchronized void unbind(IWaveformDbFactory factory){
if(waveformDbFactory==factory)
waveformDbFactory=null;
public void unbind(IWaveformDbFactory factory){
synchronized (TxEditorPart.class) {
if (waveformDbFactory == factory) waveformDbFactory = null;
}
}
public static final String ID = "com.minres.scviewer.ui.TxEditorPart"; //$NON-NLS-1$
@@ -90,20 +94,22 @@ public class TxEditorPart extends EditorPart implements ITabbedPropertySheetPage
@Override
public void createPartControl(Composite parent) {
myParent=parent;
display = parent.getDisplay();
database=waveformDbFactory.getDatabase();
database.addPropertyChangeListener(new PropertyChangeListener() {
databaseListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if("WAVEFORMS".equals(evt.getPropertyName())) {
myParent.getDisplay().syncExec(new Runnable() {
com.minres.scviewer.database.ui.UiDispatch.async(display, new Runnable() {
@Override
public void run() {
waveformView.setMaxTime(database.getMaxTime());
if (!disposed && !myParent.isDisposed()) waveformView.setMaxTime(database.getMaxTime());
}
});
}
}
});
};
database.addPropertyChangeListener(databaseListener);
WaveformViewFactory factory = new WaveformViewFactory();
waveformView = factory.createPanel(parent);
waveformView.setMaxTime(0);
@@ -202,10 +208,10 @@ public class TxEditorPart extends EditorPart implements ITabbedPropertySheetPage
database.load(files[1]);
pm.worked(1);
}
myParent.getDisplay().syncExec(new Runnable() {
com.minres.scviewer.database.ui.UiDispatch.async(display, new Runnable() {
@Override
public void run() {
updateTxDisplay();
if (!disposed && !myParent.isDisposed()) updateTxDisplay();
}
});
} catch (Exception e) {
@@ -361,14 +367,25 @@ public class TxEditorPart extends EditorPart implements ITabbedPropertySheetPage
}
public void setSelection(final ISelection selection){
myParent.getDisplay().asyncExec(new Runnable() {
com.minres.scviewer.database.ui.UiDispatch.async(display, new Runnable() {
@Override
public void run() {
waveformView.setSelection(selection);
if (!disposed && !myParent.isDisposed()) waveformView.setSelection(selection);
}
});
}
@Override public void dispose() {
disposed = true;
if (database != null) {
database.removePropertyChangeListener(databaseListener);
database.removePropertyChangeListener(waveformView);
var closing = database;
org.eclipse.core.runtime.jobs.Job.create("Close Database", monitor -> { closing.close(); return org.eclipse.core.runtime.Status.OK_STATUS; }).schedule();
}
super.dispose();
}
public ISelection getSelection(){
return waveformView.getSelection();
}
@@ -52,6 +52,9 @@ public class TxOutlinePage extends ContentOutlinePage implements ISelectionList
private TxEditorPart editor;
TreeViewer contentOutlineViewer ;
private org.eclipse.swt.widgets.Display display;
private com.minres.scviewer.database.IWaveformDb observedDatabase;
private volatile boolean disposed;
public TxOutlinePage(TxEditorPart editor) {
this.editor = editor;
@@ -66,6 +69,8 @@ public class TxOutlinePage extends ContentOutlinePage implements ISelectionList
*/
public void createControl(Composite parent) {
super.createControl(parent);
display = parent.getDisplay();
observedDatabase = editor.getDatabase();
contentOutlineViewer = getTreeViewer();
contentOutlineViewer.addSelectionChangedListener(this);
// Set up the tree viewer
@@ -87,7 +92,7 @@ public class TxOutlinePage extends ContentOutlinePage implements ISelectionList
getSite().getPage().addSelectionListener((ISelectionListener) this);
//getSite().getPage().addSelectionListener("SampleViewId",(ISelectionListener)this);
getSite().setSelectionProvider(this);
editor.getDatabase().addPropertyChangeListener(this);
observedDatabase.addPropertyChangeListener(this);
}
/*
@@ -96,7 +101,10 @@ public class TxOutlinePage extends ContentOutlinePage implements ISelectionList
* @see org.eclipse.ui.part.IPage#dispose()
*/
public void dispose() {
// dispose
disposed = true;
if (observedDatabase != null) observedDatabase.removePropertyChangeListener(this);
if (getSite() != null) getSite().getPage().removeSelectionListener(this);
if (contentOutlineViewer != null) contentOutlineViewer.removeSelectionChangedListener(this);
super.dispose();
}
@@ -213,7 +221,10 @@ public class TxOutlinePage extends ContentOutlinePage implements ISelectionList
@Override
public void propertyChange(PropertyChangeEvent evt) {
if("CHILDS".equals(evt.getPropertyName())) {
contentOutlineViewer.refresh();
if (!disposed && display != null) com.minres.scviewer.database.ui.UiDispatch.async(display, () -> {
if (!disposed && evt.getSource() == observedDatabase && contentOutlineViewer != null
&& !contentOutlineViewer.getControl().isDisposed()) contentOutlineViewer.refresh();
});
}
}
@@ -45,6 +45,18 @@ public class CombinedBitVectorTest {
}
private String value(EventEntry entry) { return entry == null ? null : entry.events[0].toString(); }
@Test public void cancellationStopsAnUnchangedHistoryScanAndAllowsRetry() {
var input = new Signal(0, "input", 2);
for (int i = 0; i < 1000; i++) input.addSignalChange(i, BitVector.fromString(2, i % 2 == 0 ? "00" : "10"));
var bus = combine(input, input);
AtomicInteger checks = new AtomicInteger();
try {
ReadCancellation.with(() -> checks.incrementAndGet() > 30, () -> bus.getEvents().floorEntry(999));
fail("History scan ignored cancellation");
} catch (java.util.concurrent.CancellationException expected) { }
assertEquals(0, bus.getEvents().floorEntry(999).timestamp);
}
@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");
@@ -49,6 +49,51 @@ public class SQLiteBatchTest {
} finally { workers.shutdownNow(); }
}
@Test public void relationReadersWaitForCompletedInitialization() throws Exception {
var entered = new java.util.concurrent.CountDownLatch(1);
var release = new java.util.concurrent.CountDownLatch(1);
var recording = java.nio.file.Files.createTempFile("scviewer-relations-", ".txdb");
java.nio.file.Files.copy(TxTestSupport.input("my_sqldb.txdb").toPath(), recording, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
class BlockingDatabase extends Database {
volatile boolean block;
@Override public String getConnectionUrl() { return "jdbc:sqlite:" + recording; }
@Override public Connection createConnection() throws SQLException {
if (block) {
entered.countDown();
try { assertTrue(release.await(5, java.util.concurrent.TimeUnit.SECONDS)); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new SQLException(e); }
}
return super.createConnection();
}
}
BlockingDatabase database = new BlockingDatabase();
ScvStream row = new ScvStream(); row.setId(1); row.setName("test"); row.setKind("test");
TxStream stream = new TxStream(database, row);
try (Connection connection = database.createConnection(); var statement = connection.createStatement()) {
statement.executeUpdate("DELETE FROM ScvTxRelation");
}
ITx transaction = stream.getTransactionList().get(0);
int before = database.connections;
database.block = true;
var workers = java.util.concurrent.Executors.newFixedThreadPool(2);
try {
var first = workers.submit(transaction::getIncomingRelations);
assertTrue(entered.await(5, java.util.concurrent.TimeUnit.SECONDS));
var secondStarted = new java.util.concurrent.CountDownLatch(1);
var second = workers.submit(() -> { secondStarted.countDown(); return transaction.getIncomingRelations(); });
assertTrue(secondStarted.await(5, java.util.concurrent.TimeUnit.SECONDS));
try { second.get(100, java.util.concurrent.TimeUnit.MILLISECONDS); fail("Published an unfinished relation list"); }
catch (java.util.concurrent.TimeoutException expected) { }
release.countDown();
assertTrue(first.get(5, java.util.concurrent.TimeUnit.SECONDS).isEmpty());
assertTrue(second.get(5, java.util.concurrent.TimeUnit.SECONDS).isEmpty());
assertEquals(before + 1, database.connections);
} finally {
release.countDown(); workers.shutdownNow();
java.nio.file.Files.deleteIfExists(recording);
}
}
@Test
public void loadsAllTimesInOneQueryAndSharesGeneratorTransactions() {
Database database = new Database();
@@ -0,0 +1,131 @@
/*******************************************************************************
* 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.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Test;
import com.minres.scviewer.database.*;
public class ThreadingTest {
@Test public void registryPublishesEveryNameAndOneIdentity() throws Exception {
String prefix = UUID.randomUUID().toString();
ExecutorService pool = Executors.newFixedThreadPool(8);
CountDownLatch start = new CountDownLatch(1);
try {
List<Future<List<RelationType>>> results = new ArrayList<>();
for (int thread = 0; thread < 8; thread++) {
int id = thread;
results.add(pool.submit(() -> {
start.await();
List<RelationType> values = new ArrayList<>();
for (int i = 0; i < 2000; i++) {
values.add(RelationTypeFactory.create(prefix + ":" + id + ":" + i));
assertSame(RelationTypeFactory.create(prefix), RelationTypeFactory.create(prefix));
}
return values;
}));
}
start.countDown();
for (int thread = 0; thread < results.size(); thread++) {
List<RelationType> values = results.get(thread).get(10, TimeUnit.SECONDS);
for (int i = 0; i < values.size(); i++) assertSame(values.get(i), RelationTypeFactory.create(prefix + ":" + thread + ":" + i));
}
} finally { pool.shutdownNow(); }
}
@Test public void hierarchyReturnsStableSnapshotsWithInitializedParents() {
HierNode root = new HierNode("root");
HierNode first = new HierNode("first");
root.addChild(first);
List<IHierNode> snapshot = root.getChildNodes();
root.addChild(new HierNode("second"));
assertEquals(List.of(first), snapshot);
assertSame(root, snapshot.get(0).getParent());
assertEquals(2, root.getChildNodes().size());
}
@Test public void closureWaitsForReadersAndRejectsStaleReferences() throws Exception {
WaveformAccess.Scope scope = new WaveformAccess.Scope();
EmptyWaveform wave = new EmptyWaveform("wave");
scope.register(List.of(wave));
CountDownLatch entered = new CountDownLatch(1), release = new CountDownLatch(1);
AtomicBoolean disposed = new AtomicBoolean();
ExecutorService pool = Executors.newFixedThreadPool(3);
try {
Future<?> reader = pool.submit(() -> WaveformAccess.read(wave, () -> {
entered.countDown();
try { assertTrue(release.await(5, TimeUnit.SECONDS)); }
catch (InterruptedException e) { throw new AssertionError(e); }
assertFalse(disposed.get());
return null;
}));
assertTrue(entered.await(5, TimeUnit.SECONDS));
CountDownLatch closing = new CountDownLatch(1);
Future<?> close = pool.submit(() -> { closing.countDown(); scope.close(() -> disposed.set(true)); });
assertTrue(closing.await(5, TimeUnit.SECONDS));
Future<?> rejected = pool.submit(() -> {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (System.nanoTime() < deadline) {
try { WaveformAccess.read(wave, () -> null); }
catch (CancellationException expected) { return; }
Thread.yield();
}
fail("New readers were admitted during closure");
});
rejected.get(5, TimeUnit.SECONDS);
assertFalse(disposed.get());
release.countDown();
reader.get(5, TimeUnit.SECONDS); close.get(5, TimeUnit.SECONDS);
assertTrue(disposed.get());
try { WaveformAccess.read(wave, () -> null); fail("Read a closed recording"); }
catch (CancellationException expected) { }
} finally { release.countDown(); pool.shutdownNow(); }
}
@Test public void cancelledLazyInitializationCanRetry() {
LazyValue<String> value = new LazyValue<>();
try { value.get(() -> { throw new CancellationException(); }); fail(); }
catch (CancellationException expected) { }
assertEquals("complete", value.get(() -> "complete"));
}
@Test public void lazyWaiterCancelsWithoutBlockingOrCancellingOwner() throws Exception {
LazyValue<String> value = new LazyValue<>();
ExecutorService pool = Executors.newFixedThreadPool(2);
CountDownLatch entered = new CountDownLatch(1), release = new CountDownLatch(1);
AtomicBoolean cancelled = new AtomicBoolean();
CountDownLatch waiterWaiting = new CountDownLatch(1);
java.util.concurrent.atomic.AtomicInteger checks = new java.util.concurrent.atomic.AtomicInteger();
try {
Future<String> owner = pool.submit(() -> value.get(() -> {
entered.countDown();
try { assertTrue(release.await(5, TimeUnit.SECONDS)); }
catch (InterruptedException e) { throw new AssertionError(e); }
return "complete";
}));
assertTrue(entered.await(5, TimeUnit.SECONDS));
Future<String> waiter = pool.submit(() -> ReadCancellation.with(() -> {
if (checks.incrementAndGet() >= 2) waiterWaiting.countDown();
return cancelled.get();
}, () -> value.get(() -> "wrong")));
assertTrue("Waiter never reached cancellable lazy wait", waiterWaiting.await(5, TimeUnit.SECONDS));
cancelled.set(true);
try { waiter.get(2, TimeUnit.SECONDS); fail(); }
catch (ExecutionException expected) { assertTrue(expected.getCause() instanceof CancellationException); }
assertFalse(owner.isDone());
release.countDown();
assertEquals("complete", owner.get(5, TimeUnit.SECONDS));
} finally { release.countDown(); pool.shutdownNow(); }
}
}
@@ -0,0 +1,27 @@
/*******************************************************************************
* 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.internal.status;
import static org.junit.Assert.*;
import org.junit.Test;
public class JobProgressTest {
@Test public void cancellationAndProgressBelongToOneJob() {
JobProgress first = new JobProgress(() -> {}), second = new JobProgress(() -> {});
first.beginTask("first", 10); second.beginTask("second", 20);
first.worked(3); second.worked(8); first.setCanceled(true); first.done();
assertTrue(first.isCanceled()); assertFalse(second.isCanceled());
assertTrue(first.snapshot().done()); assertFalse(second.snapshot().done());
assertEquals("second", second.snapshot().name());
assertEquals(8, second.snapshot().work(), 0);
assertFalse(new JobProgress(() -> {}).isCanceled());
}
}
@@ -70,4 +70,38 @@ public class LatestJobTest {
query.schedule("closed", monitor -> { fail("Disposed query must not run"); return ""; });
assertTrue(displayed.isEmpty());
}
@Test public void additiveRequestsBothPublishAndCloseDiscardsQueuedResults() throws Exception {
BlockingQueue<Runnable> ui = new LinkedBlockingQueue<>();
List<String> displayed = new ArrayList<>();
try (LatestJob<String> jobs = new LatestJob<>(ui::add, displayed::add, false)) {
jobs.schedule("first vector", monitor -> "first");
Runnable first = take(ui);
jobs.schedule("second vector", monitor -> "second");
Runnable second = take(ui);
first.run(); second.run();
assertEquals(List.of("first", "second"), displayed);
jobs.schedule("stale", monitor -> "stale");
Runnable stale = take(ui);
jobs.cancel(); stale.run();
assertEquals(2, displayed.size());
}
}
@Test public void cancellingJobReachesNestedReadContext() throws Exception {
BlockingQueue<Runnable> ui = new LinkedBlockingQueue<>();
java.util.concurrent.CountDownLatch entered = new java.util.concurrent.CountDownLatch(1);
java.util.concurrent.CountDownLatch stopped = new java.util.concurrent.CountDownLatch(1);
try (LatestJob<String> query = new LatestJob<>(ui::add, ignored -> fail("Cancelled job published"))) {
query.schedule("long read", monitor -> {
entered.countDown();
try { while (true) com.minres.scviewer.database.ReadCancellation.check(); }
finally { stopped.countDown(); }
});
assertTrue(entered.await(5, TimeUnit.SECONDS));
query.cancel();
assertTrue(stopped.await(5, TimeUnit.SECONDS));
assertTrue(ui.isEmpty());
}
}
}
@@ -125,4 +125,29 @@ public class TransactionQueryTest {
assertEquals(0, reads.get());
assertEquals(0, wave.requests);
}
@Test public void slowPropertyDiscoveryDoesNotBlockHeaderRequests() throws Exception {
var entered = new java.util.concurrent.CountDownLatch(1);
var release = new java.util.concurrent.CountDownLatch(1);
Waveform wave = new Waveform();
ITx slow = (ITx) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{ITx.class}, (p, m, a) -> {
if (m.getName().equals("getAttributes")) {
entered.countDown();
assertTrue(release.await(5, java.util.concurrent.TimeUnit.SECONDS));
return List.of();
}
return 1L;
});
wave.transactions = List.of(slow);
TransactionQuery query = new TransactionQuery(wave);
var workers = java.util.concurrent.Executors.newFixedThreadPool(2);
try {
var discovery = workers.submit(() -> query.discoverAttributes(() -> false));
assertTrue(entered.await(5, java.util.concurrent.TimeUnit.SECONDS));
assertSame(wave.transactions, workers.submit(() -> query.transactions(() -> false))
.get(1, java.util.concurrent.TimeUnit.SECONDS));
release.countDown();
assertTrue(discovery.get(5, java.util.concurrent.TimeUnit.SECONDS).isEmpty());
} finally { release.countDown(); workers.shutdownNow(); }
}
}
@@ -113,12 +113,12 @@ public class BitVectorExpansionTest {
}
@Test
public void realScalarAndEmptySignalsCannotBeExpanded() {
Signal real = new Signal("real", 64);
public void realAndScalarSignalsCannotBeExpanded() {
Signal real = new Signal("real", 64) { @Override public boolean isBitVector() { return false; } };
real.events.put(0, new DoubleVal(1.5));
Signal scalar = new Signal("scalar", 1);
scalar.events.put(0, BitVector.fromString(1, "1"));
for (Signal source : List.of(real, scalar, new Signal("empty", 8))) {
for (Signal source : List.of(real, scalar)) {
TrackEntry track = new TrackEntry(source, null);
track.setExpanded(true);
assertFalse(track.isExpandable());
@@ -127,6 +127,16 @@ public class BitVectorExpansionTest {
}
}
@Test public void vectorMetadataDoesNotReadEventsOnTheUiThread() {
Signal source = new Signal("lazy", 8) {
@Override public IEventList getEvents() { throw new AssertionError("Metadata triggered I/O"); }
};
TrackEntry track = new TrackEntry(source, null);
assertTrue(track.isExpandable());
track.setExpanded(true);
assertEquals(8, track.waveforms.size());
}
@Test
public void savedExpansionPreservesHiddenBitsAndResolvesProjectedNames() throws Exception {
Signal source = new Signal("top.bus[3:0]", 4);
@@ -52,7 +52,7 @@ public class CombinedVectorSettingsTest {
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);
var real = new BitVectorExpansionTest.Signal("real", 1) { @Override public boolean isBitVector() { return false; } };
real.events.put(0, new DoubleVal(1.0));
assertFalse(BitVectorComposition.isSingleBit(new TrackEntry(real, null)));
var sources = BitVectorComposition.sources(List.of(second, first));
@@ -112,7 +112,10 @@ public class TransactionListPropertiesTest {
case "getId" -> id;
case "getBeginTime" -> 0L;
case "getEndTime" -> 1L;
case "getAttributes" -> List.of(attributes);
case "getAttributes" -> {
assertNull("A label callback read attributes on SWT", Display.getCurrent());
yield List.of(attributes);
}
case "hashCode" -> System.identityHashCode(p);
case "equals" -> p == a[0];
case "toString" -> "tx#" + id;
@@ -136,6 +139,7 @@ public class TransactionListPropertiesTest {
await(() -> shown.getItemCount() == 2 && table.getItemCount() == 1);
assertEquals("late [STRING]", search.getText());
assertEquals("late [STRING]", shown.getText());
await(() -> "last".equals(table.getItem(0).getText(2)));
assertEquals("last", table.getItem(0).getText(2));
}
@@ -145,6 +149,7 @@ public class TransactionListPropertiesTest {
await(() -> shown.getSelectionIndex() >= 0 && table.getItemCount() == 1);
assertEquals("address [STRING]", shown.getText());
assertEquals("address [STRING]", search.getText());
await(() -> "value".equals(table.getItem(0).getText(2)));
assertEquals("value", table.getItem(0).getText(2));
}
@@ -156,6 +161,7 @@ public class TransactionListPropertiesTest {
input(transactions.toArray(new ITx[0]));
await(() -> shown.getItemCount() == 3 && table.getItemCount() == 33);
shown.select(1); shown.notifyListeners(SWT.Selection, new Event());
await(() -> "second".equals(table.getItem(0).getText(2)));
assertEquals("second", table.getItem(0).getText(2));
assertTrue(Arrays.asList(shown.getItems()).contains("late [STRING]"));
list.setVisible(false);
@@ -169,22 +175,26 @@ public class TransactionListPropertiesTest {
input(transaction(1, attribute("alpha", "first"), attribute("beta", "chosen")));
await(() -> shown.getItemCount() == 2 && table.getItemCount() == 1);
shown.select(1); shown.notifyListeners(SWT.Selection, new Event());
await(() -> "chosen".equals(table.getItem(0).getText(2)));
assertEquals("chosen", table.getItem(0).getText(2));
// The preferred property is no longer the second entry in the new stream.
input(transaction(2, attribute("aardvark", "a"), attribute("alpha", "b"), attribute("beta", "restored")));
await(() -> shown.getItemCount() == 3 && table.getItemCount() == 1);
assertEquals("beta [STRING]", shown.getText());
await(() -> "restored".equals(table.getItem(0).getText(2)));
assertEquals("restored", table.getItem(0).getText(2));
// A temporary fallback and a separator must not erase the user's preference.
input(transaction(3, attribute("other", "fallback")));
await(() -> shown.getText().equals("other [STRING]") && table.getItemCount() == 1);
await(() -> "fallback".equals(table.getItem(0).getText(2)));
assertEquals("fallback", table.getItem(0).getText(2));
listView.setSelection(new StructuredSelection(new TrackEntry(new EmptyWaveform(), null)));
input(transaction(4, attribute("alpha", "default"), attribute("beta", "remembered")));
await(() -> shown.getItemCount() == 2 && table.getItemCount() == 1);
assertEquals("beta [STRING]", shown.getText());
await(() -> "remembered".equals(table.getItem(0).getText(2)));
assertEquals("remembered", table.getItem(0).getText(2));
// A subsequent explicit choice replaces the remembered preference.
@@ -192,6 +202,7 @@ public class TransactionListPropertiesTest {
input(transaction(5, attribute("aardvark", "default"), attribute("alpha", "new preference"), attribute("beta", "old")));
await(() -> shown.getItemCount() == 3 && table.getItemCount() == 1);
assertEquals("alpha [STRING]", shown.getText());
await(() -> "new preference".equals(table.getItem(0).getText(2)));
assertEquals("new preference", table.getItem(0).getText(2));
}
@@ -209,6 +220,7 @@ public class TransactionListPropertiesTest {
list.setVisible(true);
await(() -> shown.getItemCount() == 1 && table.getItemCount() == 1);
assertEquals("address [STRING]", shown.getText());
await(() -> "value".equals(table.getItem(0).getText(2)));
assertEquals("value", table.getItem(0).getText(2));
}
@@ -217,6 +229,7 @@ public class TransactionListPropertiesTest {
input(transaction(1, attribute("old", "old value")));
input(transaction(2, attribute("new", "new value")));
await(() -> shown.getText().equals("new [STRING]") && table.getItemCount() == 1);
await(() -> "new value".equals(table.getItem(0).getText(2)));
assertEquals("new value", table.getItem(0).getText(2));
listView.setSelection(new StructuredSelection(new TrackEntry(new EmptyWaveform(), null)));
assertEquals(0, shown.getItemCount());
@@ -176,6 +176,7 @@ public class WaveformScrollTest {
assertSame(bus, ((StructuredSelection) view.getSelection()).getFirstElement());
view.setGroupExpanded(bus, true);
assertEquals(6, TrackEntry.visibleTracks(view.getStreamList()).size());
waitUntil(() -> "b'1".equals(bus.waveforms.get(0).currentValue) && "b'0".equals(bus.waveforms.get(1).currentValue));
assertEquals("b'1", bus.waveforms.get(0).currentValue);
assertEquals("b'0", bus.waveforms.get(1).currentValue);
view.setGroupExpanded(bus, false);
@@ -270,8 +271,53 @@ public class WaveformScrollTest {
} finally { if (dialog.getShell() != null && !dialog.getShell().isDisposed()) dialog.close(); }
}
@Test public void lazySignalReadsStayOffSwtAndQueuedUpdatesSurviveDisposal() throws Exception {
var reads = new java.util.concurrent.atomic.AtomicInteger();
var source = new BitVectorExpansionTest.Signal("lazy", 4) {
@Override public com.minres.scviewer.database.IEventList getEvents() {
assertNull("Lazy signal read on SWT", Display.getCurrent());
reads.incrementAndGet();
return events;
}
};
source.events.put(0, com.minres.scviewer.database.BitVector.fromString(4, "1010"));
TrackEntry track = view.addWaveform(source, -1);
view.setCursorTime(0); view.update();
waitUntil(() -> !track.currentValue.equals("---") && reads.get() > 0);
invokeView("asyncUpdate", new Class<?>[]{org.eclipse.swt.widgets.Widget.class}, canvas);
shell.dispose();
drainEvents();
}
@Test public void disposingPressedImageButtonStopsItsRepeatTimer() throws Exception {
Class<?> type = view.getClass().getClassLoader().loadClass(
"com.minres.scviewer.database.ui.swt.internal.slider.ImageButton");
var button = (org.eclipse.swt.widgets.Composite) type.getConstructor(org.eclipse.swt.widgets.Composite.class, int.class)
.newInstance(shell, SWT.NONE);
type.getMethod("setAutoFire", boolean.class).invoke(button, true);
button.notifyListeners(SWT.MouseDown, new Event());
var field = type.getDeclaredField("actionTimer"); field.setAccessible(true);
Runnable timer = (Runnable) field.get(button);
button.dispose();
timer.run();
drainEvents();
}
@Test public void twoRapidCombineCommandsBothCreateVectors() throws Exception {
var inputs = scalarInputs();
WaveformViewer viewer = compositionViewer(display::asyncExec);
try {
viewer.combineBits("first", inputs);
viewer.combineBits("second", inputs);
waitUntil(() -> view.getStreamList().size() == 4);
assertEquals(java.util.Set.of("first", "second"), view.getStreamList().stream()
.filter(track -> track.waveform instanceof com.minres.scviewer.database.CombinedBitVectorWaveform)
.map(track -> track.waveform.getDisplayName()).collect(java.util.stream.Collectors.toSet()));
} finally { viewer.closeDatabase(); }
}
@Test
public void bitvectorDisclosureUpdatesAllPanesAndCursorValues() {
public void bitvectorDisclosureUpdatesAllPanesAndCursorValues() throws Exception {
var source = new BitVectorExpansionTest.Signal("bus", 4);
source.events.put(10, com.minres.scviewer.database.BitVector.fromString(4, "10xz"));
source.events.put(20, com.minres.scviewer.database.BitVector.fromString(4, "0011"));
@@ -287,10 +333,12 @@ public class WaveformScrollTest {
view.getNameControl().notifyListeners(SWT.MouseUp, event);
drainEvents();
assertEquals(TrackEntry.HierState.OPENED, bus.hierState);
waitUntil(() -> bus.waveforms.stream().map(track -> track.currentValue).toList().equals(List.of("b'1", "b'0", "b'x", "b'z")));
assertEquals(List.of("b'1", "b'0", "b'x", "b'z"),
bus.waveforms.stream().map(track -> track.currentValue).toList());
view.setCursorTime(20);
view.update();
waitUntil(() -> bus.waveforms.stream().map(track -> track.currentValue).toList().equals(List.of("b'0", "b'0", "b'1", "b'1")));
assertEquals(List.of("b'0", "b'0", "b'1", "b'1"),
bus.waveforms.stream().map(track -> track.currentValue).toList());
view.getNameControl().notifyListeners(SWT.MouseUp, event);