represented = representation.submit(() -> representModelUnlessCanceled(monitor, model));
+ if (! Boolean.TRUE.equals(represented.get()))
+ return;
if (Boolean.TRUE.equals(auto_size_stage))
{
@@ -378,7 +396,8 @@ public void loadDisplayFile(final DisplayInfo info)
}
// Start runtime for the model
- RuntimeUtil.startRuntime(model);
+ if (! startRuntimeUnlessCanceled(monitor, model))
+ return;
logger.log(Level.FINE, "Waiting for representation of model " + info.getPath());
@@ -402,6 +421,11 @@ public void loadDisplayFile(final DisplayInfo info)
}
catch (Exception ex)
{
+ if (monitor.isCanceled())
+ { // Replaced by a newer load or closed: Nothing to report to the user
+ logger.log(Level.FINE, ex, () -> "Cannot load model from " + info.getPath() + ", which was replaced or closed meanwhile");
+ return;
+ }
logger.log(Level.SEVERE, "Cannot load model from " + info.getPath(), ex);
final String exception_message;
@@ -479,6 +503,58 @@ private Void representModel(final DisplayModel model) throws Exception
return null;
}
+ /** Represent a loaded model, unless its load was cancelled. Called on the UI thread, where loads are cancelled
+ * @param monitor Monitor of the job that loaded the model
+ * @param model Model to represent
+ * @return true if represented
+ * @throws Exception on error
+ */
+ private boolean representModelUnlessCanceled(final JobMonitor monitor, final DisplayModel model) throws Exception
+ {
+ if (monitor.isCanceled())
+ {
+ model.dispose();
+ return false;
+ }
+ representModel(model);
+ return true;
+ }
+
+ /** Start the runtime of a represented model, unless its load was cancelled.
+ * If the display is disposed while the runtime starts, stop it and dispose the model, see {@link #disposeModel()}
+ * @param monitor Monitor of the job that loaded the model
+ * @param model Model to start
+ * @return true if the runtime was started and the load is still the current one
+ */
+ private boolean startRuntimeUnlessCanceled(final JobMonitor monitor, final DisplayModel model)
+ {
+ synchronized (start_lock)
+ {
+ starting_model.set(model);
+ if (monitor.isCanceled())
+ { // Disposed before the start. Unless the UI thread did it all, dispose the model
+ if (! starting_model.compareAndSet(model, null))
+ model.dispose();
+ return false;
+ }
+ RuntimeUtil.startRuntime(model);
+ if (starting_model.compareAndSet(model, null))
+ return ! monitor.isCanceled();
+ // Disposed while starting, left to this job
+ RuntimeUtil.stopRuntime(model);
+ model.dispose();
+ return false;
+ }
+ }
+
+ /** Cancel the load of a display, if one is in progress */
+ private void cancelLoad()
+ {
+ if (load_job != null && ! load_job.getMonitor().isDone())
+ load_job.cancel();
+ load_job = null;
+ }
+
/** Take note of the currently displayed model
*
* Called by the {@link DockItemRepresentation},
@@ -524,14 +600,19 @@ void trackCurrentModel(final DisplayModel model)
active_model = model;
}
- /** Stop runtime, dispose representation for current model */
+ /** Stop runtime, dispose representation for current model. Callers first cancel a load, see {@link #cancelLoad()} */
private void disposeModel()
{
final DisplayModel model = active_model;
active_model = null;
- // Close handler disposes runtime and representation for model
- if (model != null)
+ if (model == null)
+ return;
+ if (starting_model.compareAndSet(model, null))
+ // The load job is starting the runtime and will then stop it and dispose the model
+ representation.disposeRepresentation(model);
+ else
+ // Close handler disposes runtime and representation for model
ActionUtil.handleClose(model);
}
@@ -569,6 +650,8 @@ private void showRepresentationError()
/** DockItem closed */
public void onClosed()
{
+ // If still loading a display, skip it
+ cancelLoad();
// Stop runtime, dispose widgets for the model
disposeModel();
// Stop representation, so no more widgets can be created in this dock item
@@ -614,4 +697,4 @@ private boolean isCreateNewStage(String target)
{
return target.startsWith("window") || target.startsWith(TAG_STANDALONE);
}
-}
\ No newline at end of file
+}
diff --git a/app/display/runtime/src/test/java/org/csstudio/display/builder/runtime/app/BlockingPVFactory.java b/app/display/runtime/src/test/java/org/csstudio/display/builder/runtime/app/BlockingPVFactory.java
new file mode 100644
index 0000000000..e1510f559b
--- /dev/null
+++ b/app/display/runtime/src/test/java/org/csstudio/display/builder/runtime/app/BlockingPVFactory.java
@@ -0,0 +1,60 @@
+package org.csstudio.display.builder.runtime.app;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.phoebus.pv.PV;
+import org.phoebus.pv.PVFactory;
+
+/** Creates PVs "blocking://..." for tests
+ *
+ *
After {@link #block()}, creating the next PV waits until {@link #release()},
+ * like a PV type that connects while it is created.
+ * This keeps a display runtime in its start for as long as a test needs.
+ */
+@SuppressWarnings("nls")
+public class BlockingPVFactory implements PVFactory
+{
+ private static volatile CountDownLatch creating = new CountDownLatch(0);
+ private static volatile CountDownLatch released = new CountDownLatch(0);
+
+ /** Make the next PV creation wait until {@link #release()} */
+ static void block()
+ {
+ creating = new CountDownLatch(1);
+ released = new CountDownLatch(1);
+ }
+
+ /** Wait until a PV creation is waiting
+ * @throws InterruptedException when interrupted
+ */
+ static void awaitCreation() throws InterruptedException
+ {
+ if (! creating.await(10, TimeUnit.SECONDS))
+ throw new IllegalStateException("No PV was created");
+ }
+
+ /** Let a waiting PV creation continue */
+ static void release()
+ {
+ released.countDown();
+ }
+
+ @Override
+ public String getType()
+ {
+ return "blocking";
+ }
+
+ @Override
+ public PV createPV(final String name, final String base_name) throws Exception
+ {
+ creating.countDown();
+ if (! released.await(10, TimeUnit.SECONDS))
+ throw new IllegalStateException("PV creation was not released");
+ return new PV(name)
+ {
+ // Never connects, which is enough for these tests
+ };
+ }
+}
diff --git a/app/display/runtime/src/test/java/org/csstudio/display/builder/runtime/app/DisplayLoadSequenceUI.java b/app/display/runtime/src/test/java/org/csstudio/display/builder/runtime/app/DisplayLoadSequenceUI.java
new file mode 100644
index 0000000000..6c9a4c4ddd
--- /dev/null
+++ b/app/display/runtime/src/test/java/org/csstudio/display/builder/runtime/app/DisplayLoadSequenceUI.java
@@ -0,0 +1,305 @@
+package org.csstudio.display.builder.runtime.app;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+
+import org.csstudio.display.builder.representation.javafx.JFXRepresentation;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.phoebus.framework.jobs.JobManager;
+import org.phoebus.pv.PV;
+import org.phoebus.pv.PVPool;
+import org.phoebus.pv.RefCountMap;
+import org.phoebus.ui.docking.DockStage;
+import org.testfx.framework.junit5.ApplicationTest;
+import org.testfx.util.WaitForAsyncUtils;
+
+import javafx.collections.ListChangeListener;
+import javafx.collections.ObservableList;
+import javafx.scene.Node;
+import javafx.scene.control.Label;
+import javafx.stage.Stage;
+
+/** Loads of a display that follow each other quickly
+ *
+ *
Each display has its own PV.
+ * Only the PV of the display that's shown in the end may remain open,
+ * and a load that was replaced must not report errors.
+ */
+@SuppressWarnings("nls")
+class DisplayLoadSequenceUI extends ApplicationTest
+{
+ /** Errors: SEVERE log messages, a display runtime that could not be stopped, exceptions on the UI thread */
+ private final List errors = new CopyOnWriteArrayList<>();
+
+ private final Handler errorLog = new Handler()
+ {
+ @Override
+ public void publish(final LogRecord rec)
+ {
+ if (rec.getLevel().intValue() >= Level.SEVERE.intValue() ||
+ String.valueOf(rec.getMessage()).startsWith("Skipping display shutdown"))
+ errors.add(rec.getMessage());
+ }
+
+ @Override
+ public void flush()
+ {
+ // Nothing to flush
+ }
+
+ @Override
+ public void close()
+ {
+ // Nothing to close
+ }
+ };
+
+ private Stage stage;
+ private DisplayRuntimeInstance instance;
+ private boolean closed = false;
+
+ /** References to test display PVs before the test, see {@link #openPVs()} */
+ private Map pvsBefore;
+
+ @Override
+ public void start(final Stage primaryStage)
+ {
+ pvsBefore = pvReferences();
+ Logger.getLogger("").addHandler(errorLog);
+ Thread.currentThread().setUncaughtExceptionHandler((thread, ex) -> errors.add(ex.toString()));
+ stage = new Stage();
+ DockStage.configureStage(stage);
+ stage.show();
+ instance = new DisplayRuntimeInstance(new DisplayRuntimeApplication());
+ }
+
+ @AfterEach
+ void closeStage() throws Exception
+ {
+ if (! closed)
+ close();
+ interact(stage::close);
+ Logger.getLogger("").removeHandler(errorLog);
+ }
+
+ @Test
+ void testShownDisplayIsReplacedRightAway() throws Exception
+ {
+ open("a");
+
+ // As soon as a new load starts, before the file has even been read,
+ // the shown display is gone and the user sees that a display is loading
+ final DisplayInfo b = info("b");
+ final AtomicReference> pvsWhileLoading = new AtomicReference<>();
+ final List added = new CopyOnWriteArrayList<>();
+ final ListChangeListener recordAdded = change ->
+ {
+ while (change.next())
+ change.getAddedSubList().forEach(node -> added.add(describe(node)));
+ };
+ interact(() ->
+ {
+ displayArea().addListener(recordAdded);
+ instance.loadDisplayFile(b);
+ pvsWhileLoading.set(openPVs());
+ });
+ waitForDisplay("b");
+ interact(() -> displayArea().removeListener(recordAdded));
+
+ assertThat(pvsWhileLoading.get(), equalTo(List.of()));
+ // First the message, then the widgets of 'b'
+ assertThat(added.get(0), equalTo("Loading " + b));
+ assertThat(added.get(added.size() - 1), equalTo("widget"));
+ assertThat(openPVs(), equalTo(List.of("load_b")));
+ assertThat(errors, equalTo(List.of()));
+ }
+
+ @Test
+ void testBackTwiceInARow() throws Exception
+ {
+ open("a");
+ open("b");
+ open("c");
+
+ // Two 'back' steps before the first one has been represented
+ interact(() ->
+ {
+ instance.loadDisplayFile(instance.getNavigation().goBackward(1));
+ instance.loadDisplayFile(instance.getNavigation().goBackward(1));
+ });
+ waitForDisplay("a");
+
+ assertThat(openPVs(), equalTo(List.of("load_a")));
+ assertThat(errors, equalTo(List.of()));
+ }
+
+ @Test
+ void testReplacedLoadFails() throws Exception
+ {
+ open("a");
+
+ // A load that fails is replaced by a newer one before it fails
+ final DisplayInfo missing = info("missing");
+ final DisplayInfo c = info("c");
+ interact(() ->
+ {
+ instance.loadDisplayFile(missing);
+ instance.loadDisplayFile(c);
+ });
+ waitForDisplay("c");
+
+ assertThat(openPVs(), equalTo(List.of("load_c")));
+ assertThat(errors, equalTo(List.of()));
+ }
+
+ @Test
+ void testLoadWhileRuntimeStarts() throws Exception
+ {
+ open("a");
+
+ // Load a display whose runtime start takes long, because its PV is slow to create
+ BlockingPVFactory.block();
+ final DisplayInfo slow = info("slow");
+ interact(() -> instance.loadDisplayFile(slow));
+ BlockingPVFactory.awaitCreation();
+
+ // A newer load during that start doesn't have to wait for it
+ final DisplayInfo b = info("b");
+ final long start = System.currentTimeMillis();
+ interact(() -> instance.loadDisplayFile(b));
+ final long waited = System.currentTimeMillis() - start;
+ BlockingPVFactory.release();
+ waitForDisplay("b");
+
+ assertThat("Milliseconds the UI waited: " + waited, waited < 2000, equalTo(true));
+ // The started runtime of the 'slow' display was stopped
+ assertThat(openPVs(), equalTo(List.of("load_b")));
+ assertThat(errors, equalTo(List.of()));
+ }
+
+ @Test
+ void testCloseWhileLoading() throws Exception
+ {
+ open("a");
+
+ // Close the display before the load of 'b' can run
+ final DisplayInfo b = info("b");
+ instance.getDockItem().prepareToClose();
+ interact(() ->
+ {
+ instance.loadDisplayFile(b);
+ instance.close();
+ });
+ closed = true;
+ waitForLoads();
+
+ assertThat(openPVs(), equalTo(List.of()));
+ // Not reported as a failed load.
+ // (The 'Loading' message that the closed display can no longer show
+ // fails the same way on master, which this test doesn't cover.)
+ assertThat(errors.stream().filter(error -> error.startsWith("Cannot load model")).toList(), equalTo(List.of()));
+ }
+
+ /** @param name Name of the test display, "a", "b", "c", "slow", or "missing" for one that doesn't exist
+ * @return {@link DisplayInfo} for that display
+ */
+ private DisplayInfo info(final String name) throws Exception
+ {
+ return DisplayInfo.forURI(getClass().getResource("/loading/load_a.bob").toURI().resolve("load_" + name + ".bob"));
+ }
+
+ /** @param name Name of the test display to load and wait for */
+ private void open(final String name) throws Exception
+ {
+ final DisplayInfo info = info(name);
+ interact(() -> instance.loadDisplayFile(info));
+ waitForDisplay(name);
+ }
+
+ /** Close the display the same way as its tab or window would */
+ private void close() throws Exception
+ {
+ instance.getDockItem().prepareToClose();
+ interact(instance::close);
+ closed = true;
+ }
+
+ /** Wait until a test display is shown and no load job is left
+ * @param name Name of the test display
+ */
+ private void waitForDisplay(final String name) throws TimeoutException
+ {
+ final String label = "Display " + name;
+ WaitForAsyncUtils.waitFor(10, TimeUnit.SECONDS,
+ () -> label.equals(WaitForAsyncUtils.waitFor(WaitForAsyncUtils.asyncFx(() -> instance.getDockItem().getLabel()))));
+ waitForLoads();
+ }
+
+ /** Wait until no load job is left.
+ * Call after interact(), by which time a job that was just scheduled is running and counted.
+ */
+ private static void waitForLoads() throws TimeoutException
+ {
+ WaitForAsyncUtils.waitFor(10, TimeUnit.SECONDS, () -> JobManager.getJobCount() == 0);
+ WaitForAsyncUtils.waitForFxEvents();
+ }
+
+ /** @return Nodes in the area of the display. Call on the UI thread */
+ private ObservableList displayArea()
+ {
+ return JFXRepresentation.getChildren(instance.getRepresentation().getModelParent());
+ }
+
+ /** @param node Node added to the display area
+ * @return Text of the 'Loading ...' message, or "widget"
+ */
+ private static String describe(final Node node)
+ {
+ if (node instanceof Label label && label.getText().startsWith("Loading"))
+ return label.getText();
+ return "widget";
+ }
+
+ /** @return Test display PVs that this test opened and that are still open, for example "load_a".
+ * PVs that an earlier test left open don't count.
+ */
+ private List openPVs()
+ {
+ final List open = new ArrayList<>();
+ pvReferences().forEach((name, references) ->
+ {
+ for (int i = pvsBefore.getOrDefault(name, 0); i < references; ++i)
+ open.add(name);
+ });
+ Collections.sort(open);
+ return open;
+ }
+
+ /** @return References to each test display PV, by name like "load_a" */
+ private static Map pvReferences()
+ {
+ final Map references = new HashMap<>();
+ for (RefCountMap.ReferencedEntry ref : PVPool.getPVReferences())
+ {
+ final String name = ref.getEntry().getName();
+ if (name.contains("load_"))
+ references.merge(name.substring(name.indexOf("load_")), ref.getReferences(), Integer::sum);
+ }
+ return references;
+ }
+}
diff --git a/app/display/runtime/src/test/resources/META-INF/services/org.phoebus.pv.PVFactory b/app/display/runtime/src/test/resources/META-INF/services/org.phoebus.pv.PVFactory
new file mode 100644
index 0000000000..cef428ef04
--- /dev/null
+++ b/app/display/runtime/src/test/resources/META-INF/services/org.phoebus.pv.PVFactory
@@ -0,0 +1 @@
+org.csstudio.display.builder.runtime.app.BlockingPVFactory
diff --git a/app/display/runtime/src/test/resources/loading/load_a.bob b/app/display/runtime/src/test/resources/loading/load_a.bob
new file mode 100644
index 0000000000..ba74932563
--- /dev/null
+++ b/app/display/runtime/src/test/resources/loading/load_a.bob
@@ -0,0 +1,10 @@
+
+
+ Display a
+ 300
+ 100
+
+ Value
+ sim://ramp(0,10,0.1)load_a
+
+
diff --git a/app/display/runtime/src/test/resources/loading/load_b.bob b/app/display/runtime/src/test/resources/loading/load_b.bob
new file mode 100644
index 0000000000..a20bbffe7c
--- /dev/null
+++ b/app/display/runtime/src/test/resources/loading/load_b.bob
@@ -0,0 +1,10 @@
+
+
+ Display b
+ 300
+ 100
+
+ Value
+ sim://ramp(0,10,0.1)load_b
+
+
diff --git a/app/display/runtime/src/test/resources/loading/load_c.bob b/app/display/runtime/src/test/resources/loading/load_c.bob
new file mode 100644
index 0000000000..d7ebb2a077
--- /dev/null
+++ b/app/display/runtime/src/test/resources/loading/load_c.bob
@@ -0,0 +1,10 @@
+
+
+ Display c
+ 300
+ 100
+
+ Value
+ sim://ramp(0,10,0.1)load_c
+
+
diff --git a/app/display/runtime/src/test/resources/loading/load_slow.bob b/app/display/runtime/src/test/resources/loading/load_slow.bob
new file mode 100644
index 0000000000..903c4427f3
--- /dev/null
+++ b/app/display/runtime/src/test/resources/loading/load_slow.bob
@@ -0,0 +1,10 @@
+
+
+ Display slow
+ 300
+ 100
+
+ Value
+ blocking://load_slow
+
+