fixes waveform hover behvior

This commit is contained in:
eyck committed 2026-11-21 14:47:51 +01:00
1 parent 693fe402ed
commit 941676c21b
4 files changed
+562 -96

No files matched your search

@@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2020-2021 MINRES Technologies GmbH and others.
* Copyright (c) 2020-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
@@ -10,139 +10,218 @@
*******************************************************************************/
package com.minres.scviewer.database.ui.swt.internal;
import java.util.function.Supplier;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.HelpListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Widget;
import com.minres.scviewer.database.ui.UiDispatch;
import com.minres.scviewer.database.ui.swt.Constants;
import com.minres.scviewer.database.ui.swt.IToolTipContentProvider;
import com.minres.scviewer.database.ui.swt.IToolTipHelpTextProvider;
class ToolTipHandler {
/** Owns the hover popup and its UI-thread listeners and dismissal timer. */
class ToolTipHandler implements AutoCloseable {
private static final int HOVER_YOFFSET = 1;
private static final int EXIT_CHECK_INTERVAL = 100;
private static final int[] SOURCE_EVENTS = {
SWT.Dispose, SWT.KeyDown, SWT.MouseHover, SWT.MouseDown, SWT.MouseMove, SWT.MouseExit
};
private final Display display;
private Shell parentShell;
private final Shell parentShell;
private final Supplier<Point> cursorLocation;
private final Runnable exitCheck = this::checkPointer;
private final Listener listener = this::handleEvent;
private final HelpListener helpListener = event -> showHelp();
private final Listener parentDeactivated;
private final Listener parentDisposed = event -> close();
private Shell shell;
private Control control;
private Point tipPosition;
private boolean closed;
private Widget tipWidget; // widget this tooltip is hovering over
private Point tipPosition; // the position being hovered over
private static final int HOVER_YOFFSET = 1;
/**
* Creates a new tooltip handler
*
* @param parent the parent Shell
*/
public ToolTipHandler(Shell parent) {
display = parent.getDisplay();
parentShell = parent;
this(parent, parent.getDisplay()::getCursorLocation);
}
/**
* Enables customized hover help for a specified control
*
* @control the control on which to enable hoverhelp
*/
public void activateHoverHelp(final Control control) {
Listener listener = new Listener () {
Shell shell = null;
@Override
public void handleEvent (Event event) {
ToolTipHandler(Shell parent, Supplier<Point> cursorLocation) {
display = parent.getDisplay();
parentShell = parent;
this.cursorLocation = cursorLocation;
parentDeactivated = event -> UiDispatch.async(display, () -> {
if (!closed && shell != null && display.getActiveShell() != shell) hide();
});
parent.addListener(SWT.Deactivate, parentDeactivated);
parent.addListener(SWT.Dispose, parentDisposed);
}
public void activateHoverHelp(Control control) {
if (closed) return;
if (this.control != null) throw new IllegalStateException("Hover help already has an owner");
this.control = control;
for (int type : SOURCE_EVENTS) control.addListener(type, listener);
control.addHelpListener(helpListener);
}
private void handleEvent(Event event) {
if (closed) return;
switch (event.type) {
case SWT.KeyDown:
if (shell != null && shell.isVisible() && event.keyCode == SWT.F2)
if (shell != null && !shell.isDisposed() && event.keyCode == SWT.F2)
shell.setFocus();
break;
case SWT.Dispose:
case SWT.MouseMove:
close();
break;
case SWT.MouseDown:
if (shell != null){
shell.dispose ();
shell = null;
tipWidget=null;
}
case SWT.MouseMove:
hide();
break;
case SWT.MouseExit:
// A canvas exit can mean entering the popup; defer until GTK has
// updated the pointer location and compare display coordinates.
UiDispatch.async(display, this::checkPointer);
break;
case SWT.MouseHover:
createHoverWindow(control, event);
showHover(event);
break;
default:
/* do nothing */
break;
}
}
private void createHoverWindow(final Control control, Event event) {
Object o = control.getData(Constants.CONTENT_PROVIDER_TAG);
if(o instanceof IToolTipContentProvider) {
IToolTipContentProvider provider = ((IToolTipContentProvider)o);
Point pt = new Point (event.x, event.y);
tipPosition = control.toDisplay(pt);
if (shell != null && !shell.isDisposed ()) shell.dispose ();
shell = new Shell (parentShell, SWT.NO_FOCUS | SWT.TOOL);
shell.setBackground (display.getSystemColor (SWT.COLOR_INFO_BACKGROUND));
GridLayout layout = new GridLayout(1, true);
layout.verticalSpacing=0;
layout.horizontalSpacing=0;
layout.marginWidth = 0;
layout.marginHeight = 0;
shell.setLayout(layout);
boolean visible = provider.createContent(shell, pt);
shell.pack();
shell.setSize(shell.computeSize(SWT.DEFAULT, SWT.DEFAULT));
setHoverLocation(shell, tipPosition);
shell.setVisible (visible);
if(visible)
tipWidget=event.widget;
}
}
};
control.addListener (SWT.Dispose, listener);
control.addListener (SWT.KeyDown, listener);
control.addListener (SWT.MouseHover, listener);
control.addListener (SWT.MouseDown, listener);
/*
* Trap F1 Help to pop up a custom help box
*/
control.addHelpListener(event -> {
if (tipWidget == null) return;
IToolTipHelpTextProvider handler = (IToolTipHelpTextProvider)tipWidget.getData(Constants.HELP_PROVIDER_TAG);
if (handler == null) return;
String text = handler.getHelpText(tipWidget);
if (text == null) return;
if (shell.isVisible()) {
shell.setVisible(false);
Shell helpShell = new Shell(parentShell, SWT.SHELL_TRIM);
helpShell.setLayout(new FillLayout());
Label label = new Label(helpShell, SWT.NONE);
label.setText(text);
helpShell.pack();
setHoverLocation(helpShell, tipPosition);
helpShell.open();
private void showHover(Event event) {
if (control == null || control.isDisposed() || parentShell.isDisposed()) return;
Object value = control.getData(Constants.CONTENT_PROVIDER_TAG);
if (!(value instanceof IToolTipContentProvider provider)) return;
hide();
Point point = new Point(event.x, event.y);
tipPosition = control.toDisplay(point);
Shell popup = new Shell(parentShell, SWT.NO_FOCUS | SWT.TOOL);
shell = popup;
popup.addDisposeListener(disposedEvent -> {
if (shell == popup) {
shell = null;
tipPosition = null;
if (!display.isDisposed()) display.timerExec(-1, exitCheck);
}
});
popup.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
GridLayout layout = new GridLayout(1, true);
layout.verticalSpacing = layout.horizontalSpacing = layout.marginWidth = layout.marginHeight = 0;
popup.setLayout(new FillLayout());
ScrolledComposite scroll = new ScrolledComposite(popup, SWT.H_SCROLL | SWT.V_SCROLL);
Composite content = new Composite(scroll, SWT.NONE);
content.setLayout(layout);
scroll.setContent(content);
content.addListener(SWT.Resize, resized -> resizeHover(popup, scroll, content));
try {
if (!provider.createContent(content, point)) { hide(); return; }
content.pack();
resizeHover(popup, scroll, content);
watchPopupExit(popup, popup);
popup.setVisible(true);
display.timerExec(EXIT_CHECK_INTERVAL, exitCheck);
} catch (RuntimeException | Error e) { hide(); throw e; }
}
/**
* Sets the location for a hovering shell
* @param shell the object that is to hover
* @param position the position of a widget to hover over
* @return the top-left location for a hovering box
*/
private void setHoverLocation(Shell shell, Point position) {
Rectangle displayBounds = shell.getDisplay().getBounds();
Rectangle shellBounds = shell.getBounds();
shellBounds.x = Math.max(Math.min(position.x, displayBounds.width - shellBounds.width), 0);
shellBounds.y = Math.max(Math.min(position.y + HOVER_YOFFSET, displayBounds.height - shellBounds.height), 0);
shell.setBounds(shellBounds);
private void resizeHover(Shell popup, ScrolledComposite scroll, Composite content) {
Rectangle area = parentShell.getMonitor().getClientArea();
Point size = content.getSize();
Rectangle viewport = scroll.computeTrim(0, 0, size.x, size.y);
Rectangle bounds = popup.computeTrim(0, 0, viewport.width, viewport.height);
popup.setSize(Math.min(bounds.width, area.width), Math.min(bounds.height, area.height));
popup.layout(true, true);
setHoverLocation(popup, tipPosition);
}
private void watchPopupExit(Control child, Shell popup) {
child.addListener(SWT.MouseExit, event -> UiDispatch.async(display, () -> {
// Child-to-child transitions are not exits from the hover window.
if (!closed && shell == popup && !popup.isDisposed()
&& !popup.getBounds().contains(cursorLocation.get())) hide();
}));
if (child instanceof Composite composite)
for (Control nested : composite.getChildren()) watchPopupExit(nested, popup);
}
private void checkPointer() {
if (closed || shell == null || shell.isDisposed()) return;
if (control == null || control.isDisposed() || !control.isVisible() || !shell.isVisible()) {
hide();
return;
}
Point pointer = cursorLocation.get();
Point size = control.getSize();
Rectangle owner = control instanceof Composite composite ? composite.getClientArea()
: new Rectangle(0, 0, size.x, size.y);
Point ownerPosition = control.toDisplay(owner.x, owner.y);
owner.x = ownerPosition.x;
owner.y = ownerPosition.y;
if (!owner.contains(pointer) && !shell.getBounds().contains(pointer)) { hide(); return; }
// MouseExit is not guaranteed by SWT when crossing native windows quickly.
// Poll only while a popup exists; no mouse capture or global filter is needed.
display.timerExec(EXIT_CHECK_INTERVAL, exitCheck);
}
private void hide() {
if (!display.isDisposed()) display.timerExec(-1, exitCheck);
Shell old = shell;
shell = null;
tipPosition = null;
if (old != null && !old.isDisposed()) old.dispose();
}
private void showHelp() {
if (closed || control == null || control.isDisposed() || shell == null || shell.isDisposed()) return;
Object provider = control.getData(Constants.HELP_PROVIDER_TAG);
if (!(provider instanceof IToolTipHelpTextProvider help)) return;
String text = help.getHelpText(control);
if (text == null) return;
Point position = tipPosition;
hide();
Shell helpShell = new Shell(parentShell, SWT.SHELL_TRIM);
helpShell.setLayout(new FillLayout());
new Label(helpShell, SWT.NONE).setText(text);
helpShell.pack();
setHoverLocation(helpShell, position);
helpShell.open();
}
@Override public void close() {
if (closed) return;
closed = true;
hide();
if (!parentShell.isDisposed()) {
parentShell.removeListener(SWT.Deactivate, parentDeactivated);
parentShell.removeListener(SWT.Dispose, parentDisposed);
}
if (control != null && !control.isDisposed()) {
for (int type : SOURCE_EVENTS) control.removeListener(type, listener);
control.removeHelpListener(helpListener);
}
control = null;
}
private void setHoverLocation(Shell popup, Point position) {
Rectangle displayBounds = parentShell.getMonitor().getClientArea();
Rectangle bounds = popup.getBounds();
bounds.x = Math.max(displayBounds.x, Math.min(position.x, displayBounds.x + displayBounds.width - bounds.width));
bounds.y = Math.max(displayBounds.y, Math.min(position.y + HOVER_YOFFSET,
displayBounds.y + displayBounds.height - bounds.height));
popup.setBounds(bounds);
}
}
@@ -185,11 +185,25 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
private LatestJob<PreparedVector> vectorJob;
private LatestJob<PreparedSettings> settingsJob;
private com.minres.scviewer.database.ui.AsyncTransactionData transactionSnapshots;
private java.util.function.Consumer<ITx> hoverUpdate;
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); });
this::dispatchSettings, changed -> {
if (disposed) return;
if (hoverUpdate != null) hoverUpdate.accept(changed);
if (eventBroker != null) eventBroker.post(ACTIVE_WAVEFORMVIEW, this);
});
return transactionSnapshots.get(tx);
}
private void refreshHoverWhenReady(Composite parent, ITx transaction, Runnable refresh) {
java.util.function.Consumer<ITx> update = changed -> {
if (changed == transaction && !parent.isDisposed()) refresh.run();
};
hoverUpdate = update;
parent.addDisposeListener(event -> { if (hoverUpdate == update) hoverUpdate = null; });
refresh.run();
}
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();
@@ -432,6 +446,8 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
final TableColumn valueCol = new TableColumn(table, SWT.LEFT);
valueCol.setText("Value");
refreshHoverWhenReady(parent, tx, () -> {
table.removeAll();
for (ITxAttribute iTxAttribute : transactionSnapshot(tx).attributes()) {
String value = iTxAttribute.getValue().toString();
if((DataType.UNSIGNED == iTxAttribute.getDataType() || DataType.INTEGER==iTxAttribute.getDataType()) && !"0".equals(value)) {
@@ -452,6 +468,9 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
nameCol.pack();
valueCol.pack();
table.setSize(table.computeSize(SWT.DEFAULT, SWT.DEFAULT));
parent.layout(true, true);
parent.pack();
});
parent.addPaintListener( e -> {
Rectangle area = parent.getClientArea();
valueCol.setWidth(area.width - nameCol.getWidth());
@@ -482,6 +501,7 @@ public class WaveformViewer implements IPreferenceChangeListener, DisposeListene
public void closeDatabase() {
if (disposed) return;
disposed = true;
hoverUpdate = null;
if (vectorJob != null) vectorJob.close();
if (settingsJob != null) settingsJob.close();
if (transactionSnapshots != null) transactionSnapshots.close();
@@ -0,0 +1,208 @@
/*******************************************************************************
* Copyright (c) 2026 MINRES Technologies GmbH and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* MINRES Technologies GmbH - initial API and implementation
*******************************************************************************/
package com.minres.scviewer.e4.application.parts;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;
import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.minres.scviewer.database.ui.swt.Constants;
import com.minres.scviewer.database.ui.swt.IToolTipContentProvider;
import com.minres.scviewer.database.ui.swt.IToolTipHelpTextProvider;
import com.minres.scviewer.database.ui.swt.WaveformViewFactory;
public class HoverWindowTest {
private Display display;
private Shell owner;
private Canvas canvas;
private Object handler;
private Field popupField;
private final AtomicReference<Point> pointer = new AtomicReference<>();
private Label first, second;
@Before public void createControls() throws Exception {
assumeTrue("GTK integration tests require DISPLAY", !"gtk".equals(SWT.getPlatform())
|| System.getenv("DISPLAY") != null);
display = new Display();
owner = new Shell(display);
owner.setBounds(100, 100, 600, 400);
owner.setLayout(new FillLayout());
canvas = new Canvas(owner, SWT.NONE);
owner.open();
drain();
pointer.set(canvas.toDisplay(10, 10));
Class<?> type = WaveformViewFactory.class.getClassLoader().loadClass(
"com.minres.scviewer.database.ui.swt.internal.ToolTipHandler");
var constructor = type.getDeclaredConstructor(Shell.class, Supplier.class);
constructor.setAccessible(true);
handler = constructor.newInstance(owner, (Supplier<Point>) pointer::get);
var activate = type.getDeclaredMethod("activateHoverHelp", org.eclipse.swt.widgets.Control.class);
activate.setAccessible(true);
activate.invoke(handler, canvas);
popupField = type.getDeclaredField("shell");
popupField.setAccessible(true);
canvas.setData(Constants.CONTENT_PROVIDER_TAG, (IToolTipContentProvider) (parent, point) -> {
Composite content = new Composite(parent, SWT.NONE);
content.setLayout(new FillLayout());
first = new Label(content, SWT.NONE); first.setText("First label");
second = new Label(content, SWT.NONE); second.setText("Second label");
content.pack();
return true;
});
}
@After public void disposeControls() throws Exception {
if (display == null) return;
try {
if (handler != null) {
var close = handler.getClass().getDeclaredMethod("close");
close.setAccessible(true); close.invoke(handler);
}
if (owner != null && !owner.isDisposed()) owner.dispose();
drain();
} finally { display.dispose(); }
}
private void drain() {
int count = 0;
while (display.readAndDispatch()) assertTrue("UI event loop did not settle", ++count < 2000);
}
private Shell popup() throws Exception { return (Shell) popupField.get(handler); }
private Shell hover() throws Exception {
pointer.set(canvas.toDisplay(10, 10));
Event event = new Event(); event.x = 10; event.y = 10;
canvas.notifyListeners(SWT.MouseHover, event);
Shell popup = popup();
assertNotNull(popup);
assertTrue(popup.isVisible());
return popup;
}
private void assertBoundedAndScrollable(Shell popup) {
Rectangle area = owner.getMonitor().getClientArea(), bounds = popup.getBounds();
assertTrue(bounds.x >= area.x && bounds.y >= area.y);
assertTrue(bounds.x + bounds.width <= area.x + area.width);
assertTrue(bounds.y + bounds.height <= area.y + area.height);
ScrolledComposite scroll = (ScrolledComposite) popup.getChildren()[0];
assertTrue(scroll.getHorizontalBar().getVisible());
assertTrue(scroll.getVerticalBar().getVisible());
scroll.setOrigin(area.width, area.height);
assertTrue("Wide content must be reachable", scroll.getOrigin().x > 0);
assertTrue("Tall content must be reachable", scroll.getOrigin().y > 0);
}
@Test public void oversizedContentStaysOnScreenAndScrollsInBothDirections() throws Exception {
Rectangle area = owner.getMonitor().getClientArea();
canvas.setData(Constants.CONTENT_PROVIDER_TAG, (IToolTipContentProvider) (parent, point) -> {
Label label = new Label(parent, SWT.NONE);
label.setText("Oversized hover content");
label.setLayoutData(new GridData(area.width * 2, area.height * 2));
return true;
});
assertBoundedAndScrollable(hover());
}
@Test public void contentLoadedAfterOpeningAlsoStaysBoundedAndScrollable() throws Exception {
Shell popup = hover();
ScrolledComposite scroll = (ScrolledComposite) popup.getChildren()[0];
Composite content = (Composite) scroll.getContent();
assertFalse(scroll.getHorizontalBar().getVisible());
assertFalse(scroll.getVerticalBar().getVisible());
Rectangle area = owner.getMonitor().getClientArea();
first.getParent().setLayoutData(new GridData(area.width * 2, area.height * 2));
// The transaction hover packs its content after asynchronous attributes arrive.
content.pack();
assertBoundedAndScrollable(popup);
}
@Test public void sourceMovementAndExitingTheCanvasDismissHover() throws Exception {
Shell moving = hover();
canvas.notifyListeners(SWT.MouseMove, new Event());
assertTrue(moving.isDisposed());
Shell exiting = hover();
pointer.set(new Point(-10000, -10000));
canvas.notifyListeners(SWT.MouseExit, new Event());
drain();
assertTrue(exiting.isDisposed());
assertNull(popup());
}
@Test public void enteringPopupAndCrossingChildrenKeepsItOpenButLeavingClosesIt() throws Exception {
Shell popup = hover();
pointer.set(second.toDisplay(1, 1));
assertTrue(popup.getBounds().contains(pointer.get()));
canvas.notifyListeners(SWT.MouseExit, new Event());
first.notifyListeners(SWT.MouseExit, new Event());
drain();
assertFalse(popup.isDisposed());
// Leaving a child for the original canvas is also leaving the hover window.
pointer.set(canvas.toDisplay(canvas.getSize().x - 5, canvas.getSize().y - 5));
assertFalse(popup.getBounds().contains(pointer.get()));
second.notifyListeners(SWT.MouseExit, new Event());
drain();
assertTrue(popup.isDisposed());
}
@Test public void pointerCheckDismissesHoverWhenNativeExitEventIsMissing() throws Exception {
Shell popup = hover();
pointer.set(new Point(-10000, -10000));
long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(5);
while (!popup.isDisposed()) {
drain();
assertTrue("Hover did not disappear outside the window", System.nanoTime() < deadline);
Thread.sleep(5);
}
assertNull(popup());
}
@Test public void ownerDisposalCancelsChecksAndQueuedExitCallbacks() throws Exception {
Shell popup = hover();
canvas.notifyListeners(SWT.MouseExit, new Event());
canvas.dispose();
drain();
assertTrue(popup.isDisposed());
assertNull(popup());
assertFalse(owner.isListening(SWT.Deactivate));
}
@Test public void emptyContentDisposesPopupAndHelpUsesTheActiveHoverShell() throws Exception {
canvas.setData(Constants.HELP_PROVIDER_TAG, (IToolTipHelpTextProvider) widget -> "Hover help");
Shell popup = hover();
canvas.notifyListeners(SWT.Help, new Event());
assertTrue(popup.isDisposed());
assertNull(popup());
assertTrue(java.util.Arrays.stream(display.getShells()).anyMatch(shell -> shell != owner && !shell.isDisposed()));
canvas.setData(Constants.CONTENT_PROVIDER_TAG, (IToolTipContentProvider) (parent, point) -> false);
Event event = new Event(); event.x = 10; event.y = 10;
canvas.notifyListeners(SWT.MouseHover, event);
assertNull(popup());
}
}
@@ -0,0 +1,159 @@
/*******************************************************************************
* Copyright (c) 2026 MINRES Technologies GmbH and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* MINRES Technologies GmbH - initial API and implementation
*******************************************************************************/
package com.minres.scviewer.e4.application.parts;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
import org.eclipse.e4.ui.di.UISynchronize;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.minres.scviewer.database.DataType;
import com.minres.scviewer.database.tx.ITx;
import com.minres.scviewer.database.tx.ITxAttribute;
import com.minres.scviewer.database.ui.AsyncTransactionData;
import com.minres.scviewer.database.ui.UiDispatch;
public class TransactionHoverTest {
private Display display;
private WaveformViewer viewer;
private Method snapshot, refresh;
private final CountDownLatch loading = new CountDownLatch(1), release = new CountDownLatch(1);
private final AtomicInteger reads = new AtomicInteger();
private ITx transaction;
@Before public void setup() throws Exception {
assumeTrue("GTK integration tests require DISPLAY", !"gtk".equals(SWT.getPlatform())
|| System.getenv("DISPLAY") != null);
display = new Display();
viewer = new WaveformViewer();
viewer.sync = new UISynchronize() {
@Override public void asyncExec(Runnable runnable) { UiDispatch.async(display, runnable); }
@Override public void syncExec(Runnable runnable) { display.syncExec(runnable); }
@Override protected boolean isUIThread(Thread thread) { return thread == display.getThread(); }
@Override protected void showBusyWhile(Runnable runnable) { runnable.run(); }
@Override protected boolean dispatchEvents() { return display.readAndDispatch(); }
};
snapshot = WaveformViewer.class.getDeclaredMethod("transactionSnapshot", ITx.class);
snapshot.setAccessible(true);
refresh = WaveformViewer.class.getDeclaredMethod("refreshHoverWhenReady", Composite.class, ITx.class, Runnable.class);
refresh.setAccessible(true);
ITxAttribute attribute = (ITxAttribute) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{ITxAttribute.class},
(proxy, method, args) -> switch (method.getName()) {
case "getName" -> "address";
case "getValue" -> "0x1234";
case "getDataType" -> DataType.STRING;
default -> null;
});
transaction = (ITx) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[]{ITx.class},
(proxy, method, args) -> {
if (method.getName().equals("getAttributes")) {
assertNull("Hover attributes must load off SWT", Display.getCurrent());
reads.incrementAndGet(); loading.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
return List.of(attribute);
}
if (method.getName().endsWith("Relations")) return List.of();
return null;
});
}
@After public void cleanup() {
release.countDown();
if (display == null) return;
viewer.closeDatabase();
for (Shell shell : display.getShells()) if (!shell.isDisposed()) shell.dispose();
while (display.readAndDispatch()) { }
display.dispose();
}
private AsyncTransactionData.Snapshot data() {
try { return (AsyncTransactionData.Snapshot) snapshot.invoke(viewer, transaction); }
catch (ReflectiveOperationException e) { throw new AssertionError(e); }
}
private Table show(Shell popup, AtomicInteger updates) throws Exception {
Table table = new Table(popup, SWT.NONE);
new TableColumn(table, SWT.NONE); new TableColumn(table, SWT.NONE);
refresh.invoke(viewer, popup, transaction, (Runnable) () -> {
assertSame(display, Display.getCurrent());
updates.incrementAndGet();
table.removeAll();
for (ITxAttribute attribute : data().attributes())
new TableItem(table, SWT.NONE).setText(new String[]{attribute.getName(), attribute.getValue().toString()});
});
return table;
}
private void await(BooleanSupplier condition) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (!condition.getAsBoolean()) {
while (display.readAndDispatch()) { }
assertTrue("Attribute completion was not published", System.nanoTime() < deadline);
Thread.sleep(5);
}
}
@Test public void firstHoverPopulatesWhenTheBackgroundReadCompletes() throws Exception {
AtomicInteger updates = new AtomicInteger();
Table table = show(new Shell(display), updates);
assertTrue(loading.await(5, TimeUnit.SECONDS));
assertEquals(0, table.getItemCount());
release.countDown();
await(() -> table.getItemCount() == 1);
assertEquals("address", table.getItem(0).getText(0));
assertEquals("0x1234", table.getItem(0).getText(1));
assertEquals(2, updates.get());
assertEquals(1, reads.get());
}
@Test public void closingAnOldPopupDoesNotDetachItsReplacement() throws Exception {
Shell old = new Shell(display);
AtomicInteger oldUpdates = new AtomicInteger(), newUpdates = new AtomicInteger();
show(old, oldUpdates);
assertTrue(loading.await(5, TimeUnit.SECONDS));
Table replacement = show(new Shell(display), newUpdates);
old.dispose();
release.countDown();
await(() -> replacement.getItemCount() == 1);
assertEquals(1, oldUpdates.get());
assertEquals(2, newUpdates.get());
assertEquals(1, reads.get());
}
@Test public void aClosedPopupIsNotRefreshedAfterLoading() throws Exception {
Shell popup = new Shell(display);
AtomicInteger updates = new AtomicInteger();
show(popup, updates);
assertTrue(loading.await(5, TimeUnit.SECONDS));
popup.dispose(); release.countDown();
var field = WaveformViewer.class.getDeclaredField("transactionSnapshots"); field.setAccessible(true);
AsyncTransactionData cache = (AsyncTransactionData) field.get(viewer);
await(() -> cache.isReady(transaction));
assertEquals(1, updates.get());
}
}