This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git
The following commit(s) were added to refs/heads/geoapi-4.0 by this push:
new 638fa5e2c6 Avoid lost of information: - Tile observers in
`ImageAdapter`. - ColorModel when converting from RGB to float then back to RGB.
638fa5e2c6 is described below
commit 638fa5e2c63c8cc9812aab05584172f5fe52b25b
Author: Martin Desruisseaux <[email protected]>
AuthorDate: Wed Nov 18 01:45:02 2026 +0100
Avoid lost of information:
- Tile observers in `ImageAdapter`.
- ColorModel when converting from RGB to float then back to RGB.
---
.../org/apache/sis/coverage/SampleDimension.java | 84 ++---
.../sis/coverage/grid/ConvertedGridCoverage.java | 6 +-
.../coverage/internal/shared/SampleDimensions.java | 6 +-
.../main/org/apache/sis/image/AggregatedImage.java | 15 +-
.../main/org/apache/sis/image/AnnotatedImage.java | 6 +-
.../org/apache/sis/image/BandAggregateImage.java | 4 +-
.../apache/sis/image/BandedSampleConverter.java | 419 ++++++++++++++-------
.../main/org/apache/sis/image/ComputedImage.java | 86 +----
.../main/org/apache/sis/image/ComputedTiles.java | 34 +-
.../main/org/apache/sis/image/ImageAdapter.java | 128 ++++---
.../main/org/apache/sis/image/ImageProcessor.java | 6 +-
.../main/org/apache/sis/image/MonolithicImage.java | 85 ++---
.../main/org/apache/sis/image/PixelIterator.java | 4 +-
.../main/org/apache/sis/image/PlanarImage.java | 136 ++++---
.../main/org/apache/sis/image/PrefetchedImage.java | 63 +---
.../main/org/apache/sis/image/RecoloredImage.java | 8 +-
.../main/org/apache/sis/image/ResampledImage.java | 4 +-
.../org/apache/sis/image/TileForwardingImage.java | 71 ++++
.../main/org/apache/sis/image/Transferer.java | 2 +-
.../main/org/apache/sis/image/UserProperties.java | 4 +-
.../main/org/apache/sis/image/Visualization.java | 4 +-
.../image/internal/shared/WritableTiledImage.java | 40 +-
.../internal/shared/WritableUntiledImage.java | 25 +-
.../sis/image/BandedSampleConverterTest.java | 12 +-
.../sis/gui/coverage/ImagePropertyExplorer.java | 9 +-
25 files changed, 688 insertions(+), 573 deletions(-)
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/SampleDimension.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/SampleDimension.java
index 02642ff0da..4c0ee738c2 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/SampleDimension.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/SampleDimension.java
@@ -514,7 +514,7 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
return true;
}
if (object instanceof SampleDimension) {
- final SampleDimension that = (SampleDimension) object;
+ final var that = (SampleDimension) object;
/*
* `transferFunction` does not need to be compared because it is
derived from the categories.
* It is also difficult to keep `transferFunction` comparison
consistent with `categories`
@@ -841,17 +841,17 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
* Adds a qualitative category for samples of the given boolean value.
* The {@code true} value is represented by 1 and the {@code false}
value is represented by 0.
*
- * <h4>Usage note</h4>
+ * <p><b>Usage note:</b>
* The {@link #setBackground(CharSequence, Number)} method should be
used instead of this method
* when the aim is to define a default "no data" category to use when
the missing value cannot
- * be categorized more precisely (cloud, instrument error, <i>etc</i>).
+ * be categorized more precisely (cloud, instrument error,
<i>etc</i>).</p>
*
- * <h4>Default implementation</h4>
- * This convenience method delegates to {@link
#addQualitative(CharSequence, NumberRange)}.
+ * <p><b>Default implementation:</b> this convenience method delegates
to
+ * This convenience method delegates to {@link
#addQualitative(CharSequence, NumberRange)}.</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object,
* or {@code null} for a default "no data" name.
- * @param sample the sample value as a boolean.
+ * @param sample the sample value as a Boolean.
* @return {@code this}, for method call chaining.
*/
public Builder addQualitative(final CharSequence name, final boolean
sample) {
@@ -863,13 +863,13 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
* Adds a qualitative category for samples of the given tiny (8 bits)
integer value.
* The argument is treated as a signed integer ({@value
Byte#MIN_VALUE} to {@value Byte#MAX_VALUE}).
*
- * <h4>Usage note</h4>
+ * <p><b>Usage note:</b>
* The {@link #setBackground(CharSequence, Number)} method should be
used instead of this method
* when the aim is to define a default "no data" category to use when
the missing value cannot
- * be categorized more precisely (cloud, instrument error, <i>etc</i>).
+ * be categorized more precisely (cloud, instrument error,
<i>etc</i>).</p>
*
- * <h4>Default implementation</h4>
- * This convenience method delegates to {@link
#addQualitative(CharSequence, NumberRange)}.
+ * <p><b>Default implementation:</b> this convenience method delegates
to
+ * {@link #addQualitative(CharSequence, NumberRange)}.</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object,
* or {@code null} for a default "no data" name.
@@ -884,13 +884,13 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
* Adds a qualitative category for samples of the given short (16
bits) integer value.
* The argument is treated as a signed integer ({@value
Short#MIN_VALUE} to {@value Short#MAX_VALUE}).
*
- * <h4>Usage note</h4>
+ * <p><b>Usage note:</b>
* The {@link #setBackground(CharSequence, Number)} method should be
used instead of this method
* when the aim is to define a default "no data" category to use when
the missing value cannot
- * be categorized more precisely (cloud, instrument error, <i>etc</i>).
+ * be categorized more precisely (cloud, instrument error,
<i>etc</i>).</p>
*
- * <h4>Default implementation</h4>
- * This convenience method delegates to {@link
#addQualitative(CharSequence, NumberRange)}.
+ * <p><b>Default implementation:</b> this convenience method delegates
to
+ * {@link #addQualitative(CharSequence, NumberRange)}.</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object,
* or {@code null} for a default "no data" name.
@@ -905,13 +905,13 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
* Adds a qualitative category for samples of the given integer value.
* The argument is treated as a signed integer ({@value
Integer#MIN_VALUE} to {@value Integer#MAX_VALUE}).
*
- * <h4>Usage note</h4>
+ * <p><b>Usage note:</b>
* The {@link #setBackground(CharSequence, Number)} method should be
used instead of this method
* when the aim is to define a default "no data" category to use when
the missing value cannot
- * be categorized more precisely (cloud, instrument error, <i>etc</i>).
+ * be categorized more precisely (cloud, instrument error,
<i>etc</i>).</p>
*
- * <h4>Default implementation</h4>
- * This convenience method delegates to {@link
#addQualitative(CharSequence, NumberRange)}.
+ * <p><b>Default implementation:</b> this convenience method delegates
to
+ * {@link #addQualitative(CharSequence, NumberRange)}.</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object,
* or {@code null} for a default "no data" name.
@@ -925,13 +925,13 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
/**
* Adds a qualitative category for samples of the given floating-point
value.
*
- * <h4>Usage note</h4>
+ * <p><b>Usage note:</b>
* The {@link #setBackground(CharSequence, Number)} method should be
used instead of this method
* when the aim is to define a default "no data" category to use when
the missing value cannot
- * be categorized more precisely (cloud, instrument error, <i>etc</i>).
+ * be categorized more precisely (cloud, instrument error,
<i>etc</i>).</p>
*
- * <h4>Default implementation</h4>
- * This convenience method delegates to {@link
#addQualitative(CharSequence, NumberRange)}.
+ * <p><b>Default implementation:</b> this convenience method delegates
to
+ * {@link #addQualitative(CharSequence, NumberRange)}.</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object,
* or {@code null} for a default "no data" name.
@@ -952,13 +952,13 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
/**
* Adds a qualitative category for samples of the given double
precision floating-point value.
*
- * <h4>Usage note</h4>
+ * <p><b>Usage note:</b>
* The {@link #setBackground(CharSequence, Number)} method should be
used instead of this method
* when the aim is to define a default "no data" category to use when
the missing value cannot
- * be categorized more precisely (cloud, instrument error, <i>etc</i>).
+ * be categorized more precisely (cloud, instrument error,
<i>etc</i>).</p>
*
- * <h4>Default implementation</h4>
- * This convenience method delegates to {@link
#addQualitative(CharSequence, NumberRange)}.
+ * <p><b>Default implementation:</b> this convenience method delegates
to
+ * {@link #addQualitative(CharSequence, NumberRange)}.</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object,
* or {@code null} for a default "no data" name.
@@ -979,13 +979,13 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
/**
* Adds a qualitative category for samples in the given range of
values.
*
- * <h4>Usage note</h4>
+ * <p><b>Usage note:</b>
* The {@link #setBackground(CharSequence, Number)} method should be
used instead of this method
* when the aim is to define a default "no data" category to use when
the missing value cannot
- * be categorized more precisely (cloud, instrument error, <i>etc</i>).
+ * be categorized more precisely (cloud, instrument error,
<i>etc</i>).</p>
*
- * <h4>Default implementation</h4>
- * This convenience method delegates to {@link
#addQualitative(CharSequence, NumberRange)}.
+ * <p><b>Default implementation:</b> this convenience method delegates
to
+ * {@link #addQualitative(CharSequence, NumberRange)}.</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object,
* or {@code null} for a default "no data" name.
@@ -1005,10 +1005,10 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
* This is the most generic method for adding a qualitative category.
* All other {@code addQualitative(name, …)} methods are convenience
methods delegating their work to this method.
*
- * <h4>Usage note</h4>
+ * <p><b>Usage note:</b>
* The {@link #setBackground(CharSequence, Number)} method should be
used instead of this method
* when the aim is to define a default "no data" category to use when
the missing value cannot
- * be categorized more precisely (cloud, instrument error, <i>etc</i>).
+ * be categorized more precisely (cloud, instrument error,
<i>etc</i>).</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object,
* or {@code null} for a default "no data" name.
@@ -1030,8 +1030,8 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
* (not necessarily the {@link Float#NaN} canonical value)
* and that value shall not have been used by another category.
*
- * <h4>Default implementation</h4>
- * This convenience method delegates to {@link
#mapQualitative(CharSequence, NumberRange, float)}.
+ * <p><b>Default implementation:</b> this convenience method delegates
to
+ * {@link #mapQualitative(CharSequence, NumberRange, float)}.</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object,
* or {@code null} for a default "no data" name.
@@ -1098,8 +1098,8 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
* <p><b>Warning:</b> this method is provided for convenience when the
scale and offset factors are not explicitly specified.
* If those factor are available, then the other {@code
addQuantitative(name, samples, …)} methods are more reliable.</p>
*
- * <h4>Default implementation</h4>
- * This convenience method delegates to {@link
#addQuantitative(CharSequence, NumberRange, MathTransform1D, Unit)}.
+ * <p><b>Default implementation:</b> this convenience method delegates
to
+ * {@link #addQuantitative(CharSequence, NumberRange, MathTransform1D,
Unit)}.</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object,
* or {@code null} for a default "data" name.
@@ -1137,8 +1137,8 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
* Adds a quantitative category for values ranging from {@code
minimum} to {@code maximum} inclusive
* in the given units of measurement. The transfer function is set to
identity.
*
- * <h4>Default implementation</h4>
- * This convenience method delegates to {@link
#addQuantitative(CharSequence, NumberRange, MathTransform1D, Unit)}.
+ * <p><b>Default implementation:</b> this convenience method delegates
to
+ * {@link #addQuantitative(CharSequence, NumberRange, MathTransform1D,
Unit)}.</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object,
* or {@code null} for a default "data" name.
@@ -1156,8 +1156,8 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
* Adds a quantitative category for values ranging from {@code
minimum} to {@code maximum} inclusive
* in the given units of measurement. The transfer function is set to
identity.
*
- * <h4>Default implementation</h4>
- * This convenience method delegates to {@link
#addQuantitative(CharSequence, NumberRange, MathTransform1D, Unit)}.
+ * <p><b>Default implementation:</b> this convenience method delegates
to
+ * {@link #addQuantitative(CharSequence, NumberRange, MathTransform1D,
Unit)}.</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object,
* or {@code null} for a default "data" name.
@@ -1179,8 +1179,8 @@ public class SampleDimension implements IdentifiedType,
LenientComparable, Seria
*
* Results of above conversion are measurements in the units specified
by the {@code units} argument.
*
- * <h4>Default implementation</h4>
- * This convenience method delegates to {@link
#addQuantitative(CharSequence, NumberRange, MathTransform1D, Unit)}.
+ * <p><b>Default implementation:</b> this convenience method delegates
to
+ * {@link #addQuantitative(CharSequence, NumberRange, MathTransform1D,
Unit)}.</p>
*
* @param name the category name as a {@link String} or {@link
InternationalString} object.
* or {@code null} for a default "data" name.
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/ConvertedGridCoverage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/ConvertedGridCoverage.java
index 78c017524c..10bd1b84b5 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/ConvertedGridCoverage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/grid/ConvertedGridCoverage.java
@@ -142,9 +142,9 @@ final class ConvertedGridCoverage extends
DerivedGridCoverage {
final boolean converted)
throws NoninvertibleTransformException
{
- final int numBands = sources.size();
- final MathTransform1D identity = (MathTransform1D)
MathTransforms.identity(1);
- final MathTransform1D[] converters = new MathTransform1D[numBands];
+ final int numBands = sources.size();
+ final var identity = (MathTransform1D) MathTransforms.identity(1);
+ final var converters = new MathTransform1D[numBands];
Arrays.fill(converters, identity);
for (int i = 0; i < numBands; i++) {
final SampleDimension src = sources.get(i);
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/internal/shared/SampleDimensions.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/internal/shared/SampleDimensions.java
index 74ec3dc952..4974bf6ecc 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/internal/shared/SampleDimensions.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/internal/shared/SampleDimensions.java
@@ -118,8 +118,8 @@ public final class SampleDimensions {
if (bands == null) {
return null;
}
- final Number[] fillValues = new Number[bands.size()];
- for (int i=fillValues.length; --i >= 0;) {
+ final var fillValues = new Number[bands.size()];
+ for (int i = fillValues.length; --i >= 0;) {
final SampleDimension band = bands.get(i);
if (band != null) {
final Optional<Number> bg = band.getBackground();
@@ -150,7 +150,7 @@ public final class SampleDimensions {
if (bands == null) {
return null;
}
- final DoubleUnaryOperator[] sampleFilters = new
DoubleUnaryOperator[bands.size()];
+ final var sampleFilters = new DoubleUnaryOperator[bands.size()];
for (int i = 0; i < sampleFilters.length; i++) {
final SampleDimension band = bands.get(i);
if (band != null) {
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
index ec30889625..2b39da305d 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AggregatedImage.java
@@ -202,12 +202,6 @@ public class AggregatedImage extends MonolithicImage
implements Disposable {
*/
private BitSet[] updatedSourceTiles;
- /**
- * Whether listeners to writable images have been registered.
- * This is done only when first needed and use weak references.
- */
- private boolean hasAddedListeners;
-
/**
* Whether parallel execution is allowed.
* If {@code true}, may threads can be used for aggregating the pixel
values.
@@ -438,10 +432,7 @@ public class AggregatedImage extends MonolithicImage
implements Disposable {
updatedSourceTiles = null;
}
if (tile == null || sourcesToScan != null) {
- if (!hasAddedListeners) {
- hasAddedListeners = true;
- registerSourceListeners();
- }
+ registerSourceListeners(); // Does nothing if already
registered.
BitSet dirtyTiles = null;
if (sourcesToScan != null) try {
dirtyTiles = findDirtyTiles(sourcesToScan);
@@ -585,7 +576,7 @@ public class AggregatedImage extends MonolithicImage
implements Disposable {
if (dirtyTile) {
final boolean tileExists = (tiles[tileIndex] != null);
if (updatedTiles.putIfAbsent(new Point(tileX, tileY),
tileExists) == null && tileExists) {
- fireTileUpdate(tileX, tileY, true);
+ AggregatedImage.this.fireTileUpdate(tileX, tileY, true);
}
}
return super.getWritableTile(tileX, tileY);
@@ -600,7 +591,7 @@ public class AggregatedImage extends MonolithicImage
implements Disposable {
for (final Map.Entry<Point, Boolean> entry :
updatedTiles.entrySet()) {
if (entry.getValue()) {
final Point tile = entry.getKey();
- fireTileUpdate(tile.x, tile.y, false);
+ AggregatedImage.this.fireTileUpdate(tile.x, tile.y, false);
}
}
updatedTiles.clear();
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AnnotatedImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AnnotatedImage.java
index 2165cd121c..2c66657c9d 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AnnotatedImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/AnnotatedImage.java
@@ -57,7 +57,7 @@ import org.apache.sis.util.internal.shared.Strings;
*
* @author Martin Desruisseaux (Geomatys)
*/
-abstract class AnnotatedImage extends ImageAdapter {
+abstract class AnnotatedImage extends TileForwardingImage {
/**
* The suffix to add to property name for errors that occurred during
computation.
* A property with suffix is automatically created if an exception is
thrown during
@@ -237,12 +237,12 @@ abstract class AnnotatedImage extends ImageAdapter {
* cache is shared by all images using the same data. This is okay if
calculation depends
* only on sample value, not on other data.
*/
- while (source instanceof ImageAdapter) {
+ while (source instanceof TileForwardingImage) {
if (source instanceof AnnotatedImage) {
cache = ((AnnotatedImage) source).cache; // Cache for
the source of the source.
return;
}
- source = ((ImageAdapter) source).source;
+ source = ((TileForwardingImage) source).source;
}
synchronized (CACHE) {
cache = CACHE.computeIfAbsent(source, (k) -> new Cache<>(8, 200,
false));
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandAggregateImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandAggregateImage.java
index 347cc69ab2..c3381c357b 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandAggregateImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandAggregateImage.java
@@ -75,8 +75,8 @@ class BandAggregateImage extends MultiSourceImage {
static void unwrap(final BandAggregateArgument<RenderedImage>.Unwrapper
unwrapper) {
RenderedImage source = unwrapper.source;
int[] bands = unwrapper.bands;
- while (source instanceof ImageAdapter) {
- source = ((ImageAdapter) source).source;
+ while (source instanceof TileForwardingImage) {
+ source = ((TileForwardingImage) source).source;
}
if (source instanceof BandSelectImage) {
final var select = (BandSelectImage) source;
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandedSampleConverter.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandedSampleConverter.java
index 8a4270ad36..c67bdd55d4 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandedSampleConverter.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandedSampleConverter.java
@@ -18,6 +18,7 @@ package org.apache.sis.image;
import java.util.List;
import java.util.Arrays;
+import java.util.Vector;
import java.util.Objects;
import java.awt.Rectangle;
import java.awt.image.Raster;
@@ -37,6 +38,7 @@ import org.apache.sis.image.internal.shared.ImageUtilities;
import org.apache.sis.image.internal.shared.TileOpExecutor;
import org.apache.sis.image.internal.shared.ColorScaleBuilder;
import org.apache.sis.util.Disposable;
+import org.apache.sis.util.ComparisonMode;
import org.apache.sis.util.logging.Logging;
import org.apache.sis.math.DecimalFunctions;
import org.apache.sis.math.NumberType;
@@ -100,167 +102,308 @@ class BandedSampleConverter extends
WritableComputedImage {
private final List<SampleDimension> sampleDimensions;
/**
- * The sample resolutions, or {@code null} if unknown.
+ * The resolution of sample values, or {@code null} if unknown.
*/
private final double[] sampleResolutions;
/**
* Creates a new image which will compute values using the given
converters.
*
- * @param source the image for which to convert sample values.
- * @param sampleModel the sample model shared by all tiles in this image.
- * @param colorModel the color model for the expected range of values,
or {@code null}.
- * @param ranges the expected range of values for each band, or
{@code null} if unknown.
- * @param converters the transfer functions to apply on each band of
the source image.
- * If this array was a user-provided parameter,
should be cloned by caller.
- * @param sampleDimensions description of conversion result, or {@code
null} if unknown.
+ * @param builder contains all parameters for the image to construct.
*/
- private BandedSampleConverter(final RenderedImage source,
- final BandedSampleModel sampleModel,
- final ColorModel colorModel,
- final NumberRange<?>[] ranges,
- final MathTransform1D[] converters,
- final List<SampleDimension> sampleDimensions)
- {
- super(sampleModel, source);
- this.colorModel = colorModel;
- this.converters = converters;
- this.sampleDimensions = sampleDimensions;
+ private BandedSampleConverter(final Builder builder) {
+ super(builder.sampleModel, builder.source);
+ colorModel = builder.colorModel;
+ converters = builder.converters;
+ sampleDimensions = builder.sampleDimensions;
+ sampleResolutions = builder.resolution();
ensureCompatible(sampleModel, colorModel);
- /*
- * Get an estimation of the resolution, arbitrarily looking in the
middle of the range of values.
- * If the converters are linear (which is the most common case), the
middle value does not matter
- * except if it falls on a "no data" value.
+ }
+
+ /**
+ * Builder of {@link BandedSampleConverter} instances or instances of its
writable subclass.
+ * Using a builder is more convenient than processing arguments inside the
image constructor
+ * because it allows temporary storage of more information, modification
before final values,
+ * recursive invocation, and easier transfer from {@link Writable} class
to parent class.
+ *
+ * @see ImageProcessor#convert(RenderedImage, NumberRange[],
MathTransform1D[], DataType)
+ */
+ static final class Builder {
+ /**
+ * The image for which to convert sample values.
+ * The user-supplied image may be replaced by its source if this
change has no visible effect.
+ */
+ RenderedImage source;
+
+ /**
+ * The sample model shared by all tiles in the image.
+ */
+ final BandedSampleModel sampleModel;
+
+ /**
+ * The color model for the expected range of values, or {@code null}.
+ */
+ ColorModel colorModel;
+
+ /**
+ * The expected range of values for each band, or {@code null} if
unknown.
+ */
+ final NumberRange<?>[] sourceRanges;
+
+ /**
+ * The transfer functions to apply on each band of the source image.
+ * If this array was a user-provided parameter, should be cloned by
caller.
+ */
+ final MathTransform1D[] converters;
+
+ /**
+ * Inverses of {@link #converters}, or {@code nuull} if none or
unneeded or unavailable.
+ *
+ * @see #inverses()
*/
- boolean hasResolutions = false;
- final double[] resolutions = new double[converters.length];
- final Object sr = source.getProperty(SAMPLE_RESOLUTIONS_KEY);
- final int n = (sr != null &&
NumberType.isReal(sr.getClass().getComponentType())) ? Array.getLength(sr) : 0;
- for (int i=0; i<resolutions.length; i++) {
+ MathTransform1D[] inverses;
+
+ /**
+ * Whether the attempt to create {@link #inverses} is already done.
+ * If {@code true} and {@link #inverses} is still null, it means that
the inversion failed.
+ */
+ private boolean inverted;
+
+ /**
+ * Description of conversion result, or {@code null} if unknown.
+ */
+ final List<SampleDimension> sampleDimensions;
+
+ /**
+ * Prepares an image of the given data type which will compute values
using the given converters.
+ * The number of bands is the length of the {@code converters} array,
which must be greater than 0
+ * and not greater than the number of bands in the source image.
+ *
+ * @param source the image for which to convert sample values.
+ * @param layout object to use for computing tile size.
+ * @param sourceRanges the expected range of values for each band in
source image, or {@code null} if unknown.
+ * @param converters the transfer functions to apply on each band
of the source image.
+ * @param targetType the type of this image resulting from
conversion of given image.
+ * @param colorizer provider of color model for the expected
range of values, or {@code null}.
+ */
+ Builder(final RenderedImage source,
+ final ImageLayout layout,
+ final NumberRange<?>[] sourceRanges,
+ final MathTransform1D[] converters,
+ final DataType targetType,
+ final Colorizer colorizer)
+ {
+ this.source = source;
+ this.sourceRanges = sourceRanges;
+ this.converters = converters;
+ final int numBands = converters.length;
+ final int visibleBand;
/*
- * Get the sample value in the middle of the range of valid values
for the current band.
- * If no range was explicitly given, use the approximate average
of all possible values.
+ * Create the sample model and get the color model if it was
explicitly specified.
*/
- double middle = Double.NaN;
- if (ranges != null && i < ranges.length) {
- final NumberRange<?> range = ranges[i];
- if (range != null) {
- middle = range.getMedian();
- }
- }
- if (!Double.isFinite(middle)) {
- final SampleModel sm = source.getSampleModel();
- if (DataType.isUnsigned(sm)) {
- middle = Math.scalb(0.5, sm.getSampleSize(i));
- } else {
- middle = 0;
- }
+ sampleModel = layout.createBandedSampleModel(source, null,
targetType, numBands, 0);
+ sampleDimensions = SampleDimensions.IMAGE_PROCESSOR_ARGUMENT.get();
+ visibleBand = ImageUtilities.getVisibleBand(source);
+ colorModel = ColorScaleBuilder.NULL_COLOR_MODEL;
+ if (colorizer != null) {
+ var target = new Colorizer.Target(sampleModel,
sampleDimensions, visibleBand);
+ colorModel = colorizer.apply(target).orElse(null);
}
/*
- * Get the derivative in the middle value, which is constant
everywhere
- * in the common case of a linear transform.
+ * If no color model was specified or inferred from a colorizer,
search for the color model
+ * of another `BandedSampleConverter` doing the inverse
conversion. The intent is to retrieve
+ * the original color model in an (RGB) → (floating point values)
→ (resampling) → (RGB) chain.
+ * If we find no color model, default to grayscale for a range
inferred from the sample dimensions.
+ * If no sample dimension is specified, infer value range from the
data type.
*/
- final MathTransform1D c = converters[i];
- double r;
- try {
- r = c.derivative(middle);
- if (!Double.isFinite(r)) {
- r = c.derivative(1); // Second attempt if
the middle value didn't work.
+ if (colorModel == null && (colorModel =
searchColorModelInSources(source)) == null) {
+ SampleDimension sd = null;
+ if (sampleDimensions != null && visibleBand >= 0 &&
visibleBand < sampleDimensions.size()) {
+ sd = sampleDimensions.get(visibleBand);
+ }
+ final var builder = new
ColorScaleBuilder(ColorScaleBuilder.GRAYSCALE, null, false);
+ if (builder.initialize(source.getSampleModel(), sd) ||
+ builder.initialize(source.getColorModel()))
+ {
+ colorModel = builder.createColorModel(targetType,
numBands, Math.max(visibleBand, 0));
+ }
+ }
+ }
+
+ /**
+ * Searches for the color model of a source {@link
BandedSampleConverter} doing the inverse conversion.
+ * The use case is a "(RGB) → (floating point values) → (resampling) →
(RGB)" chain of image operations,
+ * in which case we want to retrieve the original color model. The
dependency tree of the first source
+ * is traversed before the dependency tree of the second source, which
is probably desirable considering
+ * that the first source is more likely to be the main source.
+ *
+ * @param image the image in which to scan the sources.
+ * @return the color model, or {@code null} if not found.
+ */
+ private ColorModel searchColorModelInSources(final RenderedImage
image) {
+ if (image instanceof BandedSampleConverter) {
+ final var other = (BandedSampleConverter) image;
+candidate: if (Arrays.equals(inverses(), other.converters)) {
+ // Additional check performed if available.
+ if (sampleDimensions != null && other.sampleDimensions !=
null) {
+ final int count = sampleDimensions.size();
+ if (count == other.sampleDimensions.size()) {
+ for (int i=0; i<count; i++) {
+ final SampleDimension s1 = this.
sampleDimensions.get(i);
+ final SampleDimension s2 =
other.sampleDimensions.get(i);
+ final boolean isConverted = (s1 ==
s1.forConvertedValues(true));
+ if
(!s1.equals(s2.forConvertedValues(isConverted),
ComparisonMode.IGNORE_METADATA)) {
+ break candidate;
+ }
+ }
+ }
+ }
+ return getCompatibleColorModel(other.getSource());
}
- } catch (TransformException e) {
- r = Double.NaN;
}
/*
- * The implicit source resolution is 1 on the assumption that we
are converting from
- * integer values. But if the source image specifies a resolution,
use the specified
- * value instead of the implicit 1 value.
+ * If the current image is not retained, search in its sources.
*/
- if (i < n) {
- final Number v = (Number) Array.get(sr, i);
- if (v != null) {
- double f = (v instanceof Float) ?
DecimalFunctions.floatToDouble(v.floatValue()) : v.doubleValue();
- if (f > 0) r *= f; // Ignore also NaN.
+ final Vector<RenderedImage> sources = image.getSources();
+ if (sources != null) {
+ for (final RenderedImage dependency : sources) {
+ ColorModel found = searchColorModelInSources(dependency);
+ if (found != null) {
+ return found;
+ }
}
}
- resolutions[i] = r;
- hasResolutions |= Double.isFinite(r);
+ return null;
}
- sampleResolutions = hasResolutions ? resolutions : null;
- }
- /**
- * Creates a new image of the given data type which will compute values
using the given converters.
- * The number of bands is the length of the {@code converters} array,
which must be greater than 0
- * and not greater than the number of bands in the source image.
- *
- * @param source the image for which to convert sample values.
- * @param layout object to use for computing tile size.
- * @param sourceRanges the expected range of values for each band in
source image, or {@code null} if unknown.
- * @param converters the transfer functions to apply on each band of
the source image.
- * @param targetType the type of this image resulting from conversion
of given image.
- * @param colorizer provider of color model for the expected range of
values, or {@code null}.
- * @return the image which compute converted values from the given source.
- *
- * @see ImageProcessor#convert(RenderedImage, NumberRange[],
MathTransform1D[], DataType)
- */
- static BandedSampleConverter create(RenderedImage source,
- final ImageLayout layout,
- final NumberRange<?>[] sourceRanges,
- final MathTransform1D[] converters,
- final DataType targetType,
- final Colorizer colorizer)
- {
- /*
- * Since this operation applies its own ColorModel anyway, skip
operation that was doing nothing else
- * than changing the color model. The new color model may be specified
by the user if (s)he provided
- * a `Colorizer` instance. Otherwise a default color model will be
inferred.
+ /**
+ * Returns the color model of the given image if it is compatible with
the image to create,
+ * or {@code null} otherwise.
+ *
+ * <p><b>Possible evolution:</b>
+ * If this method produces false negatives, a future version could
update the {@link #sampleModel}
+ * with the model of the given image resized to the width and height
of the current sample model.
+ * We would do that only if {@link ImageLayout#sampleModel} was null
(no user-supplied model).</p>
*/
- if (source instanceof RecoloredImage) {
- source = ((RecoloredImage) source).source;
- }
- final int numBands = converters.length;
- final BandedSampleModel sampleModel =
layout.createBandedSampleModel(source, null, targetType, numBands, 0);
- final List<SampleDimension> sampleDimensions =
SampleDimensions.IMAGE_PROCESSOR_ARGUMENT.get();
- final int visibleBand = ImageUtilities.getVisibleBand(source);
- ColorModel colorModel = ColorScaleBuilder.NULL_COLOR_MODEL;
- if (colorizer != null) {
- var target = new Colorizer.Target(sampleModel, sampleDimensions,
visibleBand);
- colorModel = colorizer.apply(target).orElse(null);
+ private ColorModel getCompatibleColorModel(final RenderedImage image) {
+ final ColorModel found = image.getColorModel();
+ if (found.isCompatibleSampleModel(sampleModel)) {
+ return found;
+ }
+ return null;
}
- if (colorModel == null) {
- /*
- * If no color model was specified or inferred from a colorizer,
- * default to grayscale for a range inferred from the sample
dimension.
- * If no sample dimension is specified, infer value range from
data type.
- */
- SampleDimension sd = null;
- if (sampleDimensions != null && visibleBand >= 0 && visibleBand <
sampleDimensions.size()) {
- sd = sampleDimensions.get(visibleBand);
+
+ /**
+ * Gets an estimation of the resolution of sample values. This method
arbitrarily looks in the
+ * middle of the range of values. If the converters are linear (which
is the most common case),
+ * the middle value does not matter except if it falls on a "no data"
value.
+ *
+ * @return the resolution of sample values, or {@code null} if unknown.
+ */
+ final double[] resolution() {
+ boolean hasResolutions = false;
+ final double[] resolutions = new double[converters.length];
+ final Object sr = source.getProperty(SAMPLE_RESOLUTIONS_KEY);
+ final int n = (sr != null &&
NumberType.isReal(sr.getClass().getComponentType())) ? Array.getLength(sr) : 0;
+ for (int i=0; i<resolutions.length; i++) {
+ /*
+ * Get the sample value in the middle of the range of valid
values for the current band.
+ * If no range was explicitly given, use the approximate
average of all possible values.
+ */
+ double middle = Double.NaN;
+ if (sourceRanges != null && i < sourceRanges.length) {
+ final NumberRange<?> range = sourceRanges[i];
+ if (range != null) {
+ middle = range.getMedian();
+ }
+ }
+ if (!Double.isFinite(middle)) {
+ final SampleModel sm = source.getSampleModel();
+ if (DataType.isUnsigned(sm)) {
+ middle = Math.scalb(0.5, sm.getSampleSize(i));
+ } else {
+ middle = 0;
+ }
+ }
+ /*
+ * Get the derivative in the middle value, which is constant
everywhere
+ * in the common case of a linear transform.
+ */
+ final MathTransform1D c = converters[i];
+ double r;
+ try {
+ r = c.derivative(middle);
+ if (!Double.isFinite(r)) {
+ r = c.derivative(1); // Second attempt
if the middle value didn't work.
+ }
+ } catch (TransformException e) {
+ r = Double.NaN;
+ }
+ /*
+ * The implicit source resolution is 1 on the assumption that
we are converting from
+ * integer values. But if the source image specifies a
resolution, use the specified
+ * value instead of the implicit 1 value.
+ */
+ if (i < n) {
+ final Number v = (Number) Array.get(sr, i);
+ if (v != null) {
+ double f = (v instanceof Float) ?
DecimalFunctions.floatToDouble(v.floatValue()) : v.doubleValue();
+ if (f > 0) r *= f; // Ignore also NaN.
+ }
+ }
+ resolutions[i] = r;
+ hasResolutions |= Double.isFinite(r);
}
- final var builder = new
ColorScaleBuilder(ColorScaleBuilder.GRAYSCALE, null, false);
- if (builder.initialize(source.getSampleModel(), sd) ||
- builder.initialize(source.getColorModel()))
- {
- colorModel = builder.createColorModel(targetType, numBands,
Math.max(visibleBand, 0));
+ return hasResolutions ? resolutions : null;
+ }
+
+ /**
+ * Returns the inverse of the converters, or {@code null} if none.
+ * This method returns the internal cache, do not modify the array.
+ *
+ * @return the inverse of the converters in a cached array, or {@code
null} if none.
+ */
+ private MathTransform1D[] inverses() {
+ @SuppressWarnings("LocalVariableHidesMemberVariable")
+ MathTransform1D[] inverses = this.inverses;
+ if (inverses == null && !inverted) {
+ inverses = new MathTransform1D[converters.length];
+ try {
+ for (int i=0; i<inverses.length; i++) {
+ inverses[i] = converters[i].inverse();
+ }
+ this.inverses = inverses; // Cache only if successful.
+ } catch (NoninvertibleTransformException e) {
+ Logging.recoverableException(LOGGER, ImageProcessor.class,
"convert", e);
+ }
+ inverted = true;
}
+ return inverses;
}
- /*
- * If the source image is writable, then change in the converted image
may be retro-propagated
- * to that source image. If we fail to compute the required inverse
transforms, log a notice at
- * a low level because this is not a serious problem; writable
BandedSampleConverter is a plus
- * but not a requirement.
+
+ /**
+ * Creates the converted image.
+ * Since this operation applies its own {@link ColorModel} anyway, the
{@linkplain #source}
+ * will skip operations that was doing nothing else than changing the
color model.
+ * The new color model may be specified by the user if (s)he provided
a {@link Colorizer} instance.
+ * Otherwise, a default color model has been inferred.
+ *
+ * <p>If the source image is writable, then change in the converted
image may be retro-propagated
+ * to that source image. If we fail to compute the required inverse
transforms, a notice is logged
+ * at a low level because this is not a serious problem: writable
{@link BandedSampleConverter} is
+ * a plus but not a requirement.</p>
+ *
+ * @return the image which compute converted values from the source
given at construction time.
*/
- if (source instanceof WritableRenderedImage) try {
- final MathTransform1D[] inverses = new MathTransform1D[numBands];
- for (int i=0; i<numBands; i++) {
- inverses[i] = converters[i].inverse();
+ final RenderedImage create() {
+ if (source instanceof RecoloredImage) {
+ source = ((RecoloredImage) source).source;
}
- return new Writable((WritableRenderedImage) source, sampleModel,
colorModel,
- sourceRanges, converters, inverses,
sampleDimensions);
- } catch (NoninvertibleTransformException e) {
- Logging.recoverableException(LOGGER, ImageProcessor.class,
"convert", e);
+ if (source instanceof WritableRenderedImage && inverses() != null)
{
+ return new Writable(this);
+ }
+ return new BandedSampleConverter(this);
}
- return new BandedSampleConverter(source, sampleModel, colorModel,
sourceRanges, converters, sampleDimensions);
}
/**
@@ -432,16 +575,9 @@ class BandedSampleConverter extends WritableComputedImage {
/**
* Creates a new writable image which will compute values using the
given converters.
*/
- Writable(final WritableRenderedImage source,
- final BandedSampleModel sampleModel,
- final ColorModel colorModel,
- final NumberRange<?>[] ranges,
- final MathTransform1D[] converters,
- final MathTransform1D[] inverses,
- final List<SampleDimension> sampleDimensions)
- {
- super(source, sampleModel, colorModel, ranges, converters,
sampleDimensions);
- this.inverses = inverses;
+ Writable(final Builder builder) {
+ super(builder);
+ this.inverses = builder.inverses;
}
/**
@@ -509,6 +645,7 @@ class BandedSampleConverter extends WritableComputedImage {
final var other = (BandedSampleConverter) object;
return Arrays .equals(converters, other.converters) &&
Objects.equals(colorModel, other.colorModel) &&
+ Objects.equals(sampleDimensions, other.sampleDimensions) &&
Arrays .equals(sampleResolutions, other.sampleResolutions);
}
return false;
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedImage.java
index 7a479b5f6a..f99b64d118 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedImage.java
@@ -41,7 +41,7 @@ import org.apache.sis.util.resources.Errors;
import org.apache.sis.coverage.grid.GridExtent; // For javadoc
import org.apache.sis.feature.internal.Resources;
import org.apache.sis.image.internal.shared.ImageUtilities;
-import org.apache.sis.image.internal.shared.WritableUntiledImage;
+import org.apache.sis.system.Modules;
/**
@@ -211,20 +211,6 @@ public abstract class ComputedImage extends PlanarImage
implements Disposable {
*/
protected final SampleModel sampleModel;
- /**
- * The observers, or {@code null} if none. This is a copy-on-write array:
- * values are never modified after construction (new arrays are created).
- *
- * This field is declared volatile because it is read without
synchronization by
- * {@link #markTileWritable(int, int, boolean)}. Since this is a
copy-on-write array,
- * it is okay to omit synchronization for that method but we still need
the memory effect.
- *
- * @see #addTileObserver(TileObserver)
- * @see #removeTileObserver(TileObserver)
- */
- @SuppressWarnings("VolatileArrayField")
- private volatile TileObserver[] observers;
-
/**
* Creates an initially empty image with the given sample model.
* The default tile size will be the width and height of the given sample
model
@@ -257,6 +243,23 @@ public abstract class ComputedImage extends PlanarImage
implements Disposable {
return reference;
}
+ /**
+ * Returns whether this image may notify its observers about tile updates.
+ * A value of {@code false} means that this image will not be notified
about changes in its source,
+ * therefore this image will not forward tile update events, therefore
observers registered on this
+ * class can be ignored in order to reduce the risk of memory leaks
(listeners can be other images).
+ * In case of doubt (implementations that we do not control),
conservatively returns {@code true}.
+ *
+ * <p>This method is ignored if this image implements the {@link
WritableRenderedImage} interface.
+ * In such case, this method may return {@code false} even if tile update
events are expected.</p>
+ *
+ * @return whether tile update events may occur.
+ */
+ @Override
+ final boolean mayFireTileUpdates() {
+ return reference.mayFireTileUpdates() ||
!getClass().getName().startsWith(Modules.CLASSNAME_PREFIX);
+ }
+
/**
* Sets an existing image where to write the computation result. The
sample model of specified image shall
* be equal to {@link #sampleModel} and the tile indices & pixel
coordinate systems shall be aligned.
@@ -770,59 +773,6 @@ public abstract class ComputedImage extends PlanarImage
implements Disposable {
Math.addExact(tiles.y, tiles.height - 1));
}
- /**
- * Adds an observer to be notified when a tile is about to be modified.
- * A tile can be modified directly if this image implements the {@link
WritableRenderedImage} interface
- * and a tile has been acquired for writing, or indirectly if this image
is computed from other sources
- * and one of the source images changed. In the latter case, the given
listener should be an instance of
- * {@link Observer} in order to be notified even if this image is not a
{@link WritableRenderedImage},
- *
- * @param observer the observer to notify, ignored if {@code null}.
- * If already present, it will receive multiple notifications.
- *
- * @see WritableRenderedImage#addTileObserver(TileObserver)
- * @see Observer
- *
- * @since SIS 1.8
- */
- @Override
- public synchronized void addTileObserver(final TileObserver observer) {
- if (observer instanceof Observer || this instanceof
WritableRenderedImage) {
- observers = WritableUntiledImage.addTileObserver(observers,
observer);
- }
- }
-
- /**
- * Removes an observer from the list of observers notified when a tile is
modified.
- * If the observer was not registered, nothing happens.
- * If the observer was registered for multiple notifications, it will now
be registered for one fewer.
- *
- * <p>The default implementation does nothing except ensuring that the
argument is non-null.
- * This method is overridden by subclasses such as {@link ComputedImage},
{@link AggregatedImage}
- * and all writable images.</p>
- *
- * @param observer the observer to stop notifying.
- *
- * @see WritableRenderedImage#removeTileObserver(TileObserver)
- *
- * @since SIS 1.8
- */
- @Override
- public synchronized void removeTileObserver(final TileObserver observer) {
- observers = WritableUntiledImage.removeTileObserver(observers,
observer);
- }
-
- /**
- * Notifies listeners that a tile is about to be modified or has been
modified.
- *
- * @param tileX the <var>x</var> index of the tile to acquire or
release.
- * @param tileY the <var>y</var> index of the tile to acquire or
release.
- * @param writing {@code true} if the tile will be modified, or {@code
false} if the modification is done.
- */
- private void fireTileUpdate(final int tileX, final int tileY, final
boolean writing) {
- fireTileUpdate(observers, this, tileX, tileY, writing);
- }
-
/**
* Invoked when a tile of a source image has been updated. This method
should {@linkplain #markDirtyTiles
* mark as dirty} all tiles of this {@code ComputedImage} that depend on
the updated tile.
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedTiles.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedTiles.java
index 225dbdd6d4..2bc85ff9c9 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedTiles.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ComputedTiles.java
@@ -19,19 +19,16 @@ package org.apache.sis.image;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
-import java.util.Arrays;
import java.lang.ref.WeakReference;
import java.lang.reflect.UndeclaredThrowableException;
import java.awt.Point;
import java.awt.Rectangle;
-import java.awt.image.TileObserver;
import java.awt.image.RenderedImage;
import java.awt.image.ImagingOpException;
import org.apache.sis.feature.internal.Resources;
import org.apache.sis.system.ReferenceQueueConsumer;
-import org.apache.sis.image.internal.shared.ImageUtilities;
+import org.apache.sis.util.ArraysExt;
import org.apache.sis.util.Disposable;
-import org.apache.sis.util.logging.Logging;
/**
@@ -92,17 +89,16 @@ final class ComputedTiles extends
WeakReference<ComputedImage> implements Dispos
super(image, ReferenceQueueConsumer.QUEUE);
cachedTiles = new HashMap<>();
if (ws != null) {
- sources = ws;
ws = ws.clone();
int count = 0;
try {
for (final RenderedImage source : ws) {
- if (PlanarImage.addTileObserver(source, this) &&
!listenerWasIgnored(source)) {
+ if (PlanarImage.addTileObserver(source, this)) {
ws[count++] = source;
}
}
- if (count != ws.length) {
- sources = Arrays.copyOf(ws, count);
+ if (count != 0) {
+ sources = ArraysExt.resize(ws, count);
}
} catch (Throwable e) {
unregister(ws, count + 1, e); // `unregister(…)` will
rethrow the given exception.
@@ -111,25 +107,13 @@ final class ComputedTiles extends
WeakReference<ComputedImage> implements Dispos
}
/**
- * Returns whether the given image has ignored the listener.
- * This is used for avoiding to keep unnecessary references to source
images in this class,
- * for reducing the risk of memory leak (images may potentially hold large
amount of memory).
+ * Returns whether at least one observer has been registered.
+ * If no listener has been registered, no tile update events will occur.
*
- * <p>This method uses reflection with the knowledge that the default
implementation
- * of {@link PlanarImage#addTileObserver(TileObserver)} does nothing. If
this method
- * has not been overridden, the listener has been ignored.</p>
- *
- * @param image the image where a listener has been added.
- * @return whether the image has ignored the listener (determined by
reflection.
+ * @see ComputedImage#mayFireTileUpdates()
*/
- private static boolean listenerWasIgnored(final RenderedImage image) {
- if (image instanceof PlanarImage) try {
- return image.getClass().getMethod("addTileObserver",
TileObserver.class).getDeclaringClass() == PlanarImage.class;
- } catch (ReflectiveOperationException e) {
- // Should never happen. If happen anyway, conservatively assume
that the listener is not ignored.
- Logging.unexpectedException(ImageUtilities.LOGGER,
PlanarImage.class, "addTileObserver", e);
- }
- return false;
+ final boolean mayFireTileUpdates() {
+ return sources != null;
}
/**
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageAdapter.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageAdapter.java
index ad308f8b47..c9b6f4eb92 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageAdapter.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageAdapter.java
@@ -19,30 +19,20 @@ package org.apache.sis.image;
import java.util.Objects;
import java.util.Vector;
import java.awt.Image;
-import java.awt.Rectangle;
import java.awt.image.ColorModel;
import java.awt.image.SampleModel;
import java.awt.image.RenderedImage;
-import java.awt.image.Raster;
-import java.awt.image.WritableRaster;
-import org.apache.sis.util.Disposable;
+import java.awt.image.TileObserver;
+import java.lang.ref.WeakReference;
/**
- * An image which wraps an existing image unchanged, except for properties
and/or color model.
- * All {@link RenderedImage} methods related to coordinate systems (pixel
coordinates or tile
- * indices), and all methods fetching tiles, delegate to the wrapped image.
+ * An image which wraps an existing image and keep the same pixel coordinate
systems and tile indices.
+ * All {@link RenderedImage} methods related to coordinate systems (pixel
coordinates or tile indices)
+ * delegate to the wrapped image.
+ * This class is similar to {@link SourceAlignedImage} except that it does not
extend {@link ComputedImage}.
*
- * <h2>Design note</h2>
- * Most non-abstract methods are final because {@link PixelIterator} (among
others) relies
- * on the fact that it can unwrap this image and still get the same pixel
values.
- *
- * <h2>Relationship with other classes</h2>
- * This class is similar to {@link SourceAlignedImage} except that it does not
extend {@link ComputedImage}
- * and forwards {@link #getTile(int, int)}, {@link #getData()} and other data
methods to the source image.
- *
- * <h2>Requirements for subclasses</h2>
- * All subclasses shall override {@link #equals(Object)} and {@link
#hashCode()}.
+ * <p>All subclasses shall override {@link #equals(Object)} and {@link
#hashCode()}.</p>
*
* @author Martin Desruisseaux (Geomatys)
*/
@@ -52,6 +42,13 @@ abstract class ImageAdapter extends PlanarImage {
*/
protected final RenderedImage source;
+ /**
+ * The listener registered on source image, or {@code null} if none.
+ * This listener use weak reference, therefore it should not cause
+ * retention of large amount of memory.
+ */
+ private TileObserver sourceListener;
+
/**
* Creates a new wrapper for the given image.
*
@@ -104,40 +101,79 @@ abstract class ImageAdapter extends PlanarImage {
return source.getColorModel();
}
+ /**
+ * Returns the sample model of this image.
+ */
+ @Override
+ public final SampleModel getSampleModel() {
+ return source.getSampleModel();
+ }
+
/** Delegates to the wrapped image. */
- @Override public final SampleModel getSampleModel() {return
source.getSampleModel();}
- @Override public final int getWidth() {return
source.getWidth();}
- @Override public final int getHeight() {return
source.getHeight();}
- @Override public final int getMinX() {return
source.getMinX();}
- @Override public final int getMinY() {return
source.getMinY();}
- @Override public final int getNumXTiles() {return
source.getNumXTiles();}
- @Override public final int getNumYTiles() {return
source.getNumYTiles();}
- @Override public final int getMinTileX() {return
source.getMinTileX();}
- @Override public final int getMinTileY() {return
source.getMinTileY();}
- @Override public final int getTileWidth() {return
source.getTileWidth();}
- @Override public final int getTileHeight() {return
source.getTileHeight();}
- @Override public final int getTileGridXOffset() {return
source.getTileGridXOffset();}
- @Override public final int getTileGridYOffset() {return
source.getTileGridYOffset();}
- @Override public final Raster getTile(int tx, int ty) {return
source.getTile(tx, ty);}
- @Override public final Raster getData() {return
source.getData();}
- @Override public final Raster getData(Rectangle region) {return
source.getData(region);}
- @Override public final WritableRaster copyData(WritableRaster r) {return
source.copyData(r);}
+ @Override public final int getWidth() {return source.getWidth();}
+ @Override public final int getHeight() {return
source.getHeight();}
+ @Override public final int getMinX() {return source.getMinX();}
+ @Override public final int getMinY() {return source.getMinY();}
+ @Override public final int getNumXTiles() {return
source.getNumXTiles();}
+ @Override public final int getNumYTiles() {return
source.getNumYTiles();}
+ @Override public final int getMinTileX() {return
source.getMinTileX();}
+ @Override public final int getMinTileY() {return
source.getMinTileY();}
+ @Override public final int getTileWidth() {return
source.getTileWidth();}
+ @Override public final int getTileHeight() {return
source.getTileHeight();}
+ @Override public final int getTileGridXOffset() {return
source.getTileGridXOffset();}
+ @Override public final int getTileGridYOffset() {return
source.getTileGridYOffset();}
/**
- * Notifies the source image that tiles will be computed soon in the given
region.
- * If the source image is an instance of {@link PlanarImage}, then this
method
- * forwards the notification to it. Otherwise default implementation does
nothing.
+ * Returns whether this image may notify its observers about tile updates.
+ * A value of {@code false} means that this image will not be notified
about changes in its source,
+ * therefore this image will not forward tile update events, therefore
observers registered on this
+ * class can be ignored in order to reduce the risk of memory leaks
(listeners can be other images).
+ * In case of doubt (implementations that we do not control),
conservatively returns {@code true}.
+ *
+ * @return whether tile update events may occur.
*/
@Override
- protected Disposable prefetch(final Rectangle tiles) {
- if (source instanceof PlanarImage) {
- /*
- * Forwarding directly is possible because the contract
- * of this class said that tile indices must be the same.
- */
- return ((PlanarImage) source).prefetch(tiles);
- } else {
- return super.prefetch(tiles);
+ final boolean mayFireTileUpdates() {
+ assert Thread.holdsLock(this);
+ if (sourceListener == null) {
+ final var listener = new Listener(this);
+ if (addTileObserver(source, listener)) {
+ sourceListener = listener;
+ }
+ }
+ return sourceListener != null;
+ }
+
+ /**
+ * A listener using weak reference for notifying the enclosed image that a
source changed.
+ */
+ private static final class Listener extends WeakReference<ImageAdapter>
implements Observer {
+ /**
+ * Creates a new listener which will notify the given image.
+ *
+ * @param target the image to notify when a source changed.
+ */
+ Listener(final ImageAdapter target) {
+ super(target);
+ }
+
+ /**
+ * Invoked when a source image changed.
+ * The enclosed image is notified only after the tile calculation
finished.
+ *
+ * @param source the image that owns the updated tile.
+ * @param tileX the <var>x</var> index of the tile that is being
updated.
+ * @param tileY the <var>y</var> index of the tile that is being
updated.
+ * @param writing {@code true} before writing, {@code false} after
update.
+ */
+ @Override
+ public void tileUpdate(final RenderedImage source, final int tileX,
final int tileY, final boolean writing) {
+ final ImageAdapter target = get();
+ if (target != null) {
+ target.fireTileUpdate(tileX, tileY, writing);
+ } else {
+ removeTileObserver(source, this);
+ }
}
}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java
index 1aa2bf0dcb..e110ea610e 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ImageProcessor.java
@@ -1142,7 +1142,7 @@ public class ImageProcessor implements Cloneable {
colorizer = this.colorizer;
}
// No need to clone `sourceRanges` because it is not stored by
`BandedSampleConverter`.
- return unique(BandedSampleConverter.create(source, layout,
sourceRanges, converters, targetType, colorizer));
+ return unique(new BandedSampleConverter.Builder(source, layout,
sourceRanges, converters, targetType, colorizer).create());
}
/**
@@ -1211,8 +1211,8 @@ public class ImageProcessor implements Cloneable {
break;
}
if (Objects.equals(sm, source.getSampleModel())) {
- if (source instanceof ImageAdapter) {
- source = ((ImageAdapter) source).source;
+ if (source instanceof TileForwardingImage) {
+ source = ((TileForwardingImage) source).source;
continue;
}
if (source instanceof ResampledImage) {
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/MonolithicImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/MonolithicImage.java
index 44819ee034..74caa63173 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/MonolithicImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/MonolithicImage.java
@@ -19,8 +19,6 @@ package org.apache.sis.image;
import java.lang.ref.WeakReference;
import java.awt.image.TileObserver;
import java.awt.image.RenderedImage;
-import java.awt.image.WritableRenderedImage;
-import org.apache.sis.image.internal.shared.WritableUntiledImage;
/**
@@ -31,20 +29,6 @@ import
org.apache.sis.image.internal.shared.WritableUntiledImage;
* @author Martin Desruisseaux (Geomatys)
*/
abstract class MonolithicImage extends PlanarImage {
- /**
- * The observers, or {@code null} if none. This is a copy-on-write array:
- * values are never modified after construction (new arrays are created).
- *
- * This field is declared volatile because it is read without
synchronization by
- * {@link #markTileWritable(int, int, boolean)}. Since this is a
copy-on-write array,
- * it is okay to omit synchronization for that method but we still need
the memory effect.
- *
- * @see #addTileObserver(TileObserver)
- * @see #removeTileObserver(TileObserver)
- */
- @SuppressWarnings("VolatileArrayField")
- private volatile TileObserver[] observers;
-
/**
* The common listener registered on all source images, or {@code null} if
none.
* This listener use weak reference, therefore it should not cause
retention of
@@ -52,12 +36,33 @@ abstract class MonolithicImage extends PlanarImage {
*/
private TileObserver sourceListener;
+ /**
+ * Whether a listener to writable images has been registered.
+ * This is done only when first needed and uses weak reference.
+ */
+ private boolean hasAddedListeners;
+
/**
* Creates a new monolithic image.
*/
MonolithicImage() {
}
+ /**
+ * Returns whether this image may notify its observers about tile updates.
+ * A value of {@code false} means that this image will not be notified
about changes in its source,
+ * therefore this image will not forward tile update events, therefore
observers registered on this
+ * class can be ignored in order to reduce the risk of memory leaks
(listeners can be other images).
+ * In case of doubt (implementations that we do not control),
conservatively returns {@code true}.
+ *
+ * @return whether tile update events may occur.
+ */
+ @Override
+ final boolean mayFireTileUpdates() {
+ registerSourceListeners(); // Does nothing if already registered.
+ return sourceListener != null;
+ }
+
/**
* Returns all source images as an array.
*
@@ -67,9 +72,15 @@ abstract class MonolithicImage extends PlanarImage {
/**
* Adds a listener by weak reference to all images that are writable or
planar.
+ * If a listener has already been added, then this method does nothing.
* This method should be invoked in a synchronized block.
*/
final void registerSourceListeners() {
+ assert Thread.holdsLock(this);
+ if (hasAddedListeners) {
+ return;
+ }
+ hasAddedListeners = true; // Set first for making only one
attempt in case of failure.
boolean registered = false;
TileObserver listener = sourceListener;
try {
@@ -91,6 +102,7 @@ abstract class MonolithicImage extends PlanarImage {
* This method should be invoked in a synchronized block.
*/
final void unregisterSourceListeners() {
+ assert Thread.holdsLock(this);
if (sourceListener != null) {
for (final RenderedImage source : getSourceImages()) {
removeTileObserver(source, sourceListener);
@@ -102,7 +114,7 @@ abstract class MonolithicImage extends PlanarImage {
/**
* A listener using weak reference for notifying the enclosed image that a
source changed.
*/
- private static final class Listener extends WeakReference<MonolithicImage>
implements PlanarImage.Observer {
+ private static final class Listener extends WeakReference<MonolithicImage>
implements Observer {
/**
* Creates a new listener which will notify the given image.
*
@@ -147,43 +159,4 @@ abstract class MonolithicImage extends PlanarImage {
* @see ComputedImage#sourceTileChanged(RenderedImage, int, int)
*/
protected abstract void sourceTileChanged(RenderedImage source, int tileX,
int tileY);
-
- /**
- * Adds an observer to be notified when a tile is about to be modified.
- * A tile can be modified indirectly if one of the source images changed.
- * The given listener should be an instance of {@link Observer} in order
- * to be notified even if this image is not a {@link
WritableRenderedImage}.
- *
- * @param observer the observer to notify, ignored if {@code null}.
- * If already present, it will receive multiple notifications.
- */
- @Override
- public synchronized void addTileObserver(final TileObserver observer) {
- if (observer instanceof Observer || this instanceof
WritableRenderedImage) {
- observers = WritableUntiledImage.addTileObserver(observers,
observer);
- }
- }
-
- /**
- * Removes an observer from the list of observers notified when a tile is
modified.
- * If the observer was not registered, nothing happens.
- * If the observer was registered for multiple notifications, it will now
be registered for one fewer.
- *
- * @param observer the observer to stop notifying.
- */
- @Override
- public synchronized void removeTileObserver(final TileObserver observer) {
- observers = WritableUntiledImage.removeTileObserver(observers,
observer);
- }
-
- /**
- * Notifies listeners that a tile is about to be modified or has been
modified.
- *
- * @param tileX the <var>x</var> index of the tile to acquire or
release.
- * @param tileY the <var>y</var> index of the tile to acquire or
release.
- * @param writing {@code true} if the tile will be modified, or {@code
false} if the modification is done.
- */
- final void fireTileUpdate(final int tileX, final int tileY, final boolean
writing) {
- fireTileUpdate(observers, this, tileX, tileY, writing);
- }
}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PixelIterator.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PixelIterator.java
index 4e7e6952c8..97d9260192 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PixelIterator.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PixelIterator.java
@@ -385,8 +385,8 @@ public class PixelIterator {
* also necessary for allowing the builder to recognize the {@link
BufferedImage} case.
*/
private static RenderedImage unwrap(RenderedImage image) {
- while (image instanceof ImageAdapter) {
- image = ((ImageAdapter) image).source;
+ while (image instanceof TileForwardingImage) {
+ image = ((TileForwardingImage) image).source;
}
return image;
}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.java
index 3cfd5f477f..153bb6c39e 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PlanarImage.java
@@ -40,6 +40,7 @@ import org.apache.sis.image.internal.Summarizer;
import org.apache.sis.image.internal.shared.RasterFactory;
import org.apache.sis.image.internal.shared.ImageUtilities;
import org.apache.sis.image.internal.shared.TileOpExecutor;
+import org.apache.sis.image.internal.shared.WritableUntiledImage;
import org.apache.sis.feature.internal.Resources;
import org.apache.sis.pending.jdk.JDK18;
@@ -59,9 +60,8 @@ import org.apache.sis.pending.jdk.JDK18;
* We do not try to reproduce the full set of JAI functionalities here, but we
progressively
* reproduce some little bits of functionalities as they are needed by Apache
SIS.</div>
*
- * <p>This base class does not store any state,
- * but assumes that numbering of pixel coordinates and tile indices start at
zero.
- * Subclasses need to implement at least the following methods:</p>
+ * <p>The default method implementations are suitable for images with with a
numbering of pixel coordinates
+ * and tile indices starting at zero. Subclasses need to implement at least
the following methods:</p>
* <ul>
* <li>{@link #getWidth()} — the image width in pixels.</li>
* <li>{@link #getHeight()} — the image height in pixels.</li>
@@ -256,6 +256,20 @@ public abstract class PlanarImage implements RenderedImage
{
*/
public static final String MASK_KEY = "org.apache.sis.Mask";
+ /**
+ * The observers, or {@code null} if none. This is a copy-on-write array:
+ * values are never modified after construction (new arrays are created).
+ *
+ * This field is declared volatile because it is read without
synchronization by
+ * {@link #markTileWritable(int, int, boolean)}. Since this is a
copy-on-write array,
+ * it is okay to omit synchronization for that method but we still need
the memory effect.
+ *
+ * @see #addTileObserver(TileObserver)
+ * @see #removeTileObserver(TileObserver)
+ */
+ @SuppressWarnings("VolatileArrayField")
+ private volatile TileObserver[] observers;
+
/**
* Creates a new rendered image.
*/
@@ -682,8 +696,10 @@ public abstract class PlanarImage implements RenderedImage
{
* and one of the source images changed. In the latter case, the given
listener should be an instance of
* {@link Observer} in order to be notified even if this image is not a
{@link WritableRenderedImage}.
*
- * <p>The default implementation does nothing. This method is overridden
by subclasses
- * such as {@link ComputedImage}, {@link AggregatedImage} and all writable
images.</p>
+ * <p>This method can ignore the given observer if it will never be
notified about any update event.
+ * For example, if this image never emit update events, or if this image
is a read-only view but the
+ * given observer does not implement the {@link Observer} interface, then
the observer is ignored.
+ * The intent is to avoid unnecessary strong references for reducing the
risk of memory leaks.</p>
*
* @param observer the observer to notify, ignored if {@code null}.
* If already present, it will receive multiple notifications.
@@ -693,7 +709,13 @@ public abstract class PlanarImage implements RenderedImage
{
*
* @since SIS 1.8
*/
- public void addTileObserver(TileObserver observer) {
+ public synchronized void addTileObserver(final TileObserver observer) {
+ if (observer instanceof Observer || this instanceof
WritableRenderedImage) {
+ // Following can trig the registration of listeners on source
images.
+ if (mayFireTileUpdates()) {
+ observers = WritableUntiledImage.addTileObserver(observers,
observer);
+ }
+ }
}
/**
@@ -701,20 +723,74 @@ public abstract class PlanarImage implements
RenderedImage {
* If the observer was not registered, nothing happens.
* If the observer was registered for multiple notifications, it will now
be registered for one fewer.
*
- * <p>The default implementation does nothing. This method is overridden
by subclasses
- * such as {@link ComputedImage}, {@link AggregatedImage} and all writable
images.</p>
- *
* @param observer the observer to stop notifying. Ignored if {@code
null} or absent.
*
* @see WritableRenderedImage#removeTileObserver(TileObserver)
*
* @since SIS 1.8
*/
- public void removeTileObserver(TileObserver observer) {
+ public synchronized void removeTileObserver(final TileObserver observer) {
+ observers = WritableUntiledImage.removeTileObserver(observers,
observer);
+ }
+
+ /**
+ * Notifies all listeners that a tile is about to be modified or has been
modified.
+ * For each observer, one of the following methods is invoked, in
preference order:
+ *
+ * <ul>
+ * <li>{@link TileObserver#tileUpdate(WritableRenderedImage, int, int,
boolean)
+ * TileObserver.tileUpdate(WritableRenderedImage, …)} if this image
is writable.</li>
+ * <li>{@link Observer#tileUpdate(RenderedImage, int, int, boolean)
+ * PlanarImage.Observer.tileUpdate(RenderedImage, …)} if the
observer implements {@code Observer}.</li>
+ * <li>Otherwise, no method is invoked.</li>
+ * </ul>
+ *
+ * @param tileX the <var>x</var> index of the modified tile.
+ * @param tileY the <var>y</var> index of the modified tile.
+ * @param writing {@code true} if the tile will be modified, or {@code
false} if the modification is done.
+ *
+ * @since SIS 1.8
+ */
+ protected void fireTileUpdate(final int tileX, final int tileY, final
boolean writing) {
+ @SuppressWarnings("LocalVariableHidesMemberVariable")
+ final TileObserver[] observers = this.observers;
+ if (observers != null) {
+ if (this instanceof WritableRenderedImage) {
+ final var writable = (WritableRenderedImage) this;
+ for (final TileObserver observer : observers) {
+ observer.tileUpdate(writable, tileX, tileY, writing);
+ }
+ } else {
+ for (final TileObserver observer : observers) {
+ if (observer instanceof Observer) {
+ ((Observer) observer).tileUpdate(this, tileX, tileY,
writing);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Returns whether this image may notify its observers about tile updates.
+ * In case of doubt (implementations that we do not control),
conservatively returns {@code true}.
+ * A value of {@code false} does not necessarily means that the image
content will never change,
+ * but it means that this image will never be notified about such changes
and therefore it is not
+ * worth to keep references to observers.
+ *
+ * <p>This method is ignored if this image implements the {@link
WritableRenderedImage} interface.
+ * In such case, this method may return {@code false} even if tile update
events are expected.</p>
+ *
+ * @return whether tile update events may occur.
+ */
+ boolean mayFireTileUpdates() {
+ return true;
}
/**
* Adds an observer to the given image if possible.
+ * Returns {@code false} if the listener has been ignored.
+ * The return value can be used for avoiding to keep unnecessary
references to source images,
+ * for reducing the risk of memory leak (images may potentially hold large
amount of memory).
*
* @param image the image on which to add an observer.
* @param observer the observer to add.
@@ -722,11 +798,15 @@ public abstract class PlanarImage implements
RenderedImage {
*/
static boolean addTileObserver(final RenderedImage image, final
TileObserver observer) {
if (image instanceof PlanarImage) {
- ((PlanarImage) image).addTileObserver(observer);
+ final var t = (PlanarImage) image;
+ synchronized (t) {
+ final TileObserver[] observers = t.observers;
+ t.addTileObserver(observer);
+ return t.observers != observers;
+ }
} else if (image instanceof WritableRenderedImage) {
((WritableRenderedImage) image).addTileObserver(observer);
- } else {
- return false;
+ return true;
}
return false;
}
@@ -735,7 +815,7 @@ public abstract class PlanarImage implements RenderedImage {
* Removes an observer from the given image if present.
*
* @param image the image from which to remove an observer.
- * @param observer the observer to add.
+ * @param observer the observer to remove.
*/
static void removeTileObserver(final RenderedImage image, final
TileObserver observer) {
if (image instanceof PlanarImage) {
@@ -745,34 +825,6 @@ public abstract class PlanarImage implements RenderedImage
{
}
}
- /**
- * Notifies all listeners that the specified tile is about to change or
has changed.
- *
- * @param observers the observers to notify, or {@code null} if none.
- * @param image the image that owns the tile.
- * @param tileX the <var>x</var> index of the modified tile.
- * @param tileY the <var>y</var> index of the modified tile.
- * @param writing {@code true} if the tile will be modified, or {@code
false} if the modification is done.
- */
- static void fireTileUpdate(final TileObserver[] observers, final
RenderedImage image,
- final int tileX, final int tileY, final boolean
writing)
- {
- if (observers != null) {
- if (image instanceof WritableRenderedImage) {
- final var writable = (WritableRenderedImage) image;
- for (final TileObserver observer : observers) {
- observer.tileUpdate(writable, tileX, tileY, writing);
- }
- } else {
- for (final TileObserver observer : observers) {
- if (observer instanceof Observer) {
- ((Observer) observer).tileUpdate(image, tileX, tileY,
writing);
- }
- }
- }
- }
- }
-
/**
* An interface for objects that wish to be informed when an image is
about to change or has changed.
* This is an extension of {@link TileObserver} where the modified image
is not necessarily writable.
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PrefetchedImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PrefetchedImage.java
index b8b05b7b10..45b4282366 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PrefetchedImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/PrefetchedImage.java
@@ -16,12 +16,9 @@
*/
package org.apache.sis.image;
-import java.util.Vector;
import java.util.Objects;
import java.awt.Point;
import java.awt.Rectangle;
-import java.awt.image.ColorModel;
-import java.awt.image.SampleModel;
import java.awt.image.RenderedImage;
import java.awt.image.Raster;
import java.awt.image.RasterFormatException;
@@ -42,12 +39,7 @@ import org.apache.sis.util.resources.Errors;
*
* @see ImageProcessor#prefetch(RenderedImage, Rectangle)
*/
-final class PrefetchedImage extends PlanarImage implements
TileErrorHandler.Executor {
- /**
- * The source image from which to prefetch tiles.
- */
- final RenderedImage source;
-
+final class PrefetchedImage extends ImageAdapter implements
TileErrorHandler.Executor {
/**
* Index of the first prefetched tile. This index is determined from the
area of interest (AOI)
* specified at construction time; it is not necessarily the index of the
first tile in the image.
@@ -95,7 +87,7 @@ final class PrefetchedImage extends PlanarImage implements
TileErrorHandler.Exec
PrefetchedImage(final RenderedImage source, Rectangle areaOfInterest,
final ErrorHandler errorHandler, final boolean parallel)
{
- this.source = source;
+ super(source);
if (areaOfInterest != null) {
areaOfInterest = new Rectangle(areaOfInterest);
ImageUtilities.clipBounds(source, areaOfInterest);
@@ -188,43 +180,6 @@ final class PrefetchedImage extends PlanarImage implements
TileErrorHandler.Exec
return (numXTiles | numYTiles) == 0;
}
- /**
- * Returns the immediate source of image data for this image.
- */
- @Override
- @SuppressWarnings("UseOfObsoleteCollectionType")
- public Vector<RenderedImage> getSources() {
- final Vector<RenderedImage> sources = new Vector<>(1);
- sources.add(source);
- return sources;
- }
-
- /**
- * Gets a property from the source image.
- * All properties are inherited from the source with no change.
- */
- @Override
- public Object getProperty(final String name) {
- return source.getProperty(name);
- }
-
- /** Delegate to the source image. */
- @Override public String[] getPropertyNames() {return
source.getPropertyNames();}
- @Override public ColorModel getColorModel() {return
source.getColorModel();}
- @Override public SampleModel getSampleModel() {return
source.getSampleModel();}
- @Override public int getWidth() {return
source.getWidth();}
- @Override public int getHeight() {return
source.getHeight();}
- @Override public int getMinX() {return
source.getMinX();}
- @Override public int getMinY() {return
source.getMinY();}
- @Override public int getNumXTiles() {return
source.getNumXTiles();}
- @Override public int getNumYTiles() {return
source.getNumYTiles();}
- @Override public int getMinTileX() {return
source.getMinTileX();}
- @Override public int getMinTileY() {return
source.getMinTileY();}
- @Override public int getTileWidth() {return
source.getTileWidth();}
- @Override public int getTileHeight() {return
source.getTileHeight();}
- @Override public int getTileGridXOffset() {return
source.getTileGridXOffset();}
- @Override public int getTileGridYOffset() {return
source.getTileGridYOffset();}
-
/**
* Returns the tile at the given location in tile coordinates. If the
requested
* tile is in the region of prefetched tiles, that tile is returned
directly.
@@ -317,8 +272,8 @@ final class PrefetchedImage extends PlanarImage implements
TileErrorHandler.Exec
*/
@Override
public boolean equals(final Object object) {
- if (object instanceof PrefetchedImage) {
- final PrefetchedImage other = (PrefetchedImage) object;
+ if (super.equals(object)) {
+ final var other = (PrefetchedImage) object;
return source.equals(other.source) &&
minTileX == other.minTileX &&
minTileY == other.minTileY &&
@@ -327,4 +282,14 @@ final class PrefetchedImage extends PlanarImage implements
TileErrorHandler.Exec
}
return false;
}
+
+ /**
+ * Appends a content to show in the {@link #toString()} representation,
+ * after the class name and before the string representation of the
wrapped image.
+ */
+ @Override
+ final Class<PrefetchedImage> appendStringContent(final StringBuilder
buffer) {
+ buffer.append(numXTiles).append(" × ").append(numYTiles);
+ return PrefetchedImage.class;
+ }
}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/RecoloredImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/RecoloredImage.java
index 2df08ab920..27a77ca257 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/RecoloredImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/RecoloredImage.java
@@ -45,7 +45,7 @@ import org.apache.sis.measure.NumberRange;
*
* @author Martin Desruisseaux (Geomatys)
*/
-final class RecoloredImage extends ImageAdapter {
+final class RecoloredImage extends TileForwardingImage {
/**
* The color model to associate with this recolored image.
*
@@ -134,15 +134,15 @@ final class RecoloredImage extends ImageAdapter {
}
/*
* Find the image which contains the minimum and maximum values that
we want to keep.
- * We can skip `ImageAdapter` because those images may modify
properties but not sample values.
+ * We can skip `TileForwardingImage` because those images may modify
properties but not sample values.
*/
RecoloredImage expected = null;
- while (colored instanceof ImageAdapter) {
+ while (colored instanceof TileForwardingImage) {
if (colored instanceof RecoloredImage) {
expected = (RecoloredImage) colored;
break;
}
- colored = ((ImageAdapter) colored).source;
+ colored = ((TileForwardingImage) colored).source;
}
/*
* Verify if the given image, or one of its sources, has the expected
color model.
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ResampledImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ResampledImage.java
index be79cf01d4..5df1907fbb 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ResampledImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/ResampledImage.java
@@ -438,9 +438,9 @@ public class ResampledImage extends ComputedImage {
private synchronized RenderedImage getMask() {
ComputedImage image = (mask != null) ? mask.get() : null;
if (image == null) {
- mask = null; // Cleared first in case an error
occurs below.
+ mask = null; // Cleared first in case an error
occurs below.
image = new MaskImage(this);
- mask = image.reference();
+ mask = image.reference();
}
return image;
}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/TileForwardingImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/TileForwardingImage.java
new file mode 100644
index 0000000000..58f0c75bdf
--- /dev/null
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/TileForwardingImage.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.image;
+
+import java.awt.Rectangle;
+import java.awt.image.RenderedImage;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+import org.apache.sis.util.Disposable;
+
+
+/**
+ * An image which wraps an existing image unchanged, except for properties
and/or color model.
+ * All {@link RenderedImage} methods related to coordinate systems (pixel
coordinates or tile indices),
+ * and all methods fetching tiles, delegate to the wrapped image.
+ *
+ * Most non-abstract methods are final because {@link PixelIterator} (among
others)
+ * relies on the fact that it can unwrap this image and still get the same
pixel values.
+ *
+ * <p>All subclasses shall override {@link #equals(Object)} and {@link
#hashCode()}.</p>
+ *
+ * @author Martin Desruisseaux (Geomatys)
+ */
+abstract class TileForwardingImage extends ImageAdapter {
+ /**
+ * Creates a new wrapper for the given image.
+ *
+ * @param source the image to wrap.
+ */
+ protected TileForwardingImage(final RenderedImage source) {
+ super(source);
+ }
+
+ /** Delegates to the wrapped image. */
+ @Override public final Raster getTile(int tx, int ty) {return
source.getTile(tx, ty);}
+ @Override public final Raster getData() {return
source.getData();}
+ @Override public final Raster getData(Rectangle region) {return
source.getData(region);}
+ @Override public final WritableRaster copyData(WritableRaster r) {return
source.copyData(r);}
+
+ /**
+ * Notifies the source image that tiles will be computed soon in the given
region.
+ * If the source image is an instance of {@link PlanarImage}, then this
method
+ * forwards the notification to it. Otherwise default implementation does
nothing.
+ */
+ @Override
+ protected Disposable prefetch(final Rectangle tiles) {
+ if (source instanceof PlanarImage) {
+ /*
+ * Forwarding directly is possible because the contract
+ * of this class said that tile indices must be the same.
+ */
+ return ((PlanarImage) source).prefetch(tiles);
+ } else {
+ return super.prefetch(tiles);
+ }
+ }
+}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Transferer.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Transferer.java
index 9cf08a39aa..5112f21695 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Transferer.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Transferer.java
@@ -632,7 +632,7 @@ abstract class Transferer {
if (target.getMinX() == aoi.x && target.getWidth() == aoi.width) {
final SampleModel sm = target.getSampleModel();
if (sm instanceof ComponentSampleModel) {
- final ComponentSampleModel cm = (ComponentSampleModel) sm;
+ final var cm = (ComponentSampleModel) sm;
if (cm.getPixelStride() == 1 && cm.getScanlineStride() ==
target.getWidth()) {
for (final int offset :
target.getDataBuffer().getOffsets()) {
if (offset != 0) {
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/UserProperties.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/UserProperties.java
index 6f99bb7547..a70fca2723 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/UserProperties.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/UserProperties.java
@@ -31,7 +31,7 @@ import java.awt.image.RenderedImage;
*
* @author Martin Desruisseaux (Geomatys)
*/
-final class UserProperties extends ImageAdapter {
+final class UserProperties extends TileForwardingImage {
/**
* The user-specified properties which may overwrite source image
properties.
* This is a reference to the map specified at construction time, not a
copy.
@@ -114,7 +114,7 @@ final class UserProperties extends ImageAdapter {
* Appends a content to show in the {@link #toString()} representation.
*/
@Override
- Class<? extends ImageAdapter> appendStringContent(final StringBuilder
buffer) {
+ Class<UserProperties> appendStringContent(final StringBuilder buffer) {
buffer.append(properties.keySet());
return UserProperties.class;
}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Visualization.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Visualization.java
index 7d223dc81b..7227566885 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Visualization.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/Visualization.java
@@ -241,8 +241,8 @@ final class Visualization extends ResampledImage {
toSource = MathTransforms.identity(BIDIMENSIONAL);
}
for (;;) {
- if (source instanceof ImageAdapter) {
- source = ((ImageAdapter) source).source;
+ if (source instanceof TileForwardingImage) {
+ source = ((TileForwardingImage) source).source;
} else if (source instanceof ResampledImage) {
final var resampled = (ResampledImage) source;
toSource = MathTransforms.concatenate(toSource,
resampled.toSource);
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableTiledImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableTiledImage.java
index 986da20ea1..8dbd0b9921 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableTiledImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableTiledImage.java
@@ -23,7 +23,6 @@ import java.awt.Rectangle;
import java.awt.image.ColorModel;
import java.awt.image.SampleModel;
import java.awt.image.Raster;
-import java.awt.image.TileObserver;
import java.awt.image.WritableRaster;
import java.awt.image.WritableRenderedImage;
import org.apache.sis.feature.internal.Resources;
@@ -37,18 +36,6 @@ import org.apache.sis.feature.internal.Resources;
* @author Martin Desruisseaux (Geomatys)
*/
public class WritableTiledImage extends TiledImage implements
WritableRenderedImage {
- /**
- * The observers, or {@code null} if none. This is a copy-on-write array:
- * values are never modified after construction (new arrays are created).
- *
- * This field is declared volatile because it is read without
synchronization by
- * {@link #getWritableTile(int, int)} and {@link #releaseWritableTile(int,
int)}.
- * Since this is a copy-on-write array, it is okay to omit synchronization
for
- * those methods but we still need the memory effect.
- */
- @SuppressWarnings("VolatileArrayField")
- private volatile TileObserver[] observers;
-
/**
* Indices of tiles taken for a write operation.
* Values are counter of calls to {@link #getWritableTile(int, int)}.
@@ -100,29 +87,6 @@ public class WritableTiledImage extends TiledImage
implements WritableRenderedIm
return sampleModel;
}
- /**
- * Adds an observer to be notified when a tile is checked out for writing.
- * If the observer is already present, it will receive multiple
notifications.
- *
- * @param observer the observer to notify.
- */
- @Override
- public synchronized void addTileObserver(final TileObserver observer) {
- observers = WritableUntiledImage.addTileObserver(observers, observer);
- }
-
- /**
- * Removes an observer from the list of observers notified when a tile is
checked out for writing.
- * If the observer was not registered, nothing happens. If the observer
was registered for multiple
- * notifications, it will now be registered for one fewer.
- *
- * @param observer the observer to stop notifying.
- */
- @Override
- public synchronized void removeTileObserver(final TileObserver observer) {
- observers = WritableUntiledImage.removeTileObserver(observers,
observer);
- }
-
/**
* Returns the tile at the given location in tile coordinates.
* If the tile is null, an initially empty tile is created.
@@ -174,7 +138,7 @@ public class WritableTiledImage extends TiledImage
implements WritableRenderedIm
count = writables.merge(key, 1, (old, one) -> old + 1);
}
if (count <= 1) {
- WritableUntiledImage.fireTileUpdate(observers, this, tileX, tileY,
true);
+ fireTileUpdate(tileX, tileY, true);
}
return tile;
}
@@ -203,7 +167,7 @@ public class WritableTiledImage extends TiledImage
implements WritableRenderedIm
throw new
IllegalArgumentException(Resources.format(Resources.Keys.TileNotWritable_2,
tileX, tileY));
}
if (close) {
- WritableUntiledImage.fireTileUpdate(observers, this, tileX, tileY,
false);
+ fireTileUpdate(tileX, tileY, false);
}
}
diff --git
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableUntiledImage.java
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableUntiledImage.java
index abeeb4c0bb..e81cf62b38 100644
---
a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableUntiledImage.java
+++
b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/WritableUntiledImage.java
@@ -247,25 +247,12 @@ public final class WritableUntiledImage extends
BufferedImage {
*/
private void fireTileUpdate(final int count, final boolean willBeWritable)
{
if (count == 0) {
- fireTileUpdate(observers, this, 0, 0, willBeWritable);
- }
- }
-
- /**
- * Notifies all listeners that the specified tile has been checked out for
writing or has been released.
- *
- * @param observers the observers to notify, or {@code null} if none.
- * @param image the image that owns the tile.
- * @param tileX the <var>x</var> index of the tile that is being
updated.
- * @param tileY the <var>y</var> index of the tile that is being
updated.
- * @param willBeWritable if {@code true}, the tile will be grabbed for
writing; otherwise it is being released.
- */
- static void fireTileUpdate(final TileObserver[] observers, final
WritableRenderedImage image,
- final int tileX, final int tileY, final boolean
willBeWritable)
- {
- if (observers != null) {
- for (final TileObserver observer : observers) {
- observer.tileUpdate(image, tileX, tileY, willBeWritable);
+ @SuppressWarnings("LocalVariableHidesMemberVariable")
+ final TileObserver[] observers = this.observers;
+ if (observers != null) {
+ for (final TileObserver observer : observers) {
+ observer.tileUpdate(this, 0, 0, willBeWritable);
+ }
}
}
}
diff --git
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/BandedSampleConverterTest.java
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/BandedSampleConverterTest.java
index 1fc4366a5e..86358db714 100644
---
a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/BandedSampleConverterTest.java
+++
b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/BandedSampleConverterTest.java
@@ -69,9 +69,15 @@ public final class BandedSampleConverterTest extends
ImageTestCase {
random.nextBoolean()); // Banded or interleaved
sample model
source.validate(false);
source.initializeAllTiles(0);
- image = BandedSampleConverter.create(source, ImageLayout.DEFAULT, null,
- new MathTransform1D[] {(MathTransform1D)
MathTransforms.linear(scale, 0)},
- targetType, null);
+ image = new BandedSampleConverter.Builder(
+ source,
+ ImageLayout.DEFAULT,
+ null,
+ new MathTransform1D[] {
+ (MathTransform1D) MathTransforms.linear(scale, 0)
+ },
+ targetType,
+ null).create();
}
/**
diff --git
a/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/coverage/ImagePropertyExplorer.java
b/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/coverage/ImagePropertyExplorer.java
index 7d49d1fc7c..e6de3b5e3b 100644
---
a/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/coverage/ImagePropertyExplorer.java
+++
b/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/coverage/ImagePropertyExplorer.java
@@ -720,10 +720,10 @@ public class ImagePropertyExplorer extends Widget {
}
/**
- * Update the list of properties for the given image.
+ * Updates the list of properties for the given image.
* The {@link #propertyRows} are updated with an effort for reusing
existing items when
* the property name is the same. The intent is to keep selection
unchanged if possible
- * (because removing a selected row may make it unselected).
+ * (because removing a selected row may makes it unselected).
*/
private void updatePropertyList(final RenderedImage selected) {
if (selected != null) {
@@ -732,10 +732,9 @@ public class ImagePropertyExplorer extends Widget {
int insertAt = 0;
nextProp: for (final String property : properties) {
if (property != null) {
- for (int i=insertAt; i < propertyRows.size(); i++) {
+ for (int i = insertAt; i < propertyRows.size(); i++) {
if (propertyRows.get(i).update(selected,
property)) {
- propertyRows.remove(insertAt, i);
- insertAt = i + 1;
+ propertyRows.remove(insertAt++, i);
continue nextProp;
}
}