From 28eb1b673e5ad9f28299021f40883a0d03895710 Mon Sep 17 00:00:00 2001 From: Eyck Jentzsch Date: Fri, 20 Nov 2026 22:31:48 +0100 Subject: [PATCH] applies concurrency fixes --- AGENTS.md | 113 +++++++++++ .../scviewer/database/fst/FstDbLoader.java | 6 +- .../scviewer/database/fst/FstFileParser.java | 14 +- .../database/ftr/AbstractTxStream.java | 2 +- .../database/sqlite/AbstractTxStream.java | 4 +- .../minres/scviewer/database/sqlite/Tx.java | 14 +- .../database/text/AbstractTxStream.java | 2 +- .../database/ui/AsyncTransactionData.java | 85 +++++++++ .../database/ui/BitVectorComposition.java | 6 +- .../scviewer/database/ui/BitWaveform.java | 3 +- .../scviewer/database/ui/TrackEntry.java | 10 +- .../scviewer/database/ui/UiDispatch.java | 25 +++ .../ui/swt/internal/ArrowPainter.java | 10 +- .../ui/swt/internal/SignalPainter.java | 8 +- .../ui/swt/internal/StreamPainter.java | 29 +-- .../ui/swt/internal/WaveformCanvas.java | 43 ++++- .../ui/swt/internal/WaveformData.java | 145 +++++++++++++++ .../ui/swt/internal/WaveformView.java | 47 +++-- .../ui/swt/internal/slider/ActionTimer.java | 15 +- .../ui/swt/internal/slider/ImageButton.java | 5 +- .../database/ui/swt/sb/ActionScheduler.java | 4 +- .../database/ui/swt/sb/ClickControl.java | 3 +- .../ui/swt/sb/MouseDownActionTimer.java | 8 +- .../database/CombinedBitVectorWaveform.java | 5 +- .../minres/scviewer/database/HierNode.java | 14 +- .../minres/scviewer/database/IWaveform.java | 7 + .../minres/scviewer/database/LazyValue.java | 38 ++-- .../scviewer/database/ReadCancellation.java | 32 ++++ .../database/RelationTypeFactory.java | 13 +- .../scviewer/database/WaveformAccess.java | 89 +++++++++ .../database/internal/WaveformDb.java | 26 ++- .../database/tx/TransactionLists.java | 5 +- .../scviewer/database/tx/TxIntervalIndex.java | 5 +- .../application/handlers/UpdateHandler.java | 28 +-- .../internal/status/HeapStatus.java | 4 +- .../internal/status/JobProgress.java | 43 +++++ .../internal/status/StatusBarControl.java | 175 +++++------------- .../application/internal/util/LatestJob.java | 54 ++++-- .../internal/util/TransactionQuery.java | 50 +++-- .../internal/util/ViewerSettings.java | 5 +- .../application/parts/TransactionDetails.java | 36 +++- .../e4/application/parts/TransactionList.java | 5 +- .../e4/application/parts/WaveformViewer.java | 155 ++++++++++++---- .../txTableTree/AttributeLabelProvider.java | 21 ++- .../com/minres/scviewer/ui/TxEditorPart.java | 47 +++-- .../scviewer/ui/views/TxOutlinePage.java | 19 +- .../database/test/CombinedBitVectorTest.java | 12 ++ .../database/test/SQLiteBatchTest.java | 45 +++++ .../scviewer/database/test/ThreadingTest.java | 131 +++++++++++++ .../internal/status/JobProgressTest.java | 27 +++ .../internal/util/LatestJobTest.java | 34 ++++ .../internal/util/TransactionQueryTest.java | 25 +++ .../parts/BitVectorExpansionTest.java | 16 +- .../parts/CombinedVectorSettingsTest.java | 2 +- .../parts/TransactionListPropertiesTest.java | 15 +- .../application/parts/WaveformScrollTest.java | 50 ++++- 56 files changed, 1462 insertions(+), 372 deletions(-) create mode 100644 AGENTS.md create mode 100644 plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/AsyncTransactionData.java create mode 100644 plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/UiDispatch.java create mode 100644 plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/WaveformData.java create mode 100644 plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/ReadCancellation.java create mode 100644 plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/WaveformAccess.java create mode 100644 plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/status/JobProgress.java create mode 100644 tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/ThreadingTest.java create mode 100644 tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/internal/status/JobProgressTest.java diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..dfd9d3a4 --- /dev/null +++ b/AGENTS.md @@ -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//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 `` as ``. +- 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. diff --git a/plugins/com.minres.scviewer.database.fst/src/com/minres/scviewer/database/fst/FstDbLoader.java b/plugins/com.minres.scviewer.database.fst/src/com/minres/scviewer/database/fst/FstDbLoader.java index 07eae93c..daaacd00 100644 --- a/plugins/com.minres.scviewer.database.fst/src/com/minres/scviewer/database/fst/FstDbLoader.java +++ b/plugins/com.minres.scviewer.database.fst/src/com/minres/scviewer/database/fst/FstDbLoader.java @@ -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); } diff --git a/plugins/com.minres.scviewer.database.fst/src/com/minres/scviewer/database/fst/FstFileParser.java b/plugins/com.minres.scviewer.database.fst/src/com/minres/scviewer/database/fst/FstFileParser.java index 0c5977ae..26bc3bbd 100644 --- a/plugins/com.minres.scviewer.database.fst/src/com/minres/scviewer/database/fst/FstFileParser.java +++ b/plugins/com.minres.scviewer.database.fst/src/com/minres/scviewer/database/fst/FstFileParser.java @@ -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() { - FstLibrary.fstReaderClose(fst); + public synchronized void close() { + if (fst != null) { + FstLibrary.fstReaderClose(fst); + fst = null; + } } } diff --git a/plugins/com.minres.scviewer.database.ftr/src/com/minres/scviewer/database/ftr/AbstractTxStream.java b/plugins/com.minres.scviewer.database.ftr/src/com/minres/scviewer/database/ftr/AbstractTxStream.java index fc493857..51f5614d 100644 --- a/plugins/com.minres.scviewer.database.ftr/src/com/minres/scviewer/database/ftr/AbstractTxStream.java +++ b/plugins/com.minres.scviewer.database.ftr/src/com/minres/scviewer/database/ftr/AbstractTxStream.java @@ -35,7 +35,7 @@ abstract class AbstractTxStream extends HierNode implements IWaveform, ITransact @Override public List getTransactionList() { - return transactionList.get(() -> TransactionLists.fromEvents(getEvents(), () -> false)); + return transactionList.get(() -> TransactionLists.fromEvents(getEvents(), () -> { com.minres.scviewer.database.ReadCancellation.check(); return false; })); } @Override diff --git a/plugins/com.minres.scviewer.database.sqlite/src/com/minres/scviewer/database/sqlite/AbstractTxStream.java b/plugins/com.minres.scviewer.database.sqlite/src/com/minres/scviewer/database/sqlite/AbstractTxStream.java index d68f5acd..07e0facc 100644 --- a/plugins/com.minres.scviewer.database.sqlite/src/com/minres/scviewer/database/sqlite/AbstractTxStream.java +++ b/plugins/com.minres.scviewer.database.sqlite/src/com/minres/scviewer/database/sqlite/AbstractTxStream.java @@ -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; } diff --git a/plugins/com.minres.scviewer.database.sqlite/src/com/minres/scviewer/database/sqlite/Tx.java b/plugins/com.minres.scviewer.database.sqlite/src/com/minres/scviewer/database/sqlite/Tx.java index c0885aa8..f415d178 100644 --- a/plugins/com.minres.scviewer.database.sqlite/src/com/minres/scviewer/database/sqlite/Tx.java +++ b/plugins/com.minres.scviewer.database.sqlite/src/com/minres/scviewer/database/sqlite/Tx.java @@ -106,37 +106,39 @@ public class Tx implements ITx { } @Override - public Collection getIncomingRelations() { + public synchronized Collection getIncomingRelations() { if(incoming==null){ SQLiteDatabaseSelectHandler 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 getOutgoingRelations() { + public synchronized Collection getOutgoingRelations() { if(outgoing==null){ SQLiteDatabaseSelectHandler 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) { diff --git a/plugins/com.minres.scviewer.database.text/src/com/minres/scviewer/database/text/AbstractTxStream.java b/plugins/com.minres.scviewer.database.text/src/com/minres/scviewer/database/text/AbstractTxStream.java index a4790377..207217be 100644 --- a/plugins/com.minres.scviewer.database.text/src/com/minres/scviewer/database/text/AbstractTxStream.java +++ b/plugins/com.minres.scviewer.database.text/src/com/minres/scviewer/database/text/AbstractTxStream.java @@ -36,7 +36,7 @@ abstract class AbstractTxStream extends HierNode implements IWaveform, ITransact @Override public List getTransactionList() { - return transactionList.get(() -> TransactionLists.fromEvents(getEvents(), () -> false)); + return transactionList.get(() -> TransactionLists.fromEvents(getEvents(), () -> { com.minres.scviewer.database.ReadCancellation.check(); return false; })); } @Override diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/AsyncTransactionData.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/AsyncTransactionData.java new file mode 100644 index 00000000..bb3f24f7 --- /dev/null +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/AsyncTransactionData.java @@ -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 attributes, List incoming, List outgoing) { } + private static final Snapshot EMPTY = new Snapshot(List.of(), List.of(), List.of()); + private final Map values = new IdentityHashMap<>(); + private final Map jobs = new IdentityHashMap<>(); + private final java.util.ArrayDeque order = new java.util.ArrayDeque<>(); + private final boolean relations; + private final Consumer dispatch; + private final Consumer changed; + private volatile boolean closed; + public AsyncTransactionData(Consumer dispatch, Consumer changed) { + this(dispatch, changed, true); + } + public AsyncTransactionData(Consumer dispatch, Consumer 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(); + } +} diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitVectorComposition.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitVectorComposition.java index 36d499b7..68fcb4b1 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitVectorComposition.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitVectorComposition.java @@ -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 selectedBits(List roots, List selection) { diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitWaveform.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitWaveform.java index 30dc1b1b..6840e2cf 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitWaveform.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/BitWaveform.java @@ -39,7 +39,8 @@ public final class BitWaveform extends HierNode implements IWaveform { @Override public String getFullName() { return source.getFullName() + getName(); } @Override public String getDisplayName() { return source.getDisplayName() + getName(); } - public IWaveform getSource() { return source; } + @Override public java.util.List getReadSources() { return java.util.List.of(source); } + public IWaveform getSource() { return source; } public int getBitIndex() { return bit; } @Override public DirectionType getDirection() { return source.getDirection(); } @Override public long getId() { return source.getId(); } diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/TrackEntry.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/TrackEntry.java index 35992e54..b41ace91 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/TrackEntry.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/TrackEntry.java @@ -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 { @@ -93,11 +91,9 @@ public class TrackEntry { return bitVector; } - 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; - } + private static boolean isBitVector(IWaveform waveform) { + return waveform != null && waveform.getWidth() > 1 && waveform.isBitVector(); + } public boolean isExpandable() { return isGroup() || isBitVector(); diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/UiDispatch.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/UiDispatch.java new file mode 100644 index 00000000..6a6a8e04 --- /dev/null +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/UiDispatch.java @@ -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; } + } +} diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/ArrowPainter.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/ArrowPainter.java index 8f2b144b..3a401e4d 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/ArrowPainter.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/ArrowPainter.java @@ -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 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; } diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/SignalPainter.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/SignalPainter.java index 192f3898..fbce8718 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/SignalPainter.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/SignalPainter.java @@ -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; diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/StreamPainter.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/StreamPainter.java index 0b401298..f64b0d1d 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/StreamPainter.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/StreamPainter.java @@ -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 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 tracks) { + java.util.Set retained = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()); + collectWaveforms(tracks, retained); + data.retain(retained); + } + private void collectWaveforms(List tracks, java.util.Set 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 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 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(); diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/WaveformData.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/WaveformData.java new file mode 100644 index 00000000..0f09bb1a --- /dev/null +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/WaveformData.java @@ -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 values = new LinkedHashMap<>(32, .75f, true); + private final Map jobs = new LinkedHashMap<>(); + private final Consumer dispatch; + private final Runnable changed; + private volatile boolean closed; + WaveformData(Consumer 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 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(); + } +} diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/WaveformView.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/WaveformView.java index 4856c8b5..b5169882 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/WaveformView.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/WaveformView.java @@ -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 outRel = currentTxSelection.getOutgoingRelations(); + Collection 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 inRel = currentTxSelection.getIncomingRelations(); + Collection 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 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(); }); diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/slider/ActionTimer.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/slider/ActionTimer.java index 06850498..1303d764 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/slider/ActionTimer.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/slider/ActionTimer.java @@ -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() ) { - timerAction.run(); - display.timerExec( FAST_DELAY, this ); + if (active && !display.isDisposed() && timerAction.isEnabled()) { + timerAction.run(); + if (active && !display.isDisposed() && timerAction.isEnabled()) display.timerExec(FAST_DELAY, this); } } } \ No newline at end of file diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/slider/ImageButton.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/slider/ImageButton.java index fca078fd..fa49f3d9 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/slider/ImageButton.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/internal/slider/ImageButton.java @@ -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(); } }); diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/sb/ActionScheduler.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/sb/ActionScheduler.java index a9aa376e..d146d98d 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/sb/ActionScheduler.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/sb/ActionScheduler.java @@ -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); } } \ No newline at end of file diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/sb/ClickControl.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/sb/ClickControl.java index 9d95d7e1..75ca0688 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/sb/ClickControl.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/sb/ClickControl.java @@ -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 diff --git a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/sb/MouseDownActionTimer.java b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/sb/MouseDownActionTimer.java index 42f541e0..a7c0c996 100644 --- a/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/sb/MouseDownActionTimer.java +++ b/plugins/com.minres.scviewer.database.ui.swt/src/com/minres/scviewer/database/ui/swt/sb/MouseDownActionTimer.java @@ -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); } } } \ No newline at end of file diff --git a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/CombinedBitVectorWaveform.java b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/CombinedBitVectorWaveform.java index f904119a..67ad9e5e 100644 --- a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/CombinedBitVectorWaveform.java +++ b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/CombinedBitVectorWaveform.java @@ -65,6 +65,7 @@ public final class CombinedBitVectorWaveform extends HierNode implements IWavefo this.sources = List.copyOf(normalized); } + @Override public List getReadSources() { return sources.stream().map(SourceBit::waveform).toList(); } public List 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); } diff --git a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/HierNode.java b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/HierNode.java index 9abf33ff..294b839c 100644 --- a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/HierNode.java +++ b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/HierNode.java @@ -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 childNodes = Collections.synchronizedList(new ArrayList<>()); @@ -139,7 +139,7 @@ public class HierNode implements IHierNode { */ @Override public List 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) { - if (!childNodes.contains(child)) { - childNodes.add(child); - child.setParent(this); + synchronized (childNodes) { + if (!childNodes.contains(child)) { + child.setParent(this); + childNodes.add(child); + } } } diff --git a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/IWaveform.java b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/IWaveform.java index b9a2d603..c1115421 100644 --- a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/IWaveform.java +++ b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/IWaveform.java @@ -19,6 +19,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 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(); } diff --git a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/LazyValue.java b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/LazyValue.java index 5b501ebc..94878c3e 100644 --- a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/LazyValue.java +++ b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/LazyValue.java @@ -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 { 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 supplier) { - if (state == State.LOADED) return value; - if (state == State.FAILED) { - if (failure instanceof Error) throw (Error) failure; - throw (RuntimeException) failure; + public T get(Supplier 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 error) throw error; + throw (RuntimeException) failure; + } + owner = Thread.currentThread(); + state = State.LOADING; } - if (state == State.LOADING) throw new IllegalStateException("Recursive lazy loading"); - 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; } } diff --git a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/ReadCancellation.java b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/ReadCancellation.java new file mode 100644 index 00000000..dca20389 --- /dev/null +++ b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/ReadCancellation.java @@ -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 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 with(BooleanSupplier cancelled, Supplier 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); } + } +} diff --git a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/RelationTypeFactory.java b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/RelationTypeFactory.java index 2d2a7ca0..e645e95e 100644 --- a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/RelationTypeFactory.java +++ b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/RelationTypeFactory.java @@ -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 registry = new HashMap<>(); + private static ConcurrentHashMap registry = new ConcurrentHashMap<>(); } diff --git a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/WaveformAccess.java b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/WaveformAccess.java new file mode 100644 index 00000000..1e83e512 --- /dev/null +++ b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/WaveformAccess.java @@ -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 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 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 read(IWaveform waveform, Supplier query) { + return read(waveform == null ? List.of() : List.of(waveform), query); + } + public static T read(Collection waveforms, Supplier query) { + Map scopes = new IdentityHashMap<>(); + synchronized (OWNERS) { + for (IWaveform waveform : waveforms) collect(waveform, scopes); + } + List 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 scopes) { + Scope scope = OWNERS.get(waveform); + if (scope != null) scopes.put(scope, Boolean.TRUE); + else { + List sources = waveform.getReadSources(); + if (sources != null) for (IWaveform source : sources) if (source != null && source != waveform) collect(source, scopes); + } + } +} diff --git a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/internal/WaveformDb.java b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/internal/WaveformDb.java index 16a7bc76..1f592b74 100644 --- a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/internal/WaveformDb.java +++ b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/internal/WaveformDb.java @@ -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 loaderFactories = new CopyOnWriteArrayList<>(); + private final ReentrantLock lifecycle = new ReentrantLock(); + private WaveformAccess.Scope readScope = new WaveformAccess.Scope(); + private List 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 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 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 getAllRelationTypes() { - return relationTypes; + public synchronized List getAllRelationTypes() { + return List.copyOf(relationTypes); } } diff --git a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/tx/TransactionLists.java b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/tx/TransactionLists.java index dee35a36..9d316335 100644 --- a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/tx/TransactionLists.java +++ b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/tx/TransactionLists.java @@ -27,9 +27,11 @@ public final class TransactionLists { public static List fromEvents(IEventList events, BooleanSupplier cancelled) { List 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 sorted(java.util.Collection transactions) { List sorted = new ArrayList<>(transactions); - sorted.sort(Comparator.comparingLong(ITx::getBeginTime).thenComparingLong(ITx::getId)); + Comparator 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); } } diff --git a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/tx/TxIntervalIndex.java b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/tx/TxIntervalIndex.java index 63fdcdac..29199f36 100644 --- a/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/tx/TxIntervalIndex.java +++ b/plugins/com.minres.scviewer.database/src/com/minres/scviewer/database/tx/TxIntervalIndex.java @@ -26,6 +26,7 @@ public final class TxIntervalIndex { final Node left, right; Node(List 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 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()); } diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/handlers/UpdateHandler.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/handlers/UpdateHandler.java index 9a3e31dc..4f014980 100644 --- a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/handlers/UpdateHandler.java +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/handlers/UpdateHandler.java @@ -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) { - e.printStackTrace(); - } + 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; diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/status/HeapStatus.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/status/HeapStatus.java index 33b33579..73c10385 100644 --- a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/status/HeapStatus.java +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/status/HeapStatus.java @@ -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); }); diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/status/JobProgress.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/status/JobProgress.java new file mode 100644 index 00000000..b2ce4b5f --- /dev/null +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/status/JobProgress.java @@ -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); } +} diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/status/StatusBarControl.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/status/StatusBarControl.java index f1a598a3..0cd0f004 100644 --- a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/status/StatusBarControl.java +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/status/StatusBarControl.java @@ -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 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()); - Job.getJobManager().setProgressProvider(new ProgressProvider() { - @Override - public IProgressMonitor createMonitor(Job job) { - return monitor.addJob(job); - } - }); - + display = parent.getDisplay(); + manager.setCancelEnabled(false); + providerOwner = this; + Job.getJobManager().setProgressProvider(new ProgressProvider() { + @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); - } - }); - } - - /** - * 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; - } - } -} \ No newline at end of file + 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); + }); + } +} diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/LatestJob.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/LatestJob.java index 64043727..fe815ce4 100644 --- a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/LatestJob.java +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/LatestJob.java @@ -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 implements AutoCloseable { private final AtomicLong generation = new AtomicLong(); private final Consumer dispatch; private final Consumer publish; - private Job job; + private final Set jobs = ConcurrentHashMap.newKeySet(); + private final boolean latestOnly; private volatile boolean closed; public LatestJob(Consumer dispatch, Consumer publish) { + this(dispatch, publish, true); + } + + /** latestOnly=false preserves additive commands until cancel/close. */ + public LatestJob(Consumer dispatch, Consumer publish, boolean latestOnly) { + this.latestOnly = latestOnly; this.dispatch = dispatch; this.publish = publish; } @@ -35,31 +50,38 @@ public final class LatestJob implements AutoCloseable { /** Called by the owning UI thread, as are cancel() and close(). */ public void schedule(String name, Function 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); - if (monitor.isCanceled() || closed || generation.get() != request) return Status.CANCEL_STATUS; - dispatch.accept(() -> { - if (!closed && generation.get() == request) publish.accept(result); - }); - return Status.OK_STATUS; + 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 (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(); } diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/TransactionQuery.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/TransactionQuery.java index cdce3ad7..b5921661 100644 --- a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/TransactionQuery.java +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/TransactionQuery.java @@ -30,40 +30,47 @@ public final class TransactionQuery { public record Attribute(String name, DataType type) {} private final IWaveform waveform; private volatile List transactions; - private List attributes; + private volatile List attributes; public TransactionQuery(IWaveform waveform) { this.waveform = waveform; } public List transactions(BooleanSupplier cancelled) { - check(cancelled); - List 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; + return cancellable(cancelled, + () -> com.minres.scviewer.database.WaveformAccess.read(waveform, () -> { + check(cancelled); + List result = transactions; + if (result == null) { + result = waveform instanceof ITransactionProvider indexed ? indexed.getTransactionList() + : TransactionLists.fromEvents(waveform.getEvents(), cancelled); + check(cancelled); + synchronized (this) { + if (transactions == null) transactions = result; + result = transactions; } } - } - check(cancelled); - return result; + check(cancelled); + return result; + })); } public List filter(Predicate predicate, BooleanSupplier cancelled) { + return cancellable(cancelled, + () -> com.minres.scviewer.database.WaveformAccess.read(waveform, () -> { List result = new ArrayList<>(); for (ITx transaction : transactions(cancelled)) { check(cancelled); if (predicate.test(transaction)) result.add(transaction); } return List.copyOf(result); + })); } - public synchronized List discoverAttributes(BooleanSupplier cancelled) { + public List discoverAttributes(BooleanSupplier cancelled) { + return cancellable(cancelled, + () -> com.minres.scviewer.database.WaveformAccess.read(waveform, () -> discover(cancelled))); + } + + private List discover(BooleanSupplier cancelled) { check(cancelled); if (attributes != null) return attributes; Map 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 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 cancellable(BooleanSupplier cancelled, java.util.function.Supplier 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) { diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/ViewerSettings.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/ViewerSettings.java index 36f70893..8ff2b57f 100644 --- a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/ViewerSettings.java +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/internal/util/ViewerSettings.java @@ -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 tracks, List 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; } diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/TransactionDetails.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/TransactionDetails.java index f214818b..0c1f4a0b 100644 --- a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/TransactionDetails.java +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/TransactionDetails.java @@ -88,6 +88,7 @@ public class TransactionDetails { /** The tree viewer. */ private TreeViewer treeViewer; + private com.minres.scviewer.e4.application.internal.util.LatestJob inputJob; /** The col3. */ private TreeViewerColumn col1; @@ -289,7 +290,40 @@ public class TransactionDetails { } HashMap settings = new HashMap<>(); - public void setInput(Object object) { + 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) { diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/TransactionList.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/TransactionList.java index 5a2a74b3..827e3f75 100644 --- a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/TransactionList.java +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/TransactionList.java @@ -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(); diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/WaveformViewer.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/WaveformViewer.java index b8b37896..a3f6b613 100644 --- a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/WaveformViewer.java +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/WaveformViewer.java @@ -175,6 +175,7 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene /** The my parent. */ private Composite myParent; + private Display uiDisplay; /** The files to load. */ ArrayList filesToLoad = new ArrayList<>(); @@ -182,6 +183,17 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene String partConfig = ""; private Path settingsFile; private LatestJob vectorJob; + private LatestJob 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 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 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 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(); @@ -606,27 +623,83 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene captureSettings().replaceState(part.getPersistedState()); } - public void saveState(String fileName) { - try { - Path file = Path.of(fileName).toAbsolutePath().normalize(); - captureSettings().write(file); - settingsFile = file; - } - catch (IOException | IllegalArgumentException e) { - reportSettingsError("Cannot save settings", fileName + ": " + e.getMessage()); - } - } + public void saveState(String fileName) { + try { + Path file = Path.of(fileName).toAbsolutePath().normalize(); + settingsWriteQueue.add(new SettingsWrite(settingsWrites.incrementAndGet(), captureSettings(), file)); + scheduleSettingsWrites(); + } catch (IllegalArgumentException e) { reportSettingsError("Cannot save settings", fileName + ": " + e.getMessage()); } + } - public void loadState(String fileName) { - try { - Path file = Path.of(fileName).toAbsolutePath().normalize(); - applySettings(ViewerSettings.read(file)); - settingsFile = file; - } - catch (IOException | IllegalArgumentException e) { - reportSettingsError("Cannot load 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(); + 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 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) { + return new PreparedSettings(null, List.of(), List.of(), null, null, database, file, e.getMessage()); + } + }); + } /** Last successfully loaded or saved settings file for this viewer. */ public Path getSettingsFile() { @@ -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 resolved, List 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 resolved = new ArrayList<>(); List missing = new ArrayList<>(); - Map derived = settings.resolveCombinedVectors(getDatabase(), missing); + Map 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 resolved = prepared.resolved(); + List 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 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; diff --git a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/txTableTree/AttributeLabelProvider.java b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/txTableTree/AttributeLabelProvider.java index fa738752..ffbf2d4e 100644 --- a/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/txTableTree/AttributeLabelProvider.java +++ b/plugins/com.minres.scviewer.e4.application/src/com/minres/scviewer/e4/application/parts/txTableTree/AttributeLabelProvider.java @@ -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 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 res = iTx.getAttributes().stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList()); + List 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 res = iTx.getAttributes().stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList()); + List 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 res = iTx.getAttributes().stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList()); + List 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 res = iTx.getAttributes().stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList()); + List res = attributes(iTx).stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList()); if(res.size()==1) return getAttrValueAsStyledString(res.get(0)); } diff --git a/plugins/com.minres.scviewer.ui/src/com/minres/scviewer/ui/TxEditorPart.java b/plugins/com.minres.scviewer.ui/src/com/minres/scviewer/ui/TxEditorPart.java index fd755545..519d9866 100644 --- a/plugins/com.minres.scviewer.ui/src/com/minres/scviewer/ui/TxEditorPart.java +++ b/plugins/com.minres.scviewer.ui/src/com/minres/scviewer/ui/TxEditorPart.java @@ -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$ @@ -89,21 +93,23 @@ public class TxEditorPart extends EditorPart implements ITabbedPropertySheetPage */ @Override public void createPartControl(Composite parent) { - myParent=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(); } diff --git a/plugins/com.minres.scviewer.ui/src/com/minres/scviewer/ui/views/TxOutlinePage.java b/plugins/com.minres.scviewer.ui/src/com/minres/scviewer/ui/views/TxOutlinePage.java index 2ebc292e..70886d19 100644 --- a/plugins/com.minres.scviewer.ui/src/com/minres/scviewer/ui/views/TxOutlinePage.java +++ b/plugins/com.minres.scviewer.ui/src/com/minres/scviewer/ui/views/TxOutlinePage.java @@ -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,8 +101,11 @@ public class TxOutlinePage extends ContentOutlinePage implements ISelectionList * @see org.eclipse.ui.part.IPage#dispose() */ public void dispose() { - // dispose - super.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(); + }); } } diff --git a/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/CombinedBitVectorTest.java b/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/CombinedBitVectorTest.java index 02b895c3..361b4b99 100644 --- a/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/CombinedBitVectorTest.java +++ b/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/CombinedBitVectorTest.java @@ -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"); diff --git a/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/SQLiteBatchTest.java b/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/SQLiteBatchTest.java index 6810c88e..907aa852 100644 --- a/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/SQLiteBatchTest.java +++ b/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/SQLiteBatchTest.java @@ -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(); diff --git a/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/ThreadingTest.java b/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/ThreadingTest.java new file mode 100644 index 00000000..49a42b6b --- /dev/null +++ b/tests/com.minres.scviewer.database.test/src/com/minres/scviewer/database/test/ThreadingTest.java @@ -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>> results = new ArrayList<>(); + for (int thread = 0; thread < 8; thread++) { + int id = thread; + results.add(pool.submit(() -> { + start.await(); + List 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 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 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 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 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 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 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(); } + } +} diff --git a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/internal/status/JobProgressTest.java b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/internal/status/JobProgressTest.java new file mode 100644 index 00000000..5888b45e --- /dev/null +++ b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/internal/status/JobProgressTest.java @@ -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()); + } +} diff --git a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/internal/util/LatestJobTest.java b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/internal/util/LatestJobTest.java index 588e224e..9688c219 100644 --- a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/internal/util/LatestJobTest.java +++ b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/internal/util/LatestJobTest.java @@ -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 ui = new LinkedBlockingQueue<>(); + List displayed = new ArrayList<>(); + try (LatestJob 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 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 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()); + } + } } diff --git a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/internal/util/TransactionQueryTest.java b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/internal/util/TransactionQueryTest.java index 691cdb6b..b358a4ed 100644 --- a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/internal/util/TransactionQueryTest.java +++ b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/internal/util/TransactionQueryTest.java @@ -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(); } + } } diff --git a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/BitVectorExpansionTest.java b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/BitVectorExpansionTest.java index 4d74849f..b881bc7c 100644 --- a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/BitVectorExpansionTest.java +++ b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/BitVectorExpansionTest.java @@ -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); diff --git a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/CombinedVectorSettingsTest.java b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/CombinedVectorSettingsTest.java index 89b9f314..a1d30dd8 100644 --- a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/CombinedVectorSettingsTest.java +++ b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/CombinedVectorSettingsTest.java @@ -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)); diff --git a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/TransactionListPropertiesTest.java b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/TransactionListPropertiesTest.java index 5e140f97..bea0f7cb 100644 --- a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/TransactionListPropertiesTest.java +++ b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/TransactionListPropertiesTest.java @@ -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()); diff --git a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/WaveformScrollTest.java b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/WaveformScrollTest.java index 3e467c32..f807c47e 100644 --- a/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/WaveformScrollTest.java +++ b/tests/com.minres.scviewer.e4.application.test/src/com/minres/scviewer/e4/application/parts/WaveformScrollTest.java @@ -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);