You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sis.apache.org by de...@apache.org on 2021/11/03 18:11:33 UTC

[sis] 02/02: Fix `NullPointerException`, partially caused by changes in `MapCanvas` state when a rendering is in progress. We workaround this problem with a new `MapCanvas.runAfterRendering(Runnable)` method.

This is an automated email from the ASF dual-hosted git repository.

desruisseaux pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git

commit fed0a14ea23a3233ee4eb0586961a1382ea44d0d
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Wed Nov 3 18:09:17 2021 +0100

    Fix `NullPointerException`, partially caused by changes in `MapCanvas` state when a rendering is in progress.
    We workaround this problem with a new `MapCanvas.runAfterRendering(Runnable)` method.
---
 .../apache/sis/gui/coverage/CoverageCanvas.java    | 18 ++++-
 .../org/apache/sis/gui/coverage/RenderingData.java |  9 ++-
 .../java/org/apache/sis/gui/map/MapCanvas.java     | 89 +++++++++++++++++++++-
 .../java/org/apache/sis/gui/map/MapCanvasAWT.java  | 18 ++++-
 4 files changed, 125 insertions(+), 9 deletions(-)

diff --git a/application/sis-javafx/src/main/java/org/apache/sis/gui/coverage/CoverageCanvas.java b/application/sis-javafx/src/main/java/org/apache/sis/gui/coverage/CoverageCanvas.java
index fd667d1..b9b5825 100644
--- a/application/sis-javafx/src/main/java/org/apache/sis/gui/coverage/CoverageCanvas.java
+++ b/application/sis-javafx/src/main/java/org/apache/sis/gui/coverage/CoverageCanvas.java
@@ -419,7 +419,7 @@ public class CoverageCanvas extends MapCanvasAWT {
     private void onImageSpecified() {
         final GridCoverage coverage = getCoverage();
         if (coverage == null) {
-            clear();
+            runAfterRendering(this::clear);
         } else {
             final GridExtent sliceExtent = getSliceExtent();
             BackgroundThreads.execute(new Task<RenderedImage>() {
@@ -462,7 +462,10 @@ public class CoverageCanvas extends MapCanvasAWT {
                  * Invoked in JavaFX thread for setting the image to the instance we just fetched.
                  */
                 @Override protected void succeeded() {
-                    setRawImage(getValue(), imageGeometry, coverage.getSampleDimensions());
+                    final RenderedImage image = getValue();
+                    final GridGeometry    gg  = imageGeometry;
+                    List<SampleDimension> sd  = coverage.getSampleDimensions();
+                    runAfterRendering(() -> setRawImage(image, gg, sd));
                 }
             });
         }
@@ -895,6 +898,17 @@ public class CoverageCanvas extends MapCanvasAWT {
 
     /**
      * Removes the image shown and releases memory.
+     *
+     * <h4>Usage</h4>
+     * Overriding methods in subclasses should invoke {@code super.clear()}.
+     * Other methods should generally not invoke this method directly,
+     * and use the following code instead:
+     *
+     * {@preformat java
+     *     runAfterRendering(this::clear);
+     * }
+     *
+     * @see #runAfterRendering(Runnable)
      */
     @Override
     protected void clear() {
diff --git a/application/sis-javafx/src/main/java/org/apache/sis/gui/coverage/RenderingData.java b/application/sis-javafx/src/main/java/org/apache/sis/gui/coverage/RenderingData.java
index 8fcb117..646720b 100644
--- a/application/sis-javafx/src/main/java/org/apache/sis/gui/coverage/RenderingData.java
+++ b/application/sis-javafx/src/main/java/org/apache/sis/gui/coverage/RenderingData.java
@@ -253,13 +253,16 @@ final class RenderingData implements Cloneable {
         this.data          = data;
         this.dataGeometry  = domain;
         this.dataRanges    = ranges;        // Not cloned because already an unmodifiable list.
-        if (!domain.isDefined(GridGeometry.GRID_TO_CRS)) {
+        if (domain != null && !domain.isDefined(GridGeometry.GRID_TO_CRS)
+                           &&  domain.isDefined(GridGeometry.EXTENT))
+        {
             CoordinateReferenceSystem crs = null;
             if (domain.isDefined(GridGeometry.CRS)) {
                 crs = domain.getCoordinateReferenceSystem();
             }
-            dataGeometry = new GridGeometry(domain.getExtent(), PixelInCell.CELL_CENTER,
-                                    MathTransforms.identity(domain.getDimension()), crs);
+            final GridExtent extent = domain.getExtent();
+            dataGeometry = new GridGeometry(extent, PixelInCell.CELL_CENTER,
+                    MathTransforms.identity(extent.getDimension()), crs);
         }
     }
 
diff --git a/application/sis-javafx/src/main/java/org/apache/sis/gui/map/MapCanvas.java b/application/sis-javafx/src/main/java/org/apache/sis/gui/map/MapCanvas.java
index f8241bb..edd6cca 100644
--- a/application/sis-javafx/src/main/java/org/apache/sis/gui/map/MapCanvas.java
+++ b/application/sis-javafx/src/main/java/org/apache/sis/gui/map/MapCanvas.java
@@ -225,6 +225,14 @@ public abstract class MapCanvas extends PlanarCanvas {
     private Task<?> renderingInProgress;
 
     /**
+     * User-specified task of execute after rendering is completed, or {@code null} if none.
+     * {@code MapCanvas} does not use this mechanism for itself, but some subclasses need it.
+     *
+     * @see #runAfterRendering(Runnable)
+     */
+    private Runnable afterRendering;
+
+    /**
      * Whether the size of this canvas changed.
      */
     private boolean sizeChanged;
@@ -1059,6 +1067,10 @@ public abstract class MapCanvas extends PlanarCanvas {
      * Creates the background task which will invoke {@link Renderer#render()} in a background thread.
      * The tasks must invoke {@link #renderingCompleted(Task)} in JavaFX thread after completion,
      * either successful or not.
+     *
+     * <p><b>Note:</b> it is important that no other worker is in progress at the time this method is invoked
+     * ({@code assert renderingInProgress == null}), otherwise conflicts may happen when workers will update
+     * the {@code MapCanvas} fields after they completed their task.</p>
      */
     Task<?> createWorker(final Renderer renderer) {
         return new Task<Void>() {
@@ -1113,6 +1125,18 @@ public abstract class MapCanvas extends PlanarCanvas {
         } else if (!hasError) {
             clearError();
         }
+        /*
+         * Run user-specified task if any. `MapCanvas` does not use this mechanism for itself,
+         * but some subclasses need it. User is responsible for providing tasks that do not fail.
+         */
+        final Runnable t = afterRendering;
+        if (t != null) try {
+            afterRendering = null;
+            t.run();
+        } catch (Exception e) {
+            // `runAfterRendering(…)` is the documented method providing this feature.
+            unexpectedException("runAfterRendering", e);
+        }
     }
 
     /**
@@ -1150,8 +1174,10 @@ public abstract class MapCanvas extends PlanarCanvas {
      * @see #requestRepaint()
      */
     private void paintAfterDelay() {
-        renderingInProgress = null;
-        repaint();
+        if (renderingInProgress instanceof Delayed) {
+            renderingInProgress = null;
+            repaint();
+        }
     }
 
     /**
@@ -1207,6 +1233,8 @@ public abstract class MapCanvas extends PlanarCanvas {
      * is reset to {@code false} after this {@code MapCanvas} has been updated with new rendering result.
      *
      * @return a property telling whether a rendering is in progress.
+     *
+     * @see #runAfterRendering(Runnable)
      */
     public final ReadOnlyBooleanProperty renderingProperty() {
         return isRendering.getReadOnlyProperty();
@@ -1252,14 +1280,69 @@ public abstract class MapCanvas extends PlanarCanvas {
     /**
      * Invoked when an unexpected exception occurred but it is okay to continue despite it.
      */
-    private static void unexpectedException(final String method, final NonInvertibleTransformException e) {
+    private static void unexpectedException(final String method, final Exception e) {
         Logging.unexpectedException(Logging.getLogger(Modules.APPLICATION), MapCanvas.class, method, e);
     }
 
     /**
+     * Registers a task to execute after the background thread finished its current rendering task.
+     * This method shall be invoked in JavaFX thread. If there is a {@linkplain #renderingProperty()
+     * rendering in progress} at the time this method is invoked, then the given task is queued for
+     * execution in JavaFX thread after the rendering finished.
+     * Otherwise the given task is executed immediately.
+     *
+     * <p>Exceptions are propagated if the given task has been executed immediately,
+     * or logged if execution has been deferred.</p>
+     *
+     * <p>This method is useful for subclasses when modifying the {@code MapCanvas} state during
+     * a rendering process may cause inconsistent state.</p>
+     *
+     * @param  task  the task to execute.
+     * @return {@code true} if the task has been executed immediately, or
+     *         {@code false} if it has been queued for later execution.
+     *
+     * @see #renderingProperty()
+     * @see Platform#runLater(Runnable)
+     *
+     * @since 1.2
+     */
+    protected boolean runAfterRendering(final Runnable task) {
+        ArgumentChecks.ensureNonNull("task", task);
+        assert Platform.isFxApplicationThread();
+        if (renderingInProgress == null || renderingInProgress instanceof Delayed) {
+            task.run();
+            return true;
+        }
+        final Runnable before = afterRendering;
+        if (before == null) {
+            afterRendering = task;
+        } else {
+            afterRendering = () -> {
+                try {
+                    before.run();
+                } catch (Exception e) {
+                    unexpectedException("runAfterRendering", e);
+                }
+                task.run();
+            };
+        }
+        return false;
+    }
+
+    /**
      * Removes map content and clears all properties of this canvas.
      *
+     * <h4>Usage</h4>
+     * Overriding methods in subclasses should invoke {@code super.clear()}.
+     * Other methods should generally not invoke this method directly,
+     * and use the following code instead:
+     *
+     * {@preformat java
+     *     runAfterRendering(this::clear);
+     * }
+     *
      * @see #reset()
+     * @see #runAfterRendering(Runnable)
      */
     protected void clear() {
         assert Platform.isFxApplicationThread();
diff --git a/application/sis-javafx/src/main/java/org/apache/sis/gui/map/MapCanvasAWT.java b/application/sis-javafx/src/main/java/org/apache/sis/gui/map/MapCanvasAWT.java
index 863cbcb..0bb9da6 100644
--- a/application/sis-javafx/src/main/java/org/apache/sis/gui/map/MapCanvasAWT.java
+++ b/application/sis-javafx/src/main/java/org/apache/sis/gui/map/MapCanvasAWT.java
@@ -339,6 +339,11 @@ public abstract class MapCanvasAWT extends MapCanvas {
      * In all cases we need to be careful to not use directly any {@link MapCanvas} field from the {@code call()}
      * methods. Information needed by {@code call()} must be copied first.
      *
+     * <h4>Preconditions</h4>
+     * It is important that no other worker is in progress at the time this method is invoked
+     * ({@code assert renderingInProgress == null}), otherwise conflicts may happen when workers
+     * will update the {@code MapCanvasAWT} fields after they completed their task.</p>
+     *
      * @see #requestRepaint()
      */
     @Override
@@ -593,7 +598,7 @@ public abstract class MapCanvasAWT extends MapCanvas {
                     final Graphics2D gr = buffer.createGraphics();
                     try {
                         renderer.translate(gr);
-                        gr.setColor(new Color(0XA0804040, true));
+                        gr.setColor(new Color(0xA0804040, true));
                         gr.fillRoundRect(x, y, width, height, width/5, height/5);
                         gr.setColor(Color.RED);
                         final GlyphVector glyphs = font.createGlyphVector(gr.getFontRenderContext(), WARNING_TEXT);
@@ -625,6 +630,17 @@ public abstract class MapCanvasAWT extends MapCanvas {
     /**
      * Clears the image and all intermediate buffer.
      * Invoking this method may help to release memory when the map is no longer shown.
+     *
+     * <h4>Usage</h4>
+     * Overriding methods in subclasses should invoke {@code super.clear()}.
+     * Other methods should generally not invoke this method directly,
+     * and use the following code instead:
+     *
+     * {@preformat java
+     *     runAfterRendering(this::clear);
+     * }
+     *
+     * @see #runAfterRendering(Runnable)
      */
     @Override
     protected void clear() {