Statistics
| Revision:

gvsig-raster / org.gvsig.raster / branches / org.gvsig.raster.2.4 / org.gvsig.raster / org.gvsig.raster.lib / org.gvsig.raster.lib.legend / org.gvsig.raster.lib.legend.impl / src / main / java / org / gvsig / raster / lib / legend / impl / DefaultRasterLegend.java @ 8788

History | View | Annotate | Download (52 KB)

1
package org.gvsig.raster.lib.legend.impl;
2

    
3
import java.awt.Graphics;
4
import java.awt.Image;
5
import java.awt.geom.AffineTransform;
6
import java.awt.geom.NoninvertibleTransformException;
7
import java.awt.image.BufferedImage;
8
import java.util.ArrayList;
9
import java.util.Iterator;
10
import java.util.List;
11

    
12
import org.cresques.cts.ICoordTrans;
13
import org.slf4j.Logger;
14
import org.slf4j.LoggerFactory;
15

    
16
import org.gvsig.fmap.dal.DALLocator;
17
import org.gvsig.fmap.dal.DataStore;
18
import org.gvsig.fmap.dal.raster.api.RasterStore;
19
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
20
import org.gvsig.fmap.geom.GeometryLocator;
21
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
22
import org.gvsig.fmap.geom.exception.CreateGeometryException;
23
import org.gvsig.fmap.geom.primitive.Envelope;
24
import org.gvsig.fmap.geom.primitive.Point;
25
import org.gvsig.fmap.mapcontext.ViewPort;
26
import org.gvsig.fmap.mapcontext.raster.api.legend.ChangeColorInterpretationEvent;
27
import org.gvsig.fmap.mapcontext.raster.api.legend.ChangePaletteBandEvent;
28
import org.gvsig.fmap.mapcontext.raster.api.legend.ChangePaletteEvent;
29
import org.gvsig.fmap.mapcontext.raster.api.legend.RasterLegendEvent;
30
import org.gvsig.fmap.mapcontext.raster.api.legend.listeners.RasterLegendChangedListener;
31
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
32
import org.gvsig.fmap.mapcontext.rendering.legend.events.LegendContentsChangedListener;
33
import org.gvsig.fmap.mapcontext.rendering.legend.events.SymbolLegendEvent;
34
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
35
import org.gvsig.raster.lib.buffer.api.Band;
36
import org.gvsig.raster.lib.buffer.api.Buffer;
37
import org.gvsig.raster.lib.buffer.api.BufferLocator;
38
import org.gvsig.raster.lib.buffer.api.BufferManager;
39
import org.gvsig.raster.lib.buffer.api.NoData;
40
import org.gvsig.raster.lib.buffer.api.OperationManager;
41
import org.gvsig.raster.lib.buffer.api.exceptions.BufferException;
42
import org.gvsig.raster.lib.buffer.api.exceptions.BufferOperationException;
43
import org.gvsig.raster.lib.buffer.api.operations.Operation;
44
import org.gvsig.raster.lib.buffer.api.operations.OperationList;
45
import org.gvsig.raster.lib.buffer.api.operations.OperationListEntry;
46
import org.gvsig.raster.lib.buffer.api.operations.SpecifiedBandsOperation;
47
import org.gvsig.raster.lib.buffer.spi.operations.AbstractOperation;
48
import org.gvsig.raster.lib.buffer.spi.operations.AbstractSpecifiedBandsOperation;
49
import org.gvsig.raster.lib.legend.api.RasterLegend;
50
import org.gvsig.raster.lib.legend.api.Transparency;
51
import org.gvsig.raster.lib.legend.api.colorinterpretation.ColorInterpretation;
52
import org.gvsig.raster.lib.legend.api.colorinterpretation.ColorInterpretationNotification;
53
import org.gvsig.raster.lib.legend.api.colortable.ColorTable;
54
import org.gvsig.raster.lib.legend.api.operations.ColoredOperation;
55
import org.gvsig.raster.lib.legend.impl.operations.cmyktorgb.CMYKToRGBOperation;
56
import org.gvsig.raster.lib.legend.impl.operations.cmyktorgb.CMYKToRGBOperationFactory;
57
import org.gvsig.raster.lib.legend.impl.operations.colortable.ColorTableOperation;
58
import org.gvsig.raster.lib.legend.impl.operations.colortable.ColorTableOperationFactory;
59
import org.gvsig.raster.lib.legend.impl.operations.hsltorgb.HSLToRGBOperation;
60
import org.gvsig.raster.lib.legend.impl.operations.hsltorgb.HSLToRGBOperationFactory;
61
import org.gvsig.tools.ToolsLocator;
62
import org.gvsig.tools.dispose.DisposeUtils;
63
import org.gvsig.tools.dynobject.DynClass;
64
import org.gvsig.tools.dynobject.DynObject;
65
import org.gvsig.tools.dynobject.DynObjectManager;
66
import org.gvsig.tools.dynobject.DynStruct;
67
import org.gvsig.tools.dynobject.impl.DefaultDynObjectManager;
68
import org.gvsig.tools.locator.LocatorException;
69
import org.gvsig.tools.observer.Observable;
70
import org.gvsig.tools.operations.OperationException;
71
import org.gvsig.tools.persistence.PersistenceManager;
72
import org.gvsig.tools.persistence.Persistent;
73
import org.gvsig.tools.persistence.PersistentState;
74
import org.gvsig.tools.persistence.exception.PersistenceException;
75
import org.gvsig.tools.swing.api.ToolsSwingLocator;
76
import org.gvsig.tools.task.SimpleTaskStatus;
77
import org.gvsig.tools.task.TaskStatusManager;
78

    
79
/**
80
 * Default implementation of {@link RasterLegend}. This object can draw buffers
81
 * with a {@link ColorInterpretation}, {@link ColorTable} and {@link OperationList}
82
 *
83
 *
84
 * @author <a href="mailto:lmarques@disid.com">Lluis Marques</a>
85
 *
86
 */
