applies concurrency fixes

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

No files matched your search

@@ -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;
@@ -471,12 +471,14 @@ public class HeapStatus extends Composite {
* Gc.
*/
private void gc() {
var display = getDisplay();
gcRunning(true);
Thread t = new Thread() {
@Override
public void run() {
busyGC();
getDisplay().asyncExec(() -> {
if (display.isDisposed()) return;
com.minres.scviewer.database.ui.UiDispatch.async(display, () -> {
if (!isDisposed())
gcRunning(false);
});
@@ -0,0 +1,43 @@
/*******************************************************************************
* Copyright (c) 2015-2021 MINRES Technologies GmbH and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* MINRES Technologies GmbH - initial API and implementation
*******************************************************************************/
package com.minres.scviewer.e4.application.internal.status;
import org.eclipse.core.runtime.NullProgressMonitor;
/** Per-job cancellation and progress state. Only immutable snapshots reach SWT. */
public final class JobProgress extends NullProgressMonitor {
public record Snapshot(String name, int total, double work, boolean done) { }
private final Runnable changed;
private String name = "";
private int total;
private double work;
private boolean done;
public JobProgress(Runnable changed) { this.changed = changed; }
@Override public void beginTask(String name, int totalWork) {
synchronized (this) { this.name = name; total = totalWork; work = 0; done = false; }
changed.run();
}
@Override public void setTaskName(String name) {
synchronized (this) { this.name = name; }
changed.run();
}
@Override public void subTask(String name) { setTaskName(name); }
@Override public void worked(int work) { internalWorked(work); }
@Override public void internalWorked(double amount) {
synchronized (this) { work += amount; }
changed.run();
}
@Override public void done() {
synchronized (this) { done = true; }
changed.run();
}
public synchronized Snapshot snapshot() { return new Snapshot(name, total, work, done); }
}
@@ -15,7 +15,6 @@ import javax.annotation.PreDestroy;
import javax.inject.Inject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
@@ -45,14 +44,15 @@ public class StatusBarControl {
/** The osgi preverences. */
@Inject @Optional PreferencesService osgiPreverences;
/** The sync. */
private final UISynchronize sync;
/** The manager. */
protected StatusLineManager manager;
/** The monitor. */
private SyncedProgressMonitor monitor;
private final java.util.Set<JobProgress> monitors = java.util.concurrent.ConcurrentHashMap.newKeySet();
private final java.util.concurrent.atomic.AtomicBoolean updatePending = new java.util.concurrent.atomic.AtomicBoolean();
private static StatusBarControl providerOwner;
private volatile boolean disposed;
private org.eclipse.swt.widgets.Display display;
/**
* Instantiates a new status bar control.
@@ -61,7 +61,6 @@ public class StatusBarControl {
*/
@Inject
public StatusBarControl(UISynchronize sync) {
this.sync=sync;
manager = new StatusLineManager();
manager.update(true);
}
@@ -86,6 +85,12 @@ public class StatusBarControl {
*/
@PreDestroy
void destroy() {
disposed = true;
if (providerOwner == this) {
Job.getJobManager().setProgressProvider(null);
providerOwner = null;
}
monitors.clear();
if (manager != null) {
manager.dispose();
manager = null;
@@ -101,14 +106,24 @@ public class StatusBarControl {
private void createStatusLine(Composite parent, MToolControl toolControl) {
// IEclipseContext context = modelService.getContainingContext(toolControl);
manager.createControl(parent);
monitor=new SyncedProgressMonitor(manager.getProgressMonitor());
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;
}
}
}
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);
});
}
}
@@ -10,24 +10,39 @@
*******************************************************************************/
package com.minres.scviewer.e4.application.internal.util;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.Function;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
/** Publishes only the latest request, including when older results are already queued. */
import com.minres.scviewer.database.ReadCancellation;
/** Owns background requests and rejects stale results, including queued UI callbacks. */
public final class LatestJob<T> implements AutoCloseable {
private final AtomicLong generation = new AtomicLong();
private final Consumer<Runnable> dispatch;
private final Consumer<T> publish;
private Job job;
private final Set<Job> jobs = ConcurrentHashMap.newKeySet();
private final boolean latestOnly;
private volatile boolean closed;
public LatestJob(Consumer<Runnable> dispatch, Consumer<T> publish) {
this(dispatch, publish, true);
}
/** latestOnly=false preserves additive commands until cancel/close. */
public LatestJob(Consumer<Runnable> dispatch, Consumer<T> publish, boolean latestOnly) {
this.latestOnly = latestOnly;
this.dispatch = dispatch;
this.publish = publish;
}
@@ -35,31 +50,38 @@ public final class LatestJob<T> implements AutoCloseable {
/** Called by the owning UI thread, as are cancel() and close(). */
public void schedule(String name, Function<IProgressMonitor, T> query) {
if (closed) return;
cancel();
if (latestOnly) cancel();
final long request = generation.get();
job = new Job(name) {
@Override
protected IStatus run(IProgressMonitor monitor) {
if (monitor.isCanceled()) return Status.CANCEL_STATUS;
T result = query.apply(monitor);
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();
}
@@ -30,40 +30,47 @@ public final class TransactionQuery {
public record Attribute(String name, DataType type) {}
private final IWaveform waveform;
private volatile List<ITx> transactions;
private List<Attribute> attributes;
private volatile List<Attribute> attributes;
public TransactionQuery(IWaveform waveform) { this.waveform = waveform; }
public List<ITx> transactions(BooleanSupplier cancelled) {
check(cancelled);
List<ITx> result = transactions;
if (result == null) {
synchronized (this) {
result = transactions;
if (result == null) {
try {
result = waveform instanceof ITransactionProvider indexed ? indexed.getTransactionList()
: TransactionLists.fromEvents(waveform.getEvents(), cancelled);
} catch (java.util.concurrent.CancellationException e) { throw new OperationCanceledException(); }
check(cancelled);
transactions = result;
return cancellable(cancelled,
() -> com.minres.scviewer.database.WaveformAccess.read(waveform, () -> {
check(cancelled);
List<ITx> 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<ITx> filter(Predicate<ITx> predicate, BooleanSupplier cancelled) {
return cancellable(cancelled,
() -> com.minres.scviewer.database.WaveformAccess.read(waveform, () -> {
List<ITx> result = new ArrayList<>();
for (ITx transaction : transactions(cancelled)) {
check(cancelled);
if (predicate.test(transaction)) result.add(transaction);
}
return List.copyOf(result);
}));
}
public synchronized List<Attribute> discoverAttributes(BooleanSupplier cancelled) {
public List<Attribute> discoverAttributes(BooleanSupplier cancelled) {
return cancellable(cancelled,
() -> com.minres.scviewer.database.WaveformAccess.read(waveform, () -> discover(cancelled)));
}
private List<Attribute> discover(BooleanSupplier cancelled) {
check(cancelled);
if (attributes != null) return attributes;
Map<String, DataType> types = new TreeMap<>();
@@ -72,8 +79,13 @@ public final class TransactionQuery {
transaction.getAttributes().forEach(attribute -> types.putIfAbsent(attribute.getName(), attribute.getDataType()));
}
check(cancelled);
attributes = types.entrySet().stream().map(e -> new Attribute(e.getKey(), e.getValue())).toList();
return attributes;
List<Attribute> result = types.entrySet().stream().map(e -> new Attribute(e.getKey(), e.getValue())).toList();
synchronized (this) { if (attributes == null) attributes = result; return attributes; }
}
private static <T> T cancellable(BooleanSupplier cancelled, java.util.function.Supplier<T> query) {
try { return com.minres.scviewer.database.ReadCancellation.with(cancelled, query); }
catch (java.util.concurrent.CancellationException e) { throw new OperationCanceledException(); }
}
private static void check(BooleanSupplier cancelled) {
@@ -23,7 +23,6 @@ import java.util.Map;
import com.minres.scviewer.database.IWaveform;
import com.minres.scviewer.database.CombinedBitVectorWaveform;
import com.minres.scviewer.database.BitVector;
import com.minres.scviewer.database.IWaveformDb;
import com.minres.scviewer.database.WaveformType;
import com.minres.scviewer.database.EventEntry;
@@ -226,9 +225,7 @@ public record ViewerSettings(List<Track> tracks, List<Long> cursors, Long scale,
missing.add(vector.name() + ": " + bit.waveform() + "[" + bit.bit() + "]");
break;
}
EventEntry first = waveform.getEvents().firstEntry();
if (first != null && (first.events == null || first.events.length == 0
|| !(first.events[first.events.length - 1] instanceof BitVector))) {
if (!waveform.isBitVector()) {
missing.add(vector.name() + ": " + bit.waveform() + " is not a bit signal");
break;
}
@@ -88,6 +88,7 @@ public class TransactionDetails {
/** The tree viewer. */
private TreeViewer treeViewer;
private com.minres.scviewer.e4.application.internal.util.LatestJob<ITx> inputJob;
/** The col3. */
private TreeViewerColumn col1;
@@ -289,7 +290,40 @@ public class TransactionDetails {
}
HashMap<Integer, ViewSettings> 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) {
@@ -93,13 +93,13 @@ public class TransactionList extends Composite {
column("Property Value", 180, valueProvider);
Display display = getDisplay();
rowsJob = new LatestJob<>(task -> { if (!display.isDisposed()) display.asyncExec(task); }, result -> {
rowsJob = new LatestJob<>(task -> com.minres.scviewer.database.ui.UiDispatch.async(display, task), result -> {
if (isDisposed()) return;
rows = result;
tableViewer.setInput(rows);
tableViewer.setItemCount(rows.size());
});
attributesJob = new LatestJob<>(task -> { if (!display.isDisposed()) display.asyncExec(task); }, result -> {
attributesJob = new LatestJob<>(task -> com.minres.scviewer.database.ui.UiDispatch.async(display, task), result -> {
if (isDisposed()) return;
if (result.error() != null) {
MessageDialog.openError(getShell(), "Cannot load properties", result.error().toString());
@@ -216,6 +216,7 @@ public class TransactionList extends Composite {
getDisplay().timerExec(-1, applyFilter);
rowsJob.cancel();
attributesJob.cancel();
valueProvider.reset();
stream = requestedStream;
query = stream == null ? null : new TransactionQuery(stream);
rows = List.of();
@@ -175,6 +175,7 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
/** The my parent. */
private Composite myParent;
private Display uiDisplay;
/** The files to load. */
ArrayList<File> filesToLoad = new ArrayList<>();
@@ -182,6 +183,17 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
String partConfig = "";
private Path settingsFile;
private LatestJob<PreparedVector> vectorJob;
private LatestJob<PreparedSettings> settingsJob;
private com.minres.scviewer.database.ui.AsyncTransactionData transactionSnapshots;
private com.minres.scviewer.database.ui.AsyncTransactionData.Snapshot transactionSnapshot(ITx tx) {
if (transactionSnapshots == null) transactionSnapshots = new com.minres.scviewer.database.ui.AsyncTransactionData(
this::dispatchSettings, changed -> { if (!disposed && eventBroker != null) eventBroker.post(ACTIVE_WAVEFORMVIEW, this); });
return transactionSnapshots.get(tx);
}
private record SettingsWrite(long request, ViewerSettings settings, Path file) { }
private final java.util.Queue<SettingsWrite> settingsWriteQueue = new java.util.concurrent.ConcurrentLinkedQueue<>();
private final java.util.concurrent.atomic.AtomicBoolean writingSettings = new java.util.concurrent.atomic.AtomicBoolean();
private final java.util.concurrent.atomic.AtomicLong settingsWrites = new java.util.concurrent.atomic.AtomicLong();
private record PreparedVector(CombinedBitVectorWaveform vector, List<TrackEntry> tracks,
IWaveformDb database, String error) { }
@@ -225,9 +237,10 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
myPart = part;
myParent = parent;
uiDisplay = parent.getDisplay();
store=prefs;
showHover=hover;
sessions = new DatabaseSessionManager(dbFactory, task -> sync.asyncExec(task),
sessions = new DatabaseSessionManager(dbFactory, this::dispatchSettings,
db -> { if (!isViewerDisposed()) waveformPane.setMaxTime(db.getMaxTime()); },
db -> { if (!isViewerDisposed() && confirmReload()) reloadDatabase(); }, 60000);
parent.setLayout(new FillLayout(SWT.HORIZONTAL));
@@ -417,7 +430,7 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
final TableColumn valueCol = new TableColumn(table, SWT.LEFT);
valueCol.setText("Value");
for (ITxAttribute iTxAttribute : tx.getAttributes()) {
for (ITxAttribute iTxAttribute : transactionSnapshot(tx).attributes()) {
String value = iTxAttribute.getValue().toString();
if((DataType.UNSIGNED == iTxAttribute.getDataType() || DataType.INTEGER==iTxAttribute.getDataType()) && !"0".equals(value)) {
try {
@@ -468,6 +481,8 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
if (disposed) return;
disposed = true;
if (vectorJob != null) vectorJob.close();
if (settingsJob != null) settingsJob.close();
if (transactionSnapshots != null) transactionSnapshots.close();
if (sessions != null) sessions.close();
if (observedPreferences != null) {
observedPreferences.removePreferenceChangeListener(this);
@@ -537,6 +552,8 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
protected void loadDatabase(final Map<String, String> state, long delay) {
if (disposed) return;
if (vectorJob != null) vectorJob.cancel();
if (settingsJob != null) settingsJob.cancel();
if (transactionSnapshots != null) { transactionSnapshots.close(); transactionSnapshots = null; }
setSelection(null);
waveformPane.getStreamList().clear();
waveformPane.update();
@@ -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<IWaveform> sources = database == null ? List.of() : database.getAllWaves();
if (sync == null) {
// Headless callers have no SWT owner; retain synchronous validation.
try { applyPreparedSettings(prepareSettings(reader.read(), database, file)); }
catch (IOException | IllegalArgumentException e) { reportSettingsError("Cannot load settings", e.getMessage()); }
return;
}
if (settingsJob == null) settingsJob = new LatestJob<>(this::dispatchSettings, prepared -> {
if (disposed || getDatabase() != prepared.database()) return;
if (prepared.error() != null) { reportSettingsError("Cannot load settings", prepared.error()); return; }
applyPreparedSettings(prepared);
});
settingsJob.schedule("Prepare waveform settings", monitor -> {
try {
ViewerSettings settings = reader.read();
return com.minres.scviewer.database.WaveformAccess.read(sources,
() -> prepareSettings(settings, database, file));
} catch (java.util.concurrent.CancellationException e) { throw e; }
catch (IOException | IllegalArgumentException e) {
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<ResolvedTrack> resolved, List<String> missing,
ITx selectedTransaction, IWaveform selectedWaveform, IWaveformDb database, Path file, String error) { }
private void applySettings(ViewerSettings settings) { requestSettings(() -> settings, null); }
private PreparedSettings prepareSettings(ViewerSettings settings, IWaveformDb database, Path file) {
// Resolve all references before replacing the current layout.
List<ResolvedTrack> resolved = new ArrayList<>();
List<String> missing = new ArrayList<>();
Map<String, IWaveform> derived = settings.resolveCombinedVectors(getDatabase(), missing);
Map<String, IWaveform> derived = settings.resolveCombinedVectors(database, missing);
ITx selectedTransaction = null;
IWaveform selectedWaveform = null;
for (ViewerSettings.Track track : settings.tracks()) {
com.minres.scviewer.database.ReadCancellation.check();
IWaveform waveform = track.type() == WaveformType.EMPTY ? new EmptyWaveform(track.name())
: ViewerSettings.resolveWaveform(getDatabase(), track.name(), derived);
: ViewerSettings.resolveWaveform(database, track.name(), derived);
if (waveform == null) {
missing.add(settings.displayName(track.name()));
continue;
@@ -721,6 +799,18 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
selectedWaveform = waveform;
}
}
return new PreparedSettings(settings, List.copyOf(resolved), List.copyOf(missing), selectedTransaction,
selectedWaveform, database, file, null);
}
private void applyPreparedSettings(PreparedSettings prepared) {
if (vectorJob != null) vectorJob.cancel();
ViewerSettings settings = prepared.settings();
List<ResolvedTrack> resolved = prepared.resolved();
List<String> missing = prepared.missing();
ITx selectedTransaction = prepared.selectedTransaction();
IWaveform selectedWaveform = prepared.selectedWaveform();
if (prepared.file() != null) settingsFile = prepared.file();
waveformPane.setSelection(StructuredSelection.EMPTY);
waveformPane.getStreamList().clear();
List<TrackEntry> selectedTracks = new ArrayList<>();
@@ -978,21 +1068,24 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
long visibleStart = waveformPane.getWaveformZoom().getMinVisibleTime();
long visibleEnd = waveformPane.getWaveformZoom().getMaxVisibleTime();
long cursor = waveformPane.getCursorTime();
if (vectorJob == null) vectorJob = new LatestJob<>(task -> sync.asyncExec(task), result -> {
if (vectorJob == null) vectorJob = new LatestJob<>(this::dispatchSettings, result -> {
if (disposed || getDatabase() != result.database()) return;
if (result.error() != null) { reportSettingsError("Cannot combine bits", result.error()); return; }
insertCombinedVector(result.vector(), result.tracks());
});
}, false);
vectorJob.schedule("Combine bits", monitor -> {
try {
var vector = new CombinedBitVectorWaveform(name.trim(), BitVectorComposition.sources(snapshot));
vector.getEvents().firstEntry(); // Load any lazy inputs on this worker, before painting on the UI thread.
return com.minres.scviewer.database.WaveformAccess.read(vector, () -> {
vector.getEvents().firstEntry(); // Load lazy inputs while holding a recording lease.
vector.getEvents().floorEntry(visibleStart);
vector.getEvents().floorEntry(cursor);
for (var ignored : vector.getEvents().subMap(visibleStart, true, visibleEnd)) {
if (monitor.isCanceled()) return null;
}
return new PreparedVector(vector, snapshot, database, null);
});
} catch (java.util.concurrent.CancellationException exception) { throw exception;
} catch (RuntimeException exception) {
return new PreparedVector(null, snapshot, database, exception.toString());
}
@@ -1125,9 +1218,9 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
res.add(IWaveformView.NEXT_PREV_IN_STREAM);
ITx transaction = WaveformSelection.from(waveformPane.getSelection()).transaction();
if (transaction != null) {
for (ITxRelation relation : transaction.getIncomingRelations())
for (ITxRelation relation : transactionSnapshot(transaction).incoming())
if (!res.contains(relation.getRelationType())) res.add(relation.getRelationType());
for (ITxRelation relation : transaction.getOutgoingRelations())
for (ITxRelation relation : transactionSnapshot(transaction).outgoing())
if (!res.contains(relation.getRelationType())) res.add(relation.getRelationType());
}
return res;
@@ -28,6 +28,19 @@ import com.minres.scviewer.e4.application.parts.WaveformViewer;
* The Class AttributeLabelProvider.
*/
public class AttributeLabelProvider extends LabelProvider implements IStyledLabelProvider {
private com.minres.scviewer.database.ui.AsyncTransactionData data;
private List<ITxAttribute> attributes(ITx tx) {
var display = org.eclipse.swt.widgets.Display.getCurrent();
// Headless consumers are already on a worker and can read synchronously.
if (display == null) return tx.getAttributes();
if (data == null) data = new com.minres.scviewer.database.ui.AsyncTransactionData(
task -> com.minres.scviewer.database.ui.UiDispatch.async(display, task),
changed -> fireLabelProviderChanged(new org.eclipse.jface.viewers.LabelProviderChangedEvent(this, changed)), false);
return data.get(tx).attributes();
}
public void reset() { if (data != null) data.close(); data = null; }
@Override public void dispose() { reset(); super.dispose(); }
/**
*
@@ -84,14 +97,14 @@ public class AttributeLabelProvider extends LabelProvider implements IStyledLabe
return new StyledString(waveformViewerPart.getScaledTime(iTx.getBeginTime()));
case TYPE:
if(showProp!=null){
List<ITxAttribute> res = iTx.getAttributes().stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
List<ITxAttribute> res = attributes(iTx).stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
if(res.size()==1)
return new StyledString(res.get(0).getDataType().toString());
}
return new StyledString("");
case VALUE:
if(showProp!=null){
List<ITxAttribute> res = iTx.getAttributes().stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
List<ITxAttribute> res = attributes(iTx).stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
if(res.size()==1)
return getAttrValueAsStyledString(res.get(0));
}
@@ -115,7 +128,7 @@ public class AttributeLabelProvider extends LabelProvider implements IStyledLabe
if(element instanceof TransactionTreeNode) {
if(showProp!=null){
ITx iTx = ((TransactionTreeNode) element).element;
List<ITxAttribute> res = iTx.getAttributes().stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
List<ITxAttribute> res = attributes(iTx).stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
if(res.size()==1)
return new StyledString(res.get(0).getDataType().toString());
}
@@ -137,7 +150,7 @@ public class AttributeLabelProvider extends LabelProvider implements IStyledLabe
if(element instanceof TransactionTreeNode) {
if(showProp!=null){
ITx iTx = ((TransactionTreeNode) element).element;
List<ITxAttribute> res = iTx.getAttributes().stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
List<ITxAttribute> res = attributes(iTx).stream().filter(a -> showProp.equals(a.getName())).collect(Collectors.toList());
if(res.size()==1)
return getAttrValueAsStyledString(res.get(0));
}