87
public class DefaultRasterLegend implements RasterLegend {
88

    
89
    private static final Logger LOG = LoggerFactory.getLogger(DefaultRasterLegend.class);
90

    
91
    private ColorInterpretation colorInterpretation;
92
    private Transparency transparency;
93
    private OperationList filters;
94
    private boolean transparentNoData;
95
    private ColorManager colorManager;
96

    
97
    private List<RasterLegendChangedListener> listeners =
98
        new ArrayList<RasterLegendChangedListener>();
99

    
100
    /**
101
     * Persistence definition name
102
     */
103
    public static final String PERSISTENT_NAME = "RasterLegendPersistence";
104
    /**
105
     * Description of persistence definition
106
     */
107
    public static final String PERSISTENT_DESCRIPTION = "Persistence definition of raster legend";
108

    
109
    private final static String COLOR_INTERPRETATION_PERSISTENCE_FIELD = "colorInterpretation";
110
    private final static String FILTERS_PERSISTENCE_FIELD = "filters";
111

    
112
    /**
113
     * Empty constructor
114
     */
115
    public DefaultRasterLegend() {
116

    
117
    }
118

    
119
    /**
120
     * Default {@link RasterLegend} constructor
121
     *
122
     * @param colorInterpretation
123
     *            Color interpretation of legend
124
     */
125
    public DefaultRasterLegend(ColorInterpretation colorInterpretation) {
126
        this(colorInterpretation, null, null);
127
    }
128

    
129
    /**
130
     * Default {@link RasterLegend} constructor
131
     *
132
     * @param colorTable
133
     *            Color table of legend
134
     * @param colorInterpretation
135
     *            Color interpretation of legend
136
     * @param transparency
137
     *            Transparency of legend
138
     * @param filters
139
     *            Filters of legend
140
     */
141
    public DefaultRasterLegend(ColorInterpretation colorInterpretation,
142
        Transparency transparency, OperationList filters) {
143
        this.transparency = transparency;
144
        this.filters = filters;
145
        setColorInterpretation(colorInterpretation);
146
    }
147

    
148
    @Override
149
    public void draw(Graphics graphics, Buffer buffer, ViewPort viewPort,
150
        SimpleTaskStatus taskStatus) {
151

    
152
        boolean isMyTask = false;
153
        if (taskStatus == null) {
154
            TaskStatusManager taskStatusManager = ToolsLocator.getTaskStatusManager();
155
            taskStatus =
156
                taskStatusManager.createDefaultSimpleTaskStatus("_drawing_buffer_XxellipsisxX");
157
            taskStatus.setAutoremove(true);
158
            taskStatus.add();
159
            isMyTask = true;
160
        } else {
161
            taskStatus.push();
162
        }
163

    
164
        taskStatus.setIndeterminate();
165

    
166
        if (this.colorInterpretation == null || !this.colorInterpretation.hasInterpretation()
167
            || this.colorInterpretation.isUndefined()) {
168
            taskStatus.abort();
169
            throw new IllegalStateException(
170
                "To draw buffer, raster legend has to have a color interpretation");
171
        }
172

    
173
        // Check if viewport projection is the same as buffer projection
174
        Buffer clip = null;
175
        Buffer interpolated = null;
176
        Buffer converted = null;
177
        Buffer interpolated2 = null;
178
        Buffer bufferToDraw = buffer;
179
        try {
180
            if (bufferToDraw != null && bufferToDraw.getColumns()>0 && bufferToDraw.getRows()>0) {
181

    
182
                if (!viewPort.getProjection().equals(bufferToDraw.getProjection())) {
183

    
184
                    // Convert extension to check if envelopes intersect
185
                    ICoordTrans coordTrans = viewPort.getProjection().getCT(bufferToDraw.getProjection());
186
                    ICoordTrans invertedCoordTrans = bufferToDraw.getProjection().getCT(viewPort.getProjection());
187
                    Envelope convertedEnvelope = viewPort.getAdjustedEnvelope().convert(coordTrans);
188
                    double viewPortPixelSizeX = viewPort.getAdjustedEnvelope().getLength(0) / viewPort.getImageWidth();
189
                    double viewPortPixelSizeY = viewPort.getAdjustedEnvelope().getLength(1) / viewPort.getImageHeight();
190
                    if (!convertedEnvelope.intersects(bufferToDraw.getEnvelope())) {
191
                        return;
192
                    }
193
                    try {
194
                        // Clip buffer with doubled converted envelope
195
                        clip = bufferToDraw.clip(convertedEnvelope);
196
                        Envelope bufferEnvelopeInViewPortCoords = clip.getEnvelope().convert(invertedCoordTrans);
197

    
198
                        double widthPixel = bufferEnvelopeInViewPortCoords.getLength(0) / viewPortPixelSizeX;
199
                        double heightPixel = bufferEnvelopeInViewPortCoords.getLength(1) / viewPortPixelSizeY;
200

    
201
                        interpolated =
202
                            clip.createInterpolated((int) Math.floor(heightPixel), (int) Math.floor(widthPixel),
203
                                Buffer.INTERPOLATION_Bilinear, taskStatus);
204
                        // Convert interpolated clipped buffer
205
                        converted = interpolated.convert(invertedCoordTrans, taskStatus);
206

    
207
                        widthPixel = getWidthPixel(converted.getEnvelope(), viewPortPixelSizeX);
208
                        heightPixel = getHeightPixel(converted.getEnvelope(), viewPortPixelSizeY);
209

    
210
                        interpolated2 =
211
                            converted.createInterpolated((int) Math.floor(heightPixel), (int) Math.floor(widthPixel),
212
                                Buffer.INTERPOLATION_Bilinear, taskStatus);
213

    
214
                        bufferToDraw = interpolated2;
215

    
216
                    } catch (BufferException | LocatorException | CreateEnvelopeException e) {
217
                        LOG.warn("Buffer can not be clipped, converted or interpolated", e);
218
                        taskStatus.abort();
219
                        return;
220
                    }
221
                } else if (viewPort.getAdjustedEnvelope().intersects(bufferToDraw.getEnvelope())) {
222

    
223
                    double widthPixel = 0;
224
                    double heightPixel = 0;
225
                    try {
226
                        // Clip and interpolate buffer with view port envelope
227
                        if (!bufferToDraw.getEnvelope().equals(viewPort.getAdjustedEnvelope())) {
228
                            clip = bufferToDraw.clip(viewPort.getAdjustedEnvelope());
229
                            bufferToDraw = clip;
230
                        }
231
                        widthPixel =
232
                            getWidthPixel(bufferToDraw.getEnvelope(), viewPort.getAdjustedEnvelope().getLength(0)
233
                                / viewPort.getImageWidth());
234
                        heightPixel =
235
                            getHeightPixel(bufferToDraw.getEnvelope(), viewPort.getAdjustedEnvelope().getLength(1)
236
                                / viewPort.getImageHeight());
237

    
238
                        interpolated =
239
                            bufferToDraw.createInterpolated((int) Math.floor(heightPixel),
240
                                (int) Math.floor(widthPixel), Buffer.INTERPOLATION_BicubicSpline, taskStatus);
241
                        bufferToDraw = interpolated;
242
                    } catch (BufferException e) {
243
                        LOG.warn(
244
                            "Buffer can not be interpolated with [rows: {} , columns: {}, method: {}]",
245
                            new String[] { String.valueOf((int) Math.floor(heightPixel)),
246
                                String.valueOf((int) Math.floor(widthPixel)),
247
                                String.valueOf(Buffer.INTERPOLATION_BicubicSpline) });
248
                        taskStatus.abort();
249
                        return;
250
                    }
251
                } else {
252
                    // Do nothing view port envelope does not intersect with
253
                    // buffer
254
                    return;
255
                }
256
            }
257

    
258
            OperationManager operationManager = BufferLocator.getOperationManager();
259

    
260
            if (bufferToDraw != null && bufferToDraw.getColumns()>0 && bufferToDraw.getRows()>0) {
261

    
262
                // Draw buffer
263
                Image image = null;
264
                try {
265
                    DynObjectManager dynObjectManager = new DefaultDynObjectManager();
266
                    DynClass parametersClass = dynObjectManager.createDynClass("Parameters", "Parameters to find through ultimately.");
267
                    parametersClass.addDynFieldObject(ColoredOperation.OUTPUT_COLOR_INTERPRETATION_PARAM);
268
                    DynObject defaultParameters = dynObjectManager.createDynObject(parametersClass);
269
                    defaultParameters.setDynValue(ColoredOperation.OUTPUT_COLOR_INTERPRETATION_PARAM, colorInterpretation);
270

    
271
                    getFilters().setDefaultParameters(defaultParameters);
272

    
273
                    Object oColorInterpretation = null;
274
                    Buffer filteredBuffer = bufferToDraw;
275
                    filteredBuffer = getFilters().execute(bufferToDraw);
276
                    oColorInterpretation = getFilters().getParameterValue(ColoredOperation.OUTPUT_COLOR_INTERPRETATION_PARAM);
277
                    ColorInterpretation colorInterpretationAfterFilters = null;
278
                    if (oColorInterpretation != null) {
279
                        colorInterpretationAfterFilters = (ColorInterpretation) oColorInterpretation;
280
                    }
281
                    if (colorInterpretationAfterFilters == null) {
282
                        colorInterpretationAfterFilters = colorInterpretation;
283
                    }
284

    
285
                    if (colorInterpretationAfterFilters.isPalette()) {
286
                        DynObject colorTableOperationParameters =
287
                            operationManager.createOperationParameters(ColoredOperation.COLOR_TABLE_OPERATION_NAME);
288
                        colorTableOperationParameters.setDynValue(ColoredOperation.COLOR_INTERPRETATION_PARAM,
289
                            colorInterpretationAfterFilters);
290
//                        colorTableOperationParameters.setDynValue(ColoredOperation.COPY_UNPROCESSED_BANDS_PARAM,
291
//                            true);
292
                        Buffer rgbBuffer =
293
                            operationManager.execute(ColoredOperation.COLOR_TABLE_OPERATION_NAME, filteredBuffer,
294
                                colorTableOperationParameters);
295
                        image =
296
                            drawRGBBuffer(graphics, rgbBuffer,
297
                                (ColorInterpretation) colorTableOperationParameters
298
                                    .getDynValue(ColoredOperation.OUTPUT_COLOR_INTERPRETATION_PARAM), transparency,
299
                                getFilters());
300

    
301
                    } else if (colorInterpretationAfterFilters.hasAnyGrayBand()) {
302
                        // Draw buffer with gray scale
303
                        image = drawGrayBuffer(graphics, filteredBuffer, colorInterpretationAfterFilters, transparency, filters);
304
                        // } else if (this.colorInterpretation.isRGBA() ||
305
                        // this.colorInterpretation.isRGB()
306
                        // || this.colorInterpretation.isBGR() ||
307
                        // this.colorInterpretation.hasRGBBands()) {
308
                    } else if (colorInterpretationAfterFilters.hasAnyRGBBand()) {
309
                        // Draw RGB, RGBA or BGR buffer without color table
310
                        image =
311
                            drawRGBBuffer(graphics, filteredBuffer, colorInterpretationAfterFilters, transparency,
312
                                filters);
313
                    } else if (colorInterpretationAfterFilters.hasAnyHSLBand()) {
314
                        // Draw HSL buffer without color table
315
                        // image = drawHSLBuffer(graphics, bufferToDraw,
316
                        // colorInterpretation, transparency, filters);
317

    
318
                        DynObject hSLToRGBOperationParameters =
319
                            operationManager.createOperationParameters(HSLToRGBOperationFactory.NAME);
320
                        hSLToRGBOperationParameters.setDynValue(ColoredOperation.COLOR_INTERPRETATION_PARAM,
321
                            colorInterpretationAfterFilters);
322
//                        hSLToRGBOperationParameters.setDynValue(ColoredOperation.COPY_UNPROCESSED_BANDS_PARAM, true);
323
                        Buffer rgbBuffer =
324
                            operationManager.execute(HSLToRGBOperationFactory.NAME, filteredBuffer,
325
                                hSLToRGBOperationParameters);
326
                        image =
327
                            drawRGBBuffer(graphics, rgbBuffer,
328
                                (ColorInterpretation) hSLToRGBOperationParameters
329
                                    .getDynValue(ColoredOperation.OUTPUT_COLOR_INTERPRETATION_PARAM), transparency,
330
                                filters);
331

    
332
                    } else if (colorInterpretationAfterFilters.hasAnyCMYKBand()) {
333
                        // Draw CMYK buffer without color table
334
//                        image = drawCMYKBuffer(graphics, filteredBuffer, colorInterpretationAfterFilters, transparency, filters);
335

    
336
                        DynObject cmykToRGBOperationParameters =
337
                            operationManager.createOperationParameters(CMYKToRGBOperationFactory.NAME);
338
                        cmykToRGBOperationParameters.setDynValue(ColoredOperation.COLOR_INTERPRETATION_PARAM,
339
                            colorInterpretationAfterFilters);
340
//                        cmykToRGBOperationParameters.setDynValue(CMYKToRGBOperation.COPY_UNPROCESSED_BANDS_PARAM, true);
341
                        Buffer rgbBuffer =
342
                            operationManager.execute(CMYKToRGBOperationFactory.NAME, filteredBuffer,
343
                                cmykToRGBOperationParameters);
344
                        image =
345
                            drawRGBBuffer(graphics, rgbBuffer,
346
                                (ColorInterpretation) cmykToRGBOperationParameters
347
                                    .getDynValue(ColoredOperation.OUTPUT_COLOR_INTERPRETATION_PARAM), transparency,
348
                                filters);
349

    
350
                    } else if (colorInterpretationAfterFilters.hasAnyYCBCRBand()) {
351
                        // TODO: Hacer un filtro YCBCRToRGB y llamarlo como en
352
                        // los de arriba
353

    
354
                        // Draw YCBCR buffer without color table
355
                        image = drawYCBCRBuffer(graphics, bufferToDraw, colorInterpretation, transparency, filters);
356
                    }
357
                } catch (BufferOperationException e) {
358
                    LOG.warn("Buffer can't be converted to byte buffer", e);
359
                    taskStatus.abort();
360
                    return;
361
                }
362

    
363
                // Calculate where image has to be drawn
364
                double x = bufferToDraw.getEnvelope().getMinimum(0);
365
                double y = bufferToDraw.getEnvelope().getMaximum(1);
366
                AffineTransform affineTransform =
367
                    calculateAffineTransform(viewPort.getAdjustedEnvelope(), viewPort.getImageWidth(),
368
                        viewPort.getImageHeight());
369

    
370
                Point point;
371
                try {
372
                    point = GeometryLocator.getGeometryManager().createPoint(x, y, SUBTYPES.GEOM2D);
373
                    point.transform(affineTransform.createInverse());
374
                    graphics.drawImage(image, (int) Math.floor(point.getX()), (int) Math.floor(point.getY()), null);
375
                } catch (CreateGeometryException | NoninvertibleTransformException e) {
376
                    LOG.warn("Can not calculate the point of buffer in viewport image", e);
377
                    taskStatus.abort();
378
                    return;
379
                }
380
            }
381
        } catch (LocatorException | CreateEnvelopeException e1) {
382
            LOG.warn("Can not calculate the envelope of buffer", e1);
383
            taskStatus.abort();
384
            return;
385
        } finally {
386
            if (clip != null) {
387
                DisposeUtils.dispose(clip);
388
                clip = null;
389
            }
390
            if (interpolated != null) {
391
                DisposeUtils.dispose(interpolated);
392
                interpolated = null;
393
            }
394
            if (converted != null) {
395
                DisposeUtils.dispose(converted);
396
                converted = null;
397
            }
398
            if (interpolated2 != null) {
399
                DisposeUtils.dispose(interpolated2);
400
                interpolated2 = null;
401
            }
402
            if (bufferToDraw == null && bufferToDraw != buffer) {
403
                DisposeUtils.dispose(bufferToDraw);
404
                bufferToDraw = null;
405
            }
406

    
407
            if (!isMyTask) {
408
                taskStatus.pop();
409
            }
410
        }
411
    }
412

    
413
    private AffineTransform calculateAffineTransform(Envelope envelope, double imageWidth,
414
        double imageHeight) {
415
        double pixelSizeX = envelope.getLength(0) / imageWidth;
416
        double rotationX = 0;
417
        double x = envelope.getMinimum(0);
418
        double rotationY = 0;
419
        double pixelSizeY = -envelope.getLength(1) / imageHeight;
420
        double y = envelope.getMaximum(1);
421
        return new AffineTransform(pixelSizeX, rotationY, rotationX, pixelSizeY, x, y);
422
    }
423

    
424
    private double getWidthPixel(Envelope envelope, double dist1pixel) {
425
        double widthEnvelope = envelope.getLength(0);
426
        return widthEnvelope / dist1pixel;
427
    }
428

    
429
    private double getHeightPixel(Envelope envelope, double dist1pixel) {
430
        double heightEnvelope = envelope.getLength(1);
431
        return heightEnvelope / dist1pixel;
432
    }
433

    
434

    
435

    
436
    private Image drawRGBBuffer(Graphics graphics, Buffer buffer,
437
        ColorInterpretation colorInterpretation, Transparency transparency, OperationList filters) throws BufferOperationException {
438

    
439
        Buffer byteBuffer = convertToByteBuffer(buffer);
440
        Buffer bufferToDraw = byteBuffer;
441

    
442
        BufferedImage image = null;
443

    
444
        if (colorInterpretation.isRGB() || colorInterpretation.isRGBA() || colorInterpretation.hasAnyRGBBand()) {
445
            image = ToolsSwingLocator.getToolsSwingManager().createBufferedImage(bufferToDraw.getColumns(), bufferToDraw.getRows(),
446
                    BufferedImage.TYPE_INT_ARGB);
447
        } else if (colorInterpretation.isBGR()) {
448
            image = ToolsSwingLocator.getToolsSwingManager().createBufferedImage(bufferToDraw.getColumns(), bufferToDraw.getRows(),
449
                BufferedImage.TYPE_INT_BGR);
450
        }
451

    
452
        if (image == null) {
453
            throw new IllegalStateException(
454
                "Color interpretation is not RGB,RGBA or BGR and buffer was be drawn without color table");
455
        }
456

    
457
        int redBandIndex = colorInterpretation.getBand(ColorInterpretation.RED_BAND);
458
        int greenBandIndex = colorInterpretation.getBand(ColorInterpretation.GREEN_BAND);
459
        int blueBandIndex = colorInterpretation.getBand(ColorInterpretation.BLUE_BAND);
460

    
461
        Band redBand = null;
462
        if(redBandIndex>=0){
463
            redBand = bufferToDraw.getBand(redBandIndex);
464
        }
465
        Band greenBand = null;
466
        if(greenBandIndex>=0){
467
            greenBand = bufferToDraw.getBand(greenBandIndex);
468
        }
469
        Band blueBand = null;
470
        if(blueBandIndex>=0){
471
            blueBand = bufferToDraw.getBand(blueBandIndex);
472
        }
473
        Band alphaBand = null;
474
        if (colorInterpretation.hasAlphaBand()) {
475
            int alphaBandIndex =
476
                colorInterpretation.getBand(ColorInterpretation.ALPHA_BAND);
477
            alphaBand = bufferToDraw.getBand(alphaBandIndex);
478
        }
479

    
480
        for (int i = 0; i < bufferToDraw.getRows(); i++) {
481
            for (int j = 0; j < bufferToDraw.getColumns(); j++) {
482

    
483
                int alphaByteValue = 255;
484
                int redByteValue = 0;
485
                if(redBand!=null){
486
                    Number redValue = (Number) redBand.get(i, j);
487
                    NoData noData = redBand.getNoData();
488
                    if(noData != null){
489
                        if(redValue.equals(noData.getValue())){
490
                            alphaByteValue = 0;
491
                            redByteValue = 0;
492
                        } else {
493
                            alphaByteValue = 255;
494
                            redByteValue = redValue.byteValue();
495
                        }
496
                    } else {
497
                        redByteValue = redValue.byteValue();
498
                    }
499
                }
500
                int greenByteValue = 0;
501
                if(greenBand!=null){
502
                    Number greenValue = (Number) greenBand.get(i, j);
503
                    NoData noData = greenBand.getNoData();
504
                    if(noData != null){
505
                        if(greenValue.equals(noData.getValue())){
506
                            alphaByteValue = (alphaByteValue!=0)?255:0;
507
                            greenByteValue = 0;
508
                        } else {
509
                            alphaByteValue = 255;
510
                            greenByteValue = greenValue.byteValue();
511
                        }
512
                    } else {
513
                        greenByteValue = greenValue.byteValue();
514
                    }
515
                }
516
                int blueByteValue = 0;
517
                if(blueBand!=null){
518
                    Number blueValue = (Number) blueBand.get(i, j);
519
                    NoData noData = blueBand.getNoData();
520
                    if(noData != null){
521
                        if(blueValue.equals(noData.getValue())){
522
                            alphaByteValue = (alphaByteValue!=0)?255:0;
523
                            blueByteValue = 0;
524
                        } else {
525
                            alphaByteValue = 255;
526
                            blueByteValue = blueValue.byteValue();
527
                        }
528
                    } else {
529
                        blueByteValue = blueValue.byteValue();
530
                    }
531
                }
532

    
533
                if (alphaByteValue!=0 && alphaBand != null) {
534
                    Number alphaValue = (Number) alphaBand.get(i, j);
535
                    int alphaBandIndex = colorInterpretation.getBand(ColorInterpretation.ALPHA_BAND);
536
                    NoData noData = alphaBand.getNoData();
537
                    if(noData != null){
538
                        if(alphaValue.equals(noData.getValue())){
539
                            alphaByteValue = 0;
540
                        } else {
541
                            alphaByteValue = alphaValue.byteValue();
542
                        }
543
                    } else {
544
                        alphaByteValue = alphaValue.byteValue();
545
                    }
546
                }
547

    
548
                if (alphaByteValue!=0 && transparency != null) {
549
                    // Apply defined transparency ranges
550

    
551
                    int newAlpha =
552
                        transparency.getTransparencyRangeAlpha(redByteValue,
553
                            greenByteValue, blueByteValue);
554
                    alphaByteValue = getNewAlpha(alphaByteValue, newAlpha);
555

    
556
                    // Apply general transparency
557
                    int transparencyValue = transparency.getAlpha();
558
                    alphaByteValue = getNewAlpha(alphaByteValue, transparencyValue);
559
                }
560

    
561
                //FIXME: TO REMOVE??
562
//                if (filters != null) {
563
//                    // TODO Apply filters
564
//                }
565

    
566
                int intRGB = 0;
567
                if (colorInterpretation.hasAnyRGBBand()) {//colorInterpretation.isRGB() || colorInterpretation.isRGBA()) {
568
                    intRGB = (((byte)alphaByteValue & 0xFF) << 24) | // alpha
569
                        (((byte)redByteValue & 0xFF) << 16) | // red
570
                        (((byte)greenByteValue & 0xFF) << 8) | // green
571
                        (((byte)blueByteValue & 0xFF)); // blue String.format("%X", b)
572
//                    intRGB = ((alphaByteValue & 0xFF) << 24) | // alpha
573
//                        ((redByteValue & 0xFF) << 16) | // red
574
//                        ((greenByteValue & 0xFF) << 8) | // green
575
//                        ((blueByteValue & 0xFF) << 0); // blue String.format("%X", b)
576
                } else if (colorInterpretation.isBGR()) {
577
                    intRGB = (((byte)blueByteValue & 0xFF) << 16 | // blue
578
                        (((byte)greenByteValue & 0xFF) << 8) | // green
579
                        (((byte)redByteValue & 0xFF))); // red
580

    
581
                }
582
                image.setRGB(j, i, intRGB);
583
            }
584
        }
585
        return image;
586
    }
587

    
588
    private Image drawHSLBuffer(Graphics graphics, Buffer buffer,
589
        ColorInterpretation colorInterpretation,Transparency transparency,
590
        OperationList filters) throws BufferOperationException {
591

    
592
        Buffer byteBuffer = convertToByteBuffer(buffer);
593

    
594
        BufferedImage image = null;
595

    
596
        image = ToolsSwingLocator.getToolsSwingManager().createBufferedImage(buffer.getColumns(), buffer.getRows(),
597
            BufferedImage.TYPE_INT_ARGB);
598

    
599
        int hueBandIndex = colorInterpretation.getBand(ColorInterpretation.HUE_BAND);
600
        int saturationBandIndex = colorInterpretation.getBand(ColorInterpretation.SATURATION_BAND);
601
        int lightBandIndex = colorInterpretation.getBand(ColorInterpretation.LIGHTNESS_BAND);
602

    
603

    
604
        Band hueBand = byteBuffer.getBand(hueBandIndex);
605
        Band saturationBand = byteBuffer.getBand(saturationBandIndex);
606
        Band lightBand = byteBuffer.getBand(lightBandIndex);
607

    
608

    
609
        for (int i = 0; i < buffer.getRows(); i++) {
610
            for (int j = 0; j < buffer.getColumns(); j++) {
611
                Number hueValue = (Number) hueBand.get(i, j);
612
                Number saturationValue = (Number) saturationBand.get(i, j);
613
                Number lightValue = (Number) lightBand.get(i, j);
614

    
615
                Number[] rgbaValues=ColorUtils.fromHSLtoRGBA(hueValue.floatValue(), saturationValue.floatValue(), lightValue.floatValue());
616

    
617
                Integer alphaValue =rgbaValues[3].intValue();
618
                if (transparency != null) {
619
                    // Apply defined transparency ranges
620

    
621
                    alphaValue = alphaValue.byteValue() & 0xFF;
622
                    int newAlpha =
623
                        transparency.getTransparencyRangeAlpha(rgbaValues[0].byteValue(),
624
                            rgbaValues[1].byteValue(), rgbaValues[2].byteValue());
625
                    alphaValue = getNewAlpha(alphaValue.intValue(), newAlpha);
626

    
627
                    // Apply general transparency
628
                    int transparencyValue = transparency.getAlpha();
629
                    alphaValue = getNewAlpha(alphaValue.intValue(), transparencyValue);
630
                }
631

    
632
                if (filters != null) {
633
                    // TODO Apply filters
634
                }
635

    
636
                int intRGB = 0;
637
                intRGB = ((alphaValue.byteValue() & 0xFF) << 24) | // alpha
638
                    ((rgbaValues[0].byteValue() & 0xFF) << 16) | // red
639
                    ((rgbaValues[1].byteValue() & 0xFF) << 8) | // green
640
                    ((rgbaValues[2].byteValue() & 0xFF) << 0); // blue
641
                image.setRGB(j, i, intRGB);
642
            }
643
        }
644
        return image;
645
    }
646

    
647
    private Image drawCMYKBuffer(Graphics graphics, Buffer buffer,
648
        ColorInterpretation colorInterpretation,Transparency transparency,
649
        OperationList filters) throws BufferOperationException {
650

    
651
        Buffer byteBuffer = convertToByteBuffer(buffer);
652

    
653
        BufferedImage image = null;
654

    
655
        image = ToolsSwingLocator.getToolsSwingManager().createBufferedImage(buffer.getColumns(), buffer.getRows(),
656
            BufferedImage.TYPE_INT_ARGB);
657

    
658
        int cyanBandIndex = colorInterpretation.getBand(ColorInterpretation.CYAN_BAND);
659
        int magentaBandIndex = colorInterpretation.getBand(ColorInterpretation.MAGENTA_BAND);
660
        int yellowBandIndex = colorInterpretation.getBand(ColorInterpretation.YELLOW_BAND);
661
        int blackBandIndex = colorInterpretation.getBand(ColorInterpretation.BLACK_BAND);
662

    
663

    
664
        Band cyanBand = byteBuffer.getBand(cyanBandIndex);
665
        Band magentaBand = byteBuffer.getBand(magentaBandIndex);
666
        Band yellowBand = byteBuffer.getBand(yellowBandIndex);
667
        Band blackBand = byteBuffer.getBand(blackBandIndex);
668

    
669
        for (int i = 0; i < buffer.getRows(); i++) {
670
            for (int j = 0; j < buffer.getColumns(); j++) {
671
                Number cyanValue = (Number) cyanBand.get(i, j);
672
                Number magentaValue = (Number) magentaBand.get(i, j);
673
                Number yellowValue = (Number) yellowBand.get(i, j);
674
                Number blackValue = (Number) blackBand.get(i, j);
675

    
676

    
677

    
678
                Number[] rgbValues=ColorUtils.fromCMYKtoRGB(
679
                    cyanValue.floatValue(),
680
                    magentaValue.floatValue(),
681
                    yellowValue.floatValue(),
682
                    blackValue.floatValue()
683
                    );
684

    
685
                Integer alphaValue =255;
686
                if (transparency != null) {
687
                    // Apply defined transparency ranges
688

    
689
                    alphaValue = alphaValue.byteValue() & 0xFF;
690
                    int newAlpha =
691
                        transparency.getTransparencyRangeAlpha(rgbValues[0].byteValue(),
692
                            rgbValues[1].byteValue(), rgbValues[2].byteValue());
693
                    alphaValue = getNewAlpha(alphaValue.intValue(), newAlpha);
694

    
695
                    // Apply general transparency
696
                    int transparencyValue = transparency.getAlpha();
697
                    alphaValue = getNewAlpha(alphaValue.intValue(), transparencyValue);
698
                }
699

    
700
                if (filters != null) {
701
                    // TODO Apply filters
702
                }
703

    
704
                int intRGB = 0;
705
                intRGB = ((alphaValue.byteValue() & 0xFF) << 24) | // alpha
706
                    ((rgbValues[0].byteValue() & 0xFF) << 16) | // red
707
                    ((rgbValues[1].byteValue() & 0xFF) << 8) | // green
708
                    ((rgbValues[2].byteValue() & 0xFF) << 0); // blue
709
                image.setRGB(j, i, intRGB);
710
            }
711
        }
712
        return image;
713
    }
714

    
715
    private Image drawYCBCRBuffer(Graphics graphics, Buffer buffer,
716
        ColorInterpretation colorInterpretation,Transparency transparency,
717
        OperationList filters) throws BufferOperationException {
718

    
719
        Buffer byteBuffer = convertToByteBuffer(buffer);
720

    
721
        BufferedImage image = null;
722

    
723
        image = ToolsSwingLocator.getToolsSwingManager().createBufferedImage(buffer.getColumns(), buffer.getRows(),
724
            BufferedImage.TYPE_INT_ARGB);
725

    
726
        int yIndex = colorInterpretation.getBand(ColorInterpretation.YCBCR_Y_BAND);
727
        int cbBandIndex = colorInterpretation.getBand(ColorInterpretation.YCBCR_CB_BAND);
728
        int crBandIndex = colorInterpretation.getBand(ColorInterpretation.YCBCR_CR_BAND);
729

    
730

    
731
        Band yBand = byteBuffer.getBand(yIndex);
732
        Band cbBand = byteBuffer.getBand(cbBandIndex);
733
        Band crBand = byteBuffer.getBand(crBandIndex);
734

    
735
        for (int i = 0; i < buffer.getRows(); i++) {
736
            for (int j = 0; j < buffer.getColumns(); j++) {
737
                Number yValue = (Number) yBand.get(i, j);
738
                Number cbValue = (Number) cbBand.get(i, j);
739
                Number crValue = (Number) crBand.get(i, j);
740

    
741
                Number[] rgbValues=ColorUtils.fromYCBCRtoRGB(
742
                    yValue.floatValue(),
743
                    cbValue.floatValue(),
744
                    crValue.floatValue()
745
                    );
746

    
747
                Integer alphaValue =255;
748
                if (transparency != null) {
749
                    // Apply defined transparency ranges
750

    
751
                    alphaValue = alphaValue.byteValue() & 0xFF;
752
                    int newAlpha =
753
                        transparency.getTransparencyRangeAlpha(rgbValues[0].byteValue(),
754
                            rgbValues[1].byteValue(), rgbValues[2].byteValue());
755
                    alphaValue = getNewAlpha(alphaValue.intValue(), newAlpha);
756

    
757
                    // Apply general transparency
758
                    int transparencyValue = transparency.getAlpha();
759
                    alphaValue = getNewAlpha(alphaValue.intValue(), transparencyValue);
760
                }
761

    
762
                if (filters != null) {
763
                    // TODO Apply filters
764
                }
765

    
766
                int intRGB = 0;
767
                intRGB = ((alphaValue.byteValue() & 0xFF) << 24) | // alpha
768
                    ((rgbValues[0].byteValue() & 0xFF) << 16) | // red
769
                    ((rgbValues[1].byteValue() & 0xFF) << 8) | // green
770
                    ((rgbValues[2].byteValue() & 0xFF) << 0); // blue
771
                image.setRGB(j, i, intRGB);
772
            }
773
        }
774
        return image;
775
    }
776

    
777
    /**
778
     * Method to draw gray buffers
779
     * @param graphics
780
     * @param byteBuffer
781
     * @param filters
782
     * @return
783
     * @throws OperationException
784
     */
785
    private Image drawGrayBuffer(Graphics graphics, Buffer buffer, ColorInterpretation colorInterpretation, Transparency transparency, OperationList filters) throws BufferOperationException {
786

    
787
        BufferedImage image = null;
788
        Buffer byteBuffer = convertToByteBuffer(buffer);
789

    
790
        image = ToolsSwingLocator.getToolsSwingManager().createBufferedImage(byteBuffer.getColumns(), byteBuffer.getRows(),
791
            BufferedImage.TYPE_INT_ARGB);
792

    
793
        Band grayBand = byteBuffer.getBand(colorInterpretation.getBand(ColorInterpretation.GRAY_BAND));
794

    
795
        for (int i = 0; i < byteBuffer.getRows(); i++) {
796
            for (int j = 0; j < byteBuffer.getColumns(); j++) {
797
                int grayByteValue = 0;
798
                int alphaByteValue = (byte)255;
799
                Number grayValue = (Number) grayBand.get(i, j);
800
                NoData noData = grayBand.getNoData();
801
                if(noData != null){
802
                    if(grayValue.equals(noData.getValue())){
803
                        alphaByteValue = 0;
804
                        grayByteValue = 0;
805
                    } else {
806
                        alphaByteValue = 255;
807
                        grayByteValue = grayValue.byteValue();
808
                    }
809
                } else {
810
                    grayByteValue = grayValue.byteValue();
811
                }
812

    
813
                if (alphaByteValue != 0 && transparency != null) {
814
                    // Apply defined transparency ranges
815

    
816
//                    alphaByteValue = alphaValue.byteValue() & 0xFF;
817
                    int newAlpha = transparency.getTransparencyRangeAlpha(grayByteValue, grayByteValue, grayByteValue);
818
                    alphaByteValue = getNewAlpha(alphaByteValue, newAlpha);
819

    
820
                    // Apply general transparency
821
                    int transparencyValue = transparency.getAlpha();
822
                    alphaByteValue = getNewAlpha(alphaByteValue, transparencyValue);
823
                }
824

    
825
                if (filters != null) {
826
                    // TODO Apply filters
827
                }
828

    
829
                int intARGB = (((byte)alphaByteValue & 0xFF) << 24) | // alpha
830
                    (((byte)grayByteValue & 0xFF)<< 16) | // red
831
                    (((byte)grayByteValue & 0xFF)<< 8) | // green
832
                    (((byte)grayByteValue & 0xFF)); // blue
833

    
834
                image.setRGB(j, i, intARGB);
835
            }
836
        }
837
        return image;
838
    }
839

    
840
    private Buffer convertToByteBuffer(Buffer buffer) throws BufferOperationException {
841
        int[] types = buffer.getBandTypes();
842
        boolean mustConvert = false;
843
        List<Integer> bandsToProcess = new ArrayList<Integer>();
844
        for (int i = 0; i < types.length; i++) {
845
            if(types[i]!=BufferManager.TYPE_BYTE){
846
                bandsToProcess.add(i);
847
                mustConvert = true;
848
//                break;
849
            }
850
        }
851
        if(mustConvert){
852
            OperationManager operationManager = BufferLocator.getOperationManager();
853
            DynObject parameters = operationManager.createOperationParameters(SpecifiedBandsOperation.LINEAR_STRETCH_ENHANCEMENT_NAME);
854
            parameters.setDynValue(AbstractSpecifiedBandsOperation.BANDS_TO_PROCESS_PARAM, bandsToProcess);
855
            return operationManager.execute(SpecifiedBandsOperation.LINEAR_STRETCH_ENHANCEMENT_NAME, buffer, parameters);
856
        }
857
        return buffer;
858
    }
859

    
860
    private Image drawPaletteBuffer(Graphics graphics, Buffer buffer, ColorInterpretation colorInterpretation,
861
        Transparency transparency, OperationList filters) {
862

    
863
        BufferedImage image = ToolsSwingLocator.getToolsSwingManager().createBufferedImage(buffer.getColumns(), buffer.getRows(),
864
            BufferedImage.TYPE_INT_ARGB);
865

    
866
        for (int i = 0; i < buffer.getRows(); i++) {
867
            for (int j = 0; j < buffer.getColumns(); j++) {
868

    
869
                Object value = buffer.getBand(colorInterpretation.getPaletteBand()).get(i, j);
870
                byte[] rgba = colorInterpretation.getPalette().getRGBA(value);
871

    
872
                if (transparency != null) {
873
                    // Apply defined transparency ranges
874
                    int alpha = rgba[3] & 0xFF;
875
                    int newAlpha =
876
                        transparency.getTransparencyRangeAlpha(rgba[0], rgba[1], rgba[2]);
877
                    alpha = getNewAlpha(alpha, newAlpha);
878

    
879
                    // Apply general transparency
880
                    int transparencyValue = transparency.getAlpha();
881
                    rgba[3] = (byte) getNewAlpha(alpha, transparencyValue);
882
                }
883

    
884
                if (filters != null) {
885
                    // TODO Apply filters
886
                }
887

    
888
                int intARGB = ((rgba[3] & 0xFF) << 24) | // alpha
889
                    ((rgba[0] & 0xFF) << 16) | // red
890
                    ((rgba[1] & 0xFF) << 8) | // green
891
                    ((rgba[2] & 0xFF) << 0); // blue
892

    
893
                image.setRGB(j, i, intARGB);
894
            }
895
        }
896
        return image;
897
    }
898

    
899
    private int getNewAlpha(int alpha, int newAlpha) {
900
        return (int) Math.round(alpha * (newAlpha / 255d));
901
    }
902

    
903
    @Override
904
    public ColorInterpretation getColorInterpretation() {
905
        return this.colorInterpretation;
906
    }
907

    
908
    @Override
909
    public void setColorInterpretation(ColorInterpretation colorInterpretation) {
910
        if (this.colorInterpretation != null) {
911
            this.colorInterpretation.deleteObserver(this);
912
        }
913
        this.colorInterpretation = colorInterpretation;
914
        this.colorInterpretation.addObserver(this);
915
    }
916

    
917
    @Override
918
    public OperationList getFilters() {
919
        if(this.filters == null){
920
            BufferManager bufferManager = BufferLocator.getBufferManager();
921
            this.filters = ((OperationManager)bufferManager).createOperationList();
922
        }
923
        return this.filters;
924
    }
925

    
926
    @Override
927
    public void setFilters(OperationList filterList) {
928
        this.filters = filterList;
929
    }
930

    
931
    /**
932
     *
933
     */
934
    public static void registerPersistence() {
935
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
936
        DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
937
        if (definition == null) {
938
            definition =
939
                manager.addDefinition(DefaultRasterLegend.class, PERSISTENT_NAME,
940
                    PERSISTENT_DESCRIPTION, null, null);
941
            definition.addDynFieldObject(COLOR_INTERPRETATION_PERSISTENCE_FIELD).setMandatory(false)
942
                .setClassOfValue(ColorInterpretation.class);
943
            definition.addDynFieldObject(FILTERS_PERSISTENCE_FIELD).setMandatory(false)
944
                .setClassOfValue(OperationList.class);
945
        }
946
    }
947

    
948
    @Override
949
    public void saveToState(PersistentState state) throws PersistenceException {
950
        state.set(COLOR_INTERPRETATION_PERSISTENCE_FIELD, this.getColorInterpretation());
951
        state.set(FILTERS_PERSISTENCE_FIELD, (Persistent)this.getFilters());
952
    }
953

    
954
    @Override
955
    public void loadFromState(PersistentState state) throws PersistenceException {
956
        this.setColorInterpretation((ColorInterpretation) state
957
            .get(COLOR_INTERPRETATION_PERSISTENCE_FIELD));
958
        this.setFilters((OperationList) state.get(FILTERS_PERSISTENCE_FIELD));
959
    }
960

    
961
    @Override
962
    public void setTransparency(Transparency transparency) {
963
        this.transparency = transparency;
964
    }
965

    
966
    @Override
967
    public Transparency getTransparency() {
968
        return this.transparency;
969
    }
970

    
971
    @Override
972
    public ISymbol getDefaultSymbol() {
973
        return null;
974
    }
975

    
976
    @Override
977
    public Object clone() throws CloneNotSupportedException {
978
        DefaultRasterLegend cloned = (DefaultRasterLegend) super.clone();
979

    
980
        ColorInterpretation clonedColorInterpretation = (ColorInterpretation)this.getColorInterpretation().clone();
981
        cloned.setColorInterpretation(clonedColorInterpretation);
982
        //FIXME:
983
//        cloned.setTransparency((Transparency)this.getTransparency().clone());
984
//        cloned.setFilters(getFilters());
985

    
986
        return cloned;
987
    }
988

    
989
    @Override
990
    public ILegend cloneLegend() {
991
        try {
992
            return (RasterLegend)this.clone();
993
        } catch (Exception e) {
994
            throw new RuntimeException("Can't clone the legend", e);
995
        }
996
    }
997

    
998

    
999
    @Override
1000
    public void fireDefaultSymbolChangedEvent(SymbolLegendEvent event) {
1001

    
1002
        for (int i = 0; i < listeners.size(); i++) {
1003
            ((LegendContentsChangedListener) listeners.get(i))
1004
                    .symbolChanged(event);
1005
        }
1006
    }
1007

    
1008
    @Override
1009
    public LegendContentsChangedListener[] getListeners() {
1010
        return (LegendContentsChangedListener[]) listeners
1011
                .toArray(new LegendContentsChangedListener[listeners.size()]);
1012
    }
1013

    
1014

    
1015

    
1016
    @Override
1017
    public void setTransparentNoData(boolean noDataTransparent) {
1018
        this.transparentNoData=noDataTransparent;
1019

    
1020
    }
1021

    
1022
    @Override
1023
    public boolean areTransparentNoData() {
1024
        return this.transparentNoData;
1025
    }
1026

    
1027
    @Override
1028
    public void update(Observable observable, Object notification) {
1029
        if (notification instanceof ColorInterpretationNotification) {
1030
            String type = ((ColorInterpretationNotification) notification).getType();
1031
            if(type.equals(ColorInterpretationNotification.CHANGED_COLOR_INTERPRETATION_VALUE)
1032
               || type.equals(ColorInterpretationNotification.ADDED_COLOR_INTERPRETATION)
1033
               || type.equals(ColorInterpretationNotification.COPIED_FROM_COLOR_INTERPRETATION)){
1034
            fireColorinterpretationChangedEvent(new ChangeColorInterpretationEvent(
1035
                (String[])((ColorInterpretationNotification) notification).getValue(0),
1036
                (String[])((ColorInterpretationNotification) notification).getValue(1)));
1037
            }
1038
            if (type.equals(ColorInterpretationNotification.SETTED_PALETTE)) {
1039
                fireColorinterpretationChangedEvent(new ChangePaletteEvent(
1040
                    (ColorTable) ((ColorInterpretationNotification) notification).getValue(0),
1041
                    (ColorTable) ((ColorInterpretationNotification) notification).getValue(1)));
1042
            }
1043
            if (type.equals(ColorInterpretationNotification.CHANGED_PALETTE)) {
1044
                fireColorinterpretationChangedEvent(new ChangePaletteEvent(
1045
                    (ColorTable) ((ColorInterpretationNotification) notification).getValue(0),
1046
                    (ColorTable) ((ColorInterpretationNotification) notification).getValue(0)));
1047
            }
1048

    
1049
            if (type.equals(ColorInterpretationNotification.SETTED_PALETTE_BAND)) {
1050
                fireColorinterpretationChangedEvent(new ChangePaletteBandEvent(
1051
                    (int) ((ColorInterpretationNotification) notification).getValue(0),
1052
                    (int) ((ColorInterpretationNotification) notification).getValue(1)));
1053
            }
1054
        }
1055
    }
1056

    
1057
    public void fireColorinterpretationChangedEvent(RasterLegendEvent event) {
1058

    
1059
        for (int i = 0; i < listeners.size(); i++) {
1060
            ((RasterLegendChangedListener) listeners.get(i)).colorInterpretationChanged(event);
1061
        }
1062
    }
1063

    
1064
    @Override
1065
    public void addLegendListener(LegendContentsChangedListener listener) {
1066
        if(listener instanceof RasterLegendChangedListener){
1067
            addLegendListener((RasterLegendChangedListener)listener);
1068
            return;
1069
        }
1070
        throw new UnsupportedOperationException("Raster layer can't be listened by a no RasterLegendChangedListener");
1071

    
1072
    }
1073

    
1074
    @Override
1075
    public void removeLegendListener(LegendContentsChangedListener listener) {
1076
        if(listener instanceof RasterLegendChangedListener){
1077
            removeLegendListener((RasterLegendChangedListener)listener);
1078
            return;
1079
        }
1080
        throw new UnsupportedOperationException("Raster layer can't be listened by a no RasterLegendChangedListener");
1081

    
1082
    }
1083

    
1084
    private void addLegendListener(RasterLegendChangedListener listener) {
1085
        if (listener != null && !listeners.contains(listener))
1086
            listeners.add(listener);
1087
    }
1088

    
1089
    private void removeLegendListener(RasterLegendChangedListener listener) {
1090
        listeners.remove(listener);
1091
    }
1092

    
1093
    @Override
1094
    public void addColorTableOperation(ColorInterpretation colorInterpretation, int index) {
1095

    
1096
        removeOperationIfExists(SpecifiedBandsOperation.LINEAR_STRETCH_ENHANCEMENT_NAME);
1097
        removeOperationIfExists(ColoredOperation.COLOR_TABLE_OPERATION_NAME);
1098

    
1099
        OperationManager operationManager = BufferLocator.getOperationManager();
1100
        Operation colorTableOperation = operationManager.createOperation(ColoredOperation.COLOR_TABLE_OPERATION_NAME);
1101
        DynObject colorTableOperationParameters = operationManager.createOperationParameters(ColoredOperation.COLOR_TABLE_OPERATION_NAME);
1102
        colorTableOperationParameters.setDynValue(ColoredOperation.COLOR_INTERPRETATION_PARAM, colorInterpretation);
1103
        colorTableOperationParameters.setDynValue(AbstractOperation.COPY_UNPROCESSED_BANDS_PARAM, true);
1104
        OperationListEntry colorTableEntry = operationManager.createOperationListEntry(colorTableOperation, colorTableOperationParameters);
1105
        getFilters().add(index, colorTableEntry);
1106
    }
1107

    
1108
    @Override
1109
    public void addLinearStretchEnhancementOperationIfNeeded(ColorInterpretation colorInterpretation,
1110
        RasterStore store, int index) {
1111

    
1112
        removeOperationIfExists(SpecifiedBandsOperation.LINEAR_STRETCH_ENHANCEMENT_NAME);
1113
        removeOperationIfExists(ColoredOperation.COLOR_TABLE_OPERATION_NAME);
1114

    
1115
        RasterStore rasterStore = (RasterStore) store;
1116

    
1117
        OperationManager operationManager = BufferLocator.getOperationManager();
1118
        if ((!colorInterpretation.isPalette())
1119
            && (colorInterpretation.hasAnyColorInterpretationBand() || colorInterpretation.hasAlphaBand() || colorInterpretation
1120
                .hasAnyGrayBand())) {
1121

    
1122
            List<Integer> bandsToProcess = new ArrayList<Integer>();
1123
            for (int i = 0; i < rasterStore.getBands(); i++) {
1124
                if ((colorInterpretation.isColorInterpretation(i) || colorInterpretation.isAlphaInterpretation(i) || colorInterpretation
1125
                    .isGrayInterpretation(i))
1126
                    && (rasterStore.getBandDescriptor(i).getDataType() != BufferManager.TYPE_BYTE)) {
1127
                    bandsToProcess.add(i);
1128
                }
1129
            }
1130

    
1131
            if (!bandsToProcess.isEmpty()) {
1132
                Operation linearStretchEnhancementOperation = operationManager.createOperation(SpecifiedBandsOperation.LINEAR_STRETCH_ENHANCEMENT_NAME);
1133
                DynObject linearStretchEnhancementOperationParameters =
1134
                    operationManager.createOperationParameters(SpecifiedBandsOperation.LINEAR_STRETCH_ENHANCEMENT_NAME);
1135
                linearStretchEnhancementOperationParameters.setDynValue(
1136
                    AbstractSpecifiedBandsOperation.BANDS_TO_PROCESS_PARAM, bandsToProcess);
1137
                OperationListEntry colorTableEntry =
1138
                    ((OperationManager) operationManager).createOperationListEntry(linearStretchEnhancementOperation,
1139
                        linearStretchEnhancementOperationParameters);
1140
                getFilters().add(index, colorTableEntry);
1141
            }
1142
        }
1143
    }
1144

    
1145
    @Override
1146
    public void removeOperationIfExists(String name) {
1147
        int removed = 0;
1148
        int size = getFilters().size();
1149
        for (Iterator<OperationListEntry> iterator = getFilters().iterator(); iterator.hasNext();) {
1150
            OperationListEntry entry = (OperationListEntry) iterator.next();
1151
            Operation operation = entry.getOperation();
1152
            if (operation.getFactory().getName().equals(name)) {
1153
                iterator.remove();
1154
                removed++;
1155
            }
1156
        }
1157
        if(getFilters().size()!=size-removed){
1158
            LOG.warn("NO SE HAN ELIMINADO CORRECTAMENTE LAS ENTRADAS DE LA OPERATION_LIST.");
1159
        }
1160
    }
1161

    
1162
}