Statistics
| Revision:

root / trunk / extensions / extRasterTools-SE / src / org / gvsig / fmap / raster / layers / FLyrRasterSE.java @ 22475

History | View | Annotate | Download (58.1 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2007 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 */
19
package org.gvsig.fmap.raster.layers;
20

    
21
import java.awt.Dimension;
22
import java.awt.Graphics2D;
23
import java.awt.Point;
24
import java.awt.Rectangle;
25
import java.awt.geom.AffineTransform;
26
import java.awt.geom.NoninvertibleTransformException;
27
import java.awt.geom.Point2D;
28
import java.awt.geom.Rectangle2D;
29
import java.awt.image.BufferedImage;
30
import java.io.File;
31
import java.io.IOException;
32
import java.lang.reflect.Constructor;
33
import java.lang.reflect.InvocationTargetException;
34
import java.util.ArrayList;
35
import java.util.HashMap;
36

    
37
import javax.print.attribute.PrintRequestAttributeSet;
38
import javax.swing.ImageIcon;
39

    
40
import org.apache.log4j.Logger;
41
import org.cresques.cts.IProjection;
42
import org.gvsig.fmap.raster.legend.ColorTableLegend;
43
import org.gvsig.raster.RasterLibrary;
44
import org.gvsig.raster.buffer.BufferFactory;
45
import org.gvsig.raster.dataset.CompositeDataset;
46
import org.gvsig.raster.dataset.FileNotOpenException;
47
import org.gvsig.raster.dataset.IBuffer;
48
import org.gvsig.raster.dataset.IRasterDataSource;
49
import org.gvsig.raster.dataset.InvalidSetViewException;
50
import org.gvsig.raster.dataset.MosaicNotValidException;
51
import org.gvsig.raster.dataset.MultiRasterDataset;
52
import org.gvsig.raster.dataset.NotSupportedExtensionException;
53
import org.gvsig.raster.dataset.RasterDataset;
54
import org.gvsig.raster.dataset.io.RasterDriverException;
55
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
56
import org.gvsig.raster.dataset.properties.DatasetMetadata;
57
import org.gvsig.raster.dataset.serializer.RmfSerializerException;
58
import org.gvsig.raster.datastruct.ColorTable;
59
import org.gvsig.raster.datastruct.Extent;
60
import org.gvsig.raster.datastruct.ViewPortData;
61
import org.gvsig.raster.datastruct.persistence.ColorTableLibraryPersistence;
62
import org.gvsig.raster.grid.Grid;
63
import org.gvsig.raster.grid.GridException;
64
import org.gvsig.raster.grid.GridPalette;
65
import org.gvsig.raster.grid.GridTransparency;
66
import org.gvsig.raster.grid.filter.FilterTypeException;
67
import org.gvsig.raster.grid.filter.RasterFilterList;
68
import org.gvsig.raster.grid.filter.RasterFilterListManager;
69
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
70
import org.gvsig.raster.grid.filter.enhancement.EnhancementStretchListManager;
71
import org.gvsig.raster.grid.filter.enhancement.LinearStretchParams;
72
import org.gvsig.raster.grid.render.Rendering;
73
import org.gvsig.raster.hierarchy.IRasterDataset;
74
import org.gvsig.raster.hierarchy.IRasterOperations;
75
import org.gvsig.raster.hierarchy.IRasterProperties;
76
import org.gvsig.raster.hierarchy.IStatistics;
77
import org.gvsig.raster.process.RasterTask;
78
import org.gvsig.raster.process.RasterTaskQueue;
79
import org.gvsig.raster.projection.CRS;
80
import org.gvsig.raster.util.ColorConversion;
81
import org.gvsig.raster.util.Historical;
82
import org.gvsig.raster.util.MathUtils;
83
import org.gvsig.raster.util.RasterToolsUtil;
84

    
85
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
86
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
87
import com.iver.cit.gvsig.exceptions.layers.ReloadLayerException;
88
import com.iver.cit.gvsig.fmap.ViewPort;
89
import com.iver.cit.gvsig.fmap.core.FShape;
90
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
91
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
92
import com.iver.cit.gvsig.fmap.layers.FLayer;
93
import com.iver.cit.gvsig.fmap.layers.FLyrDefault;
94
import com.iver.cit.gvsig.fmap.layers.LayerChangeSupport;
95
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
96
import com.iver.cit.gvsig.fmap.layers.LayerListener;
97
import com.iver.cit.gvsig.fmap.layers.Tiling;
98
import com.iver.cit.gvsig.fmap.layers.XMLException;
99
import com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable;
100
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
101
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
102
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
103
import com.iver.cit.gvsig.fmap.rendering.ILegend;
104
import com.iver.cit.gvsig.fmap.rendering.LegendListener;
105
import com.iver.utiles.NotExistInXMLEntity;
106
import com.iver.utiles.XMLEntity;
107
import com.iver.utiles.swing.threads.Cancellable;
108
/**
109
 * Capa raster
110
 * @author Nacho Brodin (nachobrodin@gmail.com)
111
 */
112
public class FLyrRasterSE extends FLyrDefault implements IRasterProperties, IRasterDataset, InfoByPoint, Classifiable, IRasterOperations, IRasterLayerActions, ILayerState {
113
        private boolean             mustTileDraw        = false;
114
        private boolean             mustTilePrint       = true;
115
        private int                 maxTileDrawWidth    = 200;
116
        private int                 maxTileDrawHeight   = 200;
117
        private int                 maxTilePrintWidth   = 1500;
118
        private int                 maxTilePrintHeight  = 1500;
119
        protected IStatusRaster     status              = null;
120
        private boolean             firstLoad           = false;
121
        private boolean             removeRasterFlag    = true;
122
        private Object              params              = null;
123
        protected IRasterDataSource dataset             = null;
124
        protected Rendering         render              = null;
125
        protected BufferFactory     bufferFactory       = null;
126
        private int                 posX                = 0;
127
        private int                 posY                = 0;
128
        private double              posXWC              = 0;
129
        private int                 posYWC              = 0;
130
        private int                 r                   = 0;
131
        private int                 g                   = 0;
132
        private int                 b                   = 0;
133
        private LayerChangeSupport  layerChangeSupport  = new LayerChangeSupport();
134
        private FLyrState           state               = new FLyrState();
135
        private ArrayList           filterArguments     = null;
136
        protected ILegend           lastLegend          = null;
137
        private ArrayList           rois                = null;
138
        private RasterDrawStrategy  strategy            = null;
139
        static private IConfiguration configuration       = new DefaultLayerConfiguration();
140
        
141
        private BufferedImage         image               = null;
142

    
143
        /**
144
         * Tipo de valor no data asociado a la capa.
145
         * Sirve para diferenciar los estados seleccionados por el usuario. Siendo
146
         * estos 'Sin Valor NoData', 'NoData de Capa'(Por defecto) y 'Personalizado'
147
         */
148
        private int noDataType = RasterLibrary.NODATATYPE_LAYER;
149

    
150
        /**
151
         * Lista de transformaciones afines que son aplicadas. Esta lista es
152
         * simplemente un historico que no se utiliza. Es posible utilizarlo para
153
         * recuperar transformaciones anteriores.
154
         */
155
        private Historical          affineTransformList = new Historical();
156

    
157
        static {
158
                 RasterLibrary.wakeUp();
159
        }
160

    
161
        /**
162
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
163
         * @param layerName Nombre de la capa..
164
         * @param params Par?metros de carga del formato. El caso m?s simple es la ruta de la capa en disco.
165
         * @param d RasterDriver.
166
         * @param f Fichero.
167
         * @param proj Proyecci?n.
168
         * @return Nueva capa de tipo raster.
169
         * @throws DriverIOException
170
         */
171
        public static FLyrRasterSE createLayer(String layerName, Object params,
172
                        IProjection proj) throws LoadLayerException {
173
                FLyrRasterSE capa = new FLyrRasterSE();
174
                capa.setLoadParams(params);
175
                capa.setName(layerName);
176
                capa.setProjection(proj);
177
                capa.load();
178
                return capa;
179
        }
180

    
181
        /**
182
         * Asigna los par?metros para la carga de la capa
183
         * @param param Par?metros.
184
         */
185
        public void setLoadParams(Object param){
186
                this.params = param;
187

    
188
                //Si la capa tiene nombre acivamos el estado awake
189
                if(params != null && getName() != null) {
190
                        try {
191
                                enableAwake();
192
                        } catch (NotAvailableStateException e) {
193
                                Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
194
                        }
195
                }
196
        }
197

    
198
        /**
199
         * Obtiene los par?metros para la carga de la capa
200
         * @return param Par?metros.
201
         */
202
        public Object getLoadParams() {
203
                return params;
204
        }
205

    
206
        /*
207
         * (non-Javadoc)
208
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setName(java.lang.String)
209
         */
210
        public void setName(String name) {
211
                super.setName(name);
212

    
213
                //Si la capa tiene nombre acivamos el estado awake
214
                if(getLoadParams() != null && name != null) {
215
                        try {
216
                                if(isClosed())
217
                                        enableAwake();
218
                        } catch (NotAvailableStateException e) {
219
                                Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
220
                        }
221
                }
222
        }
223

    
224
        /*
225
         * (non-Javadoc)
226
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#wakeUp()
227
         */
228
        public void wakeUp(){
229
                if (bufferFactory == null) {
230
                        try {
231
                                reload();
232
                        } catch (ReloadLayerException e) {
233
                                // No se ha podido recuperar la capa con exito
234
                        }
235
                }
236
        }
237

    
238
        /**
239
         * Asignar el estado del raster
240
         * @param status
241
         */
242
        public void setStatus(IStatusRaster status){
243
                this.status = status;
244
        }
245

    
246
        /**
247
         * Obtiene el estado del raster
248
         * @return
249
         */
250
        public IStatusRaster getStatus(){
251
                return this.status;
252
        }
253

    
254
        /*
255
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
256
         */
257
        public void load() throws LoadLayerException {
258
                if(isStopped())
259
                        return;
260

    
261
                enableStopped(); //Paramos la capa mientras se hace un load
262

    
263
                String fName = null;
264
                int test = -1;
265
                if (params != null && params instanceof File) {
266
                        fName = ((File) params).getAbsolutePath();
267
                        test = fName.indexOf("ecwp:");
268
                }
269

    
270
                if (test != -1) {
271
                        String urlECW = fName.substring(test + 6);
272
                        fName = "ecwp://" + urlECW;
273
                        System.err.println(test + " " + fName);
274
                }
275

    
276
                try {
277
                        if(params instanceof String[][]) {
278
                                String[][] files = (String[][])params;
279
                                MultiRasterDataset[][] dt = new MultiRasterDataset[files.length][files[0].length];
280
                                for (int i = 0; i < files.length; i++)
281
                                        for (int j = 0; j < files[i].length; j++)
282
                                                dt[i][j] = MultiRasterDataset.open(getProjection(), files[i][j]);
283
                                dataset = new CompositeDataset(dt);
284
                        } else if (params == null || params instanceof File) {
285
                                if(fName != null)
286
                                        dataset = MultiRasterDataset.open(getProjection(), fName);
287
                        } else
288
                                dataset = MultiRasterDataset.open(getProjection(), params);
289
                } catch (NotSupportedExtensionException e) {
290
                        throw new LoadLayerException("Formato no valido", e);
291
                } catch (MosaicNotValidException e) {
292
                        throw new LoadLayerException("Error en el mosaico", e);
293
                } catch (Exception e) {
294
                        throw new LoadLayerException("No existe la capa.", e);
295
                }
296
                if(dataset != null)
297
                        this.init();
298
        }
299

    
300
        /**
301
         * Acciones de inicializaci?n despu?s de que la fuente de datos
302
         * de la capa est? asignada. El tipo de fuente de datos es variable
303
         * puede ser MultiRasterDataset, CompositeDataset u otras que existan e
304
         * implementen IRasterDatasource.
305
         */
306
        public void init() throws LoadLayerException {
307
                if (dataset == null)
308
                        throw new LoadLayerException("Formato no valido", new IOException());
309
                                
310
                bufferFactory = new BufferFactory(dataset);
311
                render = new Rendering(bufferFactory);
312
                initFilters();
313

    
314
                //Inicializaci?n del historico de transformaciones
315
                affineTransformList.clear();
316
                affineTransformList.add(this.getAffineTransform());
317
                try {
318
                        enableOpen();
319
                } catch (NotAvailableStateException e) {
320
                        Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Awake=" + isAwake(), e);
321
                }
322
        }
323

    
324
        /**
325
         * Obtiene la proyecci?n del fichero.
326
         * @return IProjection
327
         */
328
        public IProjection readProjection() {
329
                try {
330
                        CRS.setCRSFactory(CRSFactory.cp);
331
                        return CRS.convertWktToIProjection(dataset.getWktProjection());
332
                } catch (RasterDriverException e) {
333
                        Logger.getLogger(getClass().getName()).debug("Problemas accediendo a getWktProjection. Driver no inicializado", e);
334
                }
335
                return null;
336
        }
337
        
338
        /**
339
         * Crea el objeto renderizador de raster
340
         * @return Rendering
341
         */
342
        public Rendering getRender() {
343
                if (render == null)
344
                        render = new Rendering(bufferFactory);
345
                return render;
346
        }
347
        
348
        /**
349
         * Aplica los filtros noData al layer
350
         * @param rasterSE
351
         * @param filterManager
352
         */
353
        public void applyNoData() {
354
                Boolean noDataEnabled = configuration.getValueBoolean("nodata_transparency_enabled", Boolean.FALSE);
355
                if (noDataEnabled.booleanValue() && getDataSource().isNoDataEnabled()) {
356
                        noDataType = RasterLibrary.NODATATYPE_LAYER;
357
                        Double noDataValue = Double.valueOf(getNoDataValue());
358
                        getDataSource().getTransparencyFilesStatus().setNoData(noDataValue.doubleValue());
359
                } else {
360
                        getDataSource().getTransparencyFilesStatus().activeNoData(false);
361
                        noDataType = RasterLibrary.NODATATYPE_DISABLED;
362
                }
363
        }
364

    
365
        /**
366
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
367
         */
368
        private void initFilters() {
369
                RasterFilterList filterList = new RasterFilterList();
370
                filterList.addEnvParam("IStatistics", getDataSource().getStatistics());
371
                filterList.addEnvParam("MultiRasterDataset", getDataSource());
372
                
373
                getDataSource().resetNoDataValue();
374
                applyNoData();
375
                GridTransparency gridTransparency = new GridTransparency(getDataSource().getTransparencyFilesStatus());
376

    
377
                filterList.setInitDataType(getDataType()[0]);
378
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
379

    
380
                try {
381
                        if (this.getDataSource().getColorTables()[0] != null) {
382
                                GridPalette p = new GridPalette(getDataSource().getColorTables()[0]);
383
                                setLastLegend(p);
384
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
385
                                ctm.addColorTableFilter(p);
386
                        } else {
387
                                if (getDataType()[0] != IBuffer.TYPE_BYTE) {
388
                                        loadEnhancedOrColorTable(filterManager);
389
                                }
390
                        }
391

    
392
                        getRender().setFilterList(filterList);
393
                        // Inicializo la transparencia para el render
394
                        getRender().setLastTransparency(gridTransparency);
395
                } catch (FilterTypeException e) {
396
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
397
                        RasterToolsUtil.debug("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
398
                }
399
        }
400

    
401
        /**
402
         * Mira la configuracion para saber si debe cargar un realce o una tabla
403
         * de color por defecto
404
         * @param filterManager
405
         * @throws FilterTypeException
406
         */
407
        private void loadEnhancedOrColorTable(RasterFilterListManager filterManager) throws FilterTypeException {
408
                String colorTableName = configuration.getValueString("loadlayer_usecolortable", (String) null);
409

    
410
                String palettesPath = System.getProperty("user.home") +
411
                        File.separator +
412
                        "gvSIG" + // PluginServices.getArguments()[0] +
413
                        File.separator + "colortable";
414

    
415
                IStatistics stats = getDataSource().getStatistics();
416

    
417
                if (colorTableName != null) {
418
                        try {
419
                                stats.calcFullStatistics();
420
                                if (getBandCount() == 1) {
421
                                        ArrayList fileList = ColorTableLibraryPersistence.getPaletteFileList(palettesPath);
422
                                        for (int i = 0; i < fileList.size(); i++) {
423
                                                ArrayList paletteItems = new ArrayList();
424
                                                String paletteName = ColorTableLibraryPersistence.loadPalette(palettesPath, (String) fileList.get(i), paletteItems);
425
                                                if (paletteName.equals(colorTableName)) {
426
                                                        if (paletteItems.size() <= 0)
427
                                                                continue;
428

    
429
                                                        ColorTable colorTable = new ColorTable();
430
                                                        colorTable.setName(paletteName);
431
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
432
                                                        colorTable.setInterpolated(true);
433

    
434
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
435

    
436
                                                        GridPalette p = new GridPalette(colorTable);
437
                                                        setLastLegend(p);
438

    
439
                                                        ColorTableListManager ctm = new ColorTableListManager(filterManager);
440
                                                        ctm.addColorTableFilter(p);
441
                                                        return;
442
                                                }
443
                                        }
444
                                }
445
                        } catch (FileNotOpenException e) {
446
                                // No podemos aplicar el filtro
447
                        } catch (RasterDriverException e) {
448
                                // No podemos aplicar el filtro
449
                        } catch (InterruptedException e) {
450
                                // El usuario ha cancelado el proceso
451
                        }
452
                }
453

    
454
                /*EnhancementListManager elm = new EnhancementListManager(filterManager);
455
                elm.addEnhancedFilter(false, stats, 0.0, getRender().getRenderBands());*/
456
                
457
                EnhancementStretchListManager elm = new EnhancementStretchListManager(filterManager);
458
                try {
459
                        elm.addEnhancedStretchFilter(LinearStretchParams.createStandardParam(getRenderBands(), 0.0, stats, false), 
460
                                                                                stats, 
461
                                                                                getRender().getRenderBands(), 
462
                                                                                false);
463
                } catch (FileNotOpenException e) {
464
                        //No podemos aplicar el filtro
465
                } catch (RasterDriverException e) {
466
                        //No podemos aplicar el filtro
467
                }
468
        }
469

    
470
        /**
471
         * Devuelve si es reproyectable o no la capa
472
         * @return
473
         */
474
        public boolean isReproyectable() {
475
                if (dataset == null)
476
                        return false;
477

    
478
                int nFiles = dataset.getDatasetCount();
479
                for (int i = 0; i < nFiles; i++)
480
                        if (!dataset.getDataset(i)[0].isReproyectable())
481
                                return false;
482
                return true;
483
        }
484
        
485
        /**
486
         * @throws ReadDriverException
487
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
488
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
489
         *                 com.iver.utiles.swing.threads.Cancellable)
490
         */
491
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadDriverException {
492
                this.image = image;
493
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
494
                task.setEvent(null);
495

    
496
                try {
497
                        if (!isOpen())
498
                                return;
499

    
500
                        enableStopped();
501
                        // callLegendChanged(null);
502

    
503
                        strategy = new RasterDrawStrategy(getMapContext(), this);
504
                        strategy.stackStrategy();
505
                        HashMap tStr = strategy.getStrategy();
506
                        if (tStr != null && 
507
                                tStr.get(this) != null && 
508
                                ((Boolean) (tStr.get(this))).booleanValue() == false) {
509
                                disableStopped();
510
                                return;
511
                        }
512

    
513
                        if (isWithinScale(scale)) {
514
                                if (status != null && firstLoad) {
515
                                        if (mustTileDraw) {
516
                                                Point2D p = vp.getOffset();
517
                                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
518
                                                Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
519
                                                tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
520
                                                for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
521
                                                        // drawing part
522
                                                        try {
523
                                                                ViewPort vport = tiles.getTileViewPort(vp, tileNr);
524
//                                                                g.setClip(tiles.getClip(tileNr).x, tiles.getClip(tileNr).y, tiles.getClip(tileNr).width - 5, tiles.getClip(tileNr).height);
525
                                                                draw(image, g, vport, cancel);
526
                                                        } catch (RasterDriverException e) {
527
                                                                throw new ReadDriverException("", e);
528
                                                        } catch (InvalidSetViewException e) {
529
                                                                throw new ReadDriverException("Error al asignar la vista en el draw.", e);
530
                                                        } catch (InterruptedException e) {
531
                                                                System.out.println("Se ha cancelado el pintado");
532
//                                                                throw new ReadDriverException("Dibujado interrumpido.", e);
533
                                                        } catch (NoninvertibleTransformException e) {
534
                                                                throw new ReadDriverException("Error en la transformaci?n", e);
535
                                                        }
536
                                                }
537
                                        } else {
538
                                                try {
539
                                                        draw(image, g, vp, cancel);
540
                                                } catch (RasterDriverException e) {
541
                                                        throw new ReadDriverException("", e);
542
                                                } catch (InvalidSetViewException e) {
543
                                                        throw new ReadDriverException("Error al asignar la vista en el draw.", e);
544
                                                } catch (InterruptedException e) {
545
                                                        System.out.println("Se ha cancelado el pintado");
546
//                                                throw new ReadDriverException("Dibujado interrumpido.", e);
547
                                                }
548
                                        }
549
                                        try {
550
                                                status.applyStatus(this);
551
                                        } catch (NotSupportedExtensionException e) {
552
                                                throw new ReadDriverException("Error setting filters from a project.", e);
553
                                        } catch (RasterDriverException e) {
554
                                                throw new ReadDriverException("Error reading file from a project.", e);
555
                                        } catch (FilterTypeException e) {
556
                                                throw new ReadDriverException("Error adding filters.", e);
557
                                        }
558
                                        firstLoad = false;
559
                                }
560

    
561
                                if (mustTileDraw) {
562
                                        Point2D p = vp.getOffset();
563
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
564
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
565
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
566
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
567
                                                // drawing part
568
                                                try {
569
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
570
                                                        draw(image, g, vport, cancel);
571
                                                } catch (RasterDriverException e) {
572
                                                        throw new ReadDriverException("", e);
573
                                                } catch (InvalidSetViewException e) {
574
                                                        throw new ReadDriverException("Error al asignar la vista en el draw.", e);
575
                                                } catch (InterruptedException e) {
576
                                                        System.out.println("Se ha cancelado el pintado");
577
//                                                        throw new ReadDriverException("Dibujado interrumpido.", e);
578
                                                } catch (NoninvertibleTransformException e) {
579
                                                        throw new ReadDriverException("Error en la transformaci?n", e);
580
                                                }
581
                                        }
582
                                } else {
583
                                        try {
584
                                                draw(image, g, vp, cancel);
585
                                        } catch (RasterDriverException e) {
586
                                                throw new ReadDriverException("", e);
587
                                        } catch (InvalidSetViewException e) {
588
                                                throw new ReadDriverException("Error al asignar la vista en el draw.", e);
589
                                        } catch (InterruptedException e) {
590
                                                System.out.println("Se ha cancelado el pintado");
591
//                                        throw new ReadDriverException("Dibujado interrumpido.", e);
592
                                        }
593
                                }
594

    
595
                                if (getVirtualLayers() != null) {
596
                                        getVirtualLayers().draw(image, g, vp, cancel, scale);
597
                                }
598
                        }
599
                        //callLegendChanged(null);
600
                } finally {
601
                        disableStopped();
602
                        task.setEvent(null);
603
                }
604
        }
605

    
606
        private void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws RasterDriverException, InvalidSetViewException, InterruptedException {
607
                Rectangle2D adjustedExtent = vp.getAdjustedExtent();
608
                if (adjustedExtent == null) return;
609
                Extent e = new Extent(adjustedExtent);
610
                Dimension imgSz = vp.getImageSize();
611
                ViewPortData vp2 = new ViewPortData(vp.getProjection(), e, imgSz );
612
                vp2.setMat(vp.getAffineTransform());
613
                getRender().draw(g, vp2);
614
        }
615

    
616
        /**
617
         * Inserta la proyecci?n.
618
         *
619
         * @param proj Proyecci?n.
620
         */
621
        public void setProjection(IProjection proj) {
622
                super.setProjection(proj);
623
        }
624

    
625
        /*
626
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
627
         */
628
        public Rectangle2D getFullExtent() {
629
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
630
                //un extent aunque la capa no est? abierta
631
                if(/*!isOpen() || */dataset == null || dataset.getExtent() == null)
632
                        return null;
633
                return dataset.getExtent().toRectangle2D();
634
        }
635

    
636
        /**
637
         * Obtiene el valor del pixel del Image en la posici?n x,y
638
         * @param x Posici?n x
639
         * @param y Posici?n y
640
         * @return valor de pixel
641
         */
642
        public int[] getPixel(int pxx, int pxy) {
643
                int[] argb = { -1, -1, -1, -1 };
644
                if (!isOpen() || (image == null))
645
                        return argb;
646
                if (pxx >= 0 && pxx < image.getWidth() && pxy >= 0 && pxy < image.getHeight()) {
647
                        int value = image.getRGB(pxx, pxy);
648
                        argb[0] = ((value & 0xff000000) >> 24);
649
                        argb[1] = ((value & 0x00ff0000) >> 16);
650
                        argb[2] = ((value & 0x0000ff00) >> 8);
651
                        argb[3] = (value & 0x000000ff);
652
                }
653
                return argb;
654
        }
655

    
656
        /*
657
         * (non-Javadoc)
658
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
659
         */
660
        public double getMaxX() {
661
                if(getFullExtent() != null)
662
                        return getFullExtent().getMaxX();
663
                return -1;
664
        }
665

    
666
        /*
667
         * (non-Javadoc)
668
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
669
         */
670
        public double getMaxY() {
671
                if(getFullExtent() != null)
672
                        return this.getFullExtent().getMaxY();
673
                return -1;
674
        }
675

    
676
        /*
677
         * (non-Javadoc)
678
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinX()
679
         */
680
        public double getMinX() {
681
                if(getFullExtent() != null)
682
                        return getFullExtent().getMinX();
683
                return -1;
684
        }
685

    
686
        /*
687
         * (non-Javadoc)
688
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinY()
689
         */
690
        public double getMinY() {
691
                if(getFullExtent() != null)
692
                        return getFullExtent().getMinY();
693
                return -1;
694
        }
695

    
696
        /* (non-Javadoc)
697
         * @deprecated. See String getInfo(Point p) throws DriverException
698
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
699
         */
700
        public String queryByPoint(Point p) {
701
                if (!isOpen())
702
                        return null;
703
                ColorConversion conv = new ColorConversion();
704

    
705
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
706

    
707
                ArrayList attr = getAttributes();
708
                data += "  <raster\n";
709
                data += "    File=\"" + getFile() + "\"\n";
710
                for (int i = 0; i < attr.size(); i++) {
711
                        Object[] a = (Object[]) attr.get(i);
712

    
713
                        data += "    " + a[0].toString() + "=";
714
                        if (a[1].toString() instanceof String)
715
                                data += "\"" + a[1].toString() + "\"\n";
716
                        else
717
                                data += a[1].toString() + "\n";
718
                }
719
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
720
                data += "    Point_WC=\"" + MathUtils.format(posXWC, 3) + " , " + MathUtils.format(posYWC, 3) + "\"\n";
721
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
722
                double[] cmyk = conv.RGBtoCMYK(r & 0xff, g & 0xff, b & 0xff, 1D);
723
                data += "    CMYK=\"" + MathUtils.format(cmyk[0], 4) + ", " + MathUtils.format(cmyk[1], 4) + ", " + MathUtils.format(cmyk[2], 4) + "," + MathUtils.format(cmyk[3], 4) + "\"\n";
724
                double[] hsl = conv.RGBtoHSL(r & 0xff, g & 0xff, b & 0xff);
725
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
726
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
727
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
728
                data += "    HSL=\"" + MathUtils.format(hsl[0], 4) + ", " + MathUtils.format(hsl[1], 4) + ", " + MathUtils.format(hsl[2], 4) + "\"\n";
729
                data += "  />\n";
730

    
731
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
732
                return data;
733
        }
734

    
735
        /*
736
         * (non-Javadoc)
737
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo(java.awt.Point, double, com.iver.utiles.swing.threads.Cancellable)
738
         */
739
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException {
740
                if (!isOpen()) {
741
                        StringXMLItem[] item = new StringXMLItem[1];
742
                        String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
743
                        data += "  <raster\n" + "  Layer=\" Not available\"\n" + "  />\n";
744
                        data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
745
                        item[0] = new StringXMLItem(data, this);
746
                        return item;
747
                }
748

    
749
                Point2D pReal = getMapContext().getViewPort().toMapPoint(p);
750
                Point2D px = new Point2D.Double();
751
                if(        pReal.getX() > this.getMinX() &&
752
                        pReal.getX() < this.getMaxX() &&
753
                        pReal.getY() > this.getMinY() &&
754
                        pReal.getY() < this.getMaxY()) {
755

    
756
                        AffineTransform at = this.getDataSource().getAffineTransform();
757
                        px = new Point2D.Double(pReal.getX(), pReal.getY());
758
                        try {
759
                                at.inverseTransform(px, px);
760
                        } catch (NoninvertibleTransformException e) {
761
                                throw new ReadDriverException("Error en la transformaci?n del punto", e);
762
                        }
763
                }
764
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
765
                ColorConversion conv = new ColorConversion();
766

    
767
                StringXMLItem[] item = new StringXMLItem[1];
768
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
769

    
770
                data += "  <raster\n";
771
                data += "    View_Point=\"" + p.getX() + " , " + p.getY() + "\"\n";
772
                data += "    World_Point=\"" + MathUtils.format(pReal.getX(), 3) + " , " + MathUtils.format(pReal.getY(), 3) + "\"\n";
773
                if (px == null)
774
                        data += "    Pixel_Point=\"Out\"\n";
775
                else
776
                        data += "    Pixel_Point=\"" + (int) px.getX() + " , " + (int) px.getY() + "\"\n";
777
                data += "    RGB=\"" + rgb[1] + "  " + rgb[2] + "  " + rgb[3] + "\"\n";
778
                double[] cmyk = conv.RGBtoCMYK(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff, 1D);
779
                data += "    CMYK=\"" + MathUtils.format(cmyk[0], 4) + ", " + MathUtils.format(cmyk[1], 4) + ", " + MathUtils.format(cmyk[2], 4) + "," + MathUtils.format(cmyk[3], 4) + "\"\n";
780
                double[] hsl = conv.RGBtoHSL(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff);
781
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
782
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
783
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
784
                data += "    HSL=\"" + MathUtils.format(hsl[0], 4) + ", " + MathUtils.format(hsl[1], 4) + ", " + MathUtils.format(hsl[2], 4) + "\"\n";
785
                data += "    Band_Value=\"";
786
                try {
787
                        if (px != null) {
788
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3){
789
                                        for(int i = 0; i < getBandCount(); i++)
790
                                                data += ((Integer)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).intValue() + "  ";
791
                                }
792
                                if(getDataType()[0] == 4){
793
                                        for(int i = 0; i < getBandCount(); i++)
794
                                                data += ((Float)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).floatValue() + "  ";
795
                                }
796
                                if(getDataType()[0] == 5){
797
                                        for(int i = 0; i < getBandCount(); i++)
798
                                                data += ((Double)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).doubleValue() + "  ";
799
                                }
800
                        }
801
                } catch (RasterDriverException ex) {
802
                        throw new ReadDriverException("Error en el acceso al dataset", ex);
803
                } catch (InvalidSetViewException ex) {
804
                        throw new ReadDriverException("Error en la asignaci?n de la vista en getData", ex);
805
                } catch (FileNotOpenException ex) {
806
                        throw new ReadDriverException("Fichero no abierto en el dataset", ex);
807
                }
808
                data += "\"\n";
809
                data += "  />\n";
810
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
811

    
812
                item[0] = new StringXMLItem(data, this);
813
                return item;
814
        }
815

    
816
        /**
817
         * Filters a string for being suitable as XML Tag, erasing
818
         * all not alphabetic or numeric characters.
819
         * @param s
820
         * @return string normalized
821
         */
822
        private String normalizeAsXMLTag(String s) {
823
                return s.replaceAll("[^a-zA-Z0-9]", "");
824
        }
825

    
826
        /**
827
         * Obtiene atributos a partir de un georasterfile
828
         * @return
829
         */
830
        public ArrayList getAttributes() {
831
                ArrayList attr = new ArrayList();
832
                if(!isOpen())
833
                        return attr;
834
                Object [][] a = {
835
                        {"Filename", dataset.getDataset(0)[0].getFName()},
836
                        {"Filesize", new Long(dataset.getFileSize())},
837
                        {"Width", new Integer((int)dataset.getWidth())},
838
                        {"Height", new Integer((int)dataset.getHeight())},
839
                        {"Bands", new Integer(dataset.getBandCount())}
840
                };
841
                for (int i = 0; i < a.length; i++)
842
                        attr.add(a[i]);
843
                return attr;
844
        }
845

    
846
        /**
847
         * Escribe en el proyecto la capa actual
848
         * @throws XMLException
849
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
850
         */
851
        public XMLEntity getXMLEntity() throws XMLException {
852
                if(isClosed() || isAwake())
853
                        return null;
854

    
855
                XMLEntity xml = super.getXMLEntity();
856
                if(getFile() != null)
857
                        xml.putProperty("file", getFile());
858
                xml.putProperty("driverName", "gvSIG Raster Driver");
859

    
860
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
861
                if (status == null)
862
                        status = new StatusLayerRaster();
863
                status.getXMLEntity(xml, true, this);
864

    
865
                return xml;
866
        }
867

    
868
        public void setXMLEntity03(XMLEntity xml) throws XMLException {
869
        }
870

    
871
        /**
872
         * Recupera de disco los datos de la capa.
873
         */
874
        public void setXMLEntity(XMLEntity xml) throws XMLException {
875
                super.setXMLEntity(xml);
876

    
877
                try {
878
                        params = new File(xml.getStringProperty("file"));
879

    
880
                        if(params != null && getName() != null && getName().compareTo("") != 0) {
881
                                try {
882
                                        enableAwake();
883
                                } catch (NotAvailableStateException e) {
884
                                        Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
885
                                }
886
                        }
887
                        if(!super.getFLayerStatus().visible)
888
                                enableStopped();
889

    
890
                        // Para notificar al adapter-driver cual es la proyecci?n.
891
                        setProjection(super.getProjection());
892

    
893
                        //Inicializamos la clase a la que se usa por defecto para
894
                        //compatibilidad con proyectos antiguos
895
                        String claseStr = StatusLayerRaster.defaultClass;
896
                        if (xml.contains("raster.class"))
897
                                claseStr = xml.getStringProperty("raster.class");
898

    
899
                        if (status != null)
900
                                status.setXMLEntity(xml, this);
901
                        else {
902
                                // Cuando cargamos un proyecto
903

    
904
                                if (claseStr != null && !claseStr.equals("")) {
905
                                        try {
906
                                                Class clase = LayerFactory.getLayerClassForLayerClassName(claseStr);
907
                                                Constructor constr = clase.getConstructor(null);
908
                                                status = (IStatusRaster) constr.newInstance(null);
909
                                                if (status != null) {
910
                                                        ((StatusLayerRaster)status).setNameClass(claseStr);
911
                                                        status.setXMLEntity(xml, this);
912
                                                        filterArguments = status.getFilterArguments();
913
                                                        crearColorTable();
914
                                                }
915
                                        } catch (ClassNotFoundException exc) {
916
                                                throw new XMLException(exc);
917
                                        } catch (InstantiationException exc) {
918
                                                throw new XMLException(exc);
919
                                        } catch (IllegalAccessException exc) {
920
                                                throw new XMLException(exc);
921
                                        } catch (NoSuchMethodException exc) {
922
                                                throw new XMLException(exc);
923
                                        } catch (InvocationTargetException exc) {
924
                                                throw new XMLException(exc);
925
                                        }
926
                                }
927
                        }
928
                        firstLoad = true;
929
                } catch (NotExistInXMLEntity e) {
930

    
931
                }
932
        }
933

    
934
        private void crearColorTable() {
935
                ArrayList color = (ArrayList) filterArguments.clone();
936
                setLastLegend(ColorTableListManager.createColorTableFromArray(color));
937
        }
938

    
939
        /* (non-Javadoc)
940
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort, com.iver.cit.gvsig.fmap.operations.Cancellable)
941
         */
942
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet propeties) throws ReadDriverException {
943

    
944
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
945
                        return;
946

    
947
                if (!mustTilePrint) {
948
                        draw(null, g, viewPort, cancel,scale);
949
                } else {
950
                        // Para no pedir imagenes demasiado grandes, vamos
951
                        // a hacer lo mismo que hace EcwFile: chunkear.
952
                        // Llamamos a drawView con cuadraditos m?s peque?os
953
                        // del BufferedImage ni caso, cuando se imprime viene con null
954
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
955
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
956

    
957
                        //Si es la primera lectura salvamos los valores de m?ximo y m?nimo para la aplicaci?n
958
                        //de realce si la imagen es de 16 bits.
959

    
960
                        //RasterStats stats = getSource().getFilterStack().getStats();
961
                        //if(stats != null)
962
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
963

    
964

    
965
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
966
                                // Parte que dibuja
967
                                try {
968
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
969
                                        draw(null, g, vp, cancel, scale);
970
                                } catch (NoninvertibleTransformException e) {
971
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
972
                                }
973
                        }
974
                        /*if(stats != null){
975
                                getSource().getFilterStack().getStats().history.clear();
976
                                stats = getSource().getFilterStack().getStats();
977
                        }*/
978
                }
979
        }
980

    
981
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale) throws ReadDriverException {
982
                if(!isOpen())
983
                        return;
984

    
985
                // Para no pedir imagenes demasiado grandes, vamos
986
                // a hacer lo mismo que hace EcwFile: chunkear.
987
                // Llamamos a drawView con cuadraditos m?s peque?os
988
                // del BufferedImage ni caso, cuando se imprime viene con null
989

    
990
                int numW, numH;
991
                int stepX, stepY;
992
                int xProv, yProv;
993
                int A = 1500;
994
                int H = 1500;
995
                int altoAux, anchoAux;
996

    
997
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
998

    
999
                // Vamos a hacerlo en trozos de AxH
1000
                Rectangle r = g.getClipBounds();
1001
                numW = (int) (r.width) / A;
1002
                numH = (int) (r.height) / H;
1003

    
1004
                double[] srcPts = new double[8];
1005
                double[] dstPts = new double[8];
1006

    
1007
                yProv = (int) r.y;
1008
                for (stepY = 0; stepY < numH + 1; stepY++) {
1009
                        if ((yProv + H) > r.getMaxY())
1010
                                altoAux = (int) r.getMaxY() - yProv;
1011
                        else
1012
                                altoAux = H;
1013

    
1014
                        xProv = (int) r.x;
1015
                        for (stepX = 0; stepX < numW + 1; stepX++) {
1016
                                if ((xProv + A) > r.getMaxX())
1017
                                        anchoAux = (int) r.getMaxX() - xProv;
1018
                                else
1019
                                        anchoAux = A;
1020

    
1021
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
1022

    
1023
                                // Parte que dibuja
1024
                                srcPts[0] = xProv;
1025
                                srcPts[1] = yProv;
1026
                                srcPts[2] = xProv + anchoAux + 1;
1027
                                srcPts[3] = yProv;
1028
                                srcPts[4] = xProv + anchoAux + 1;
1029
                                srcPts[5] = yProv + altoAux + 1;
1030
                                srcPts[6] = xProv;
1031
                                srcPts[7] = yProv + altoAux + 1;
1032

    
1033
                                try {
1034
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
1035
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
1036
                                        // Extent extent = new Extent(rectCuadricula);
1037

    
1038
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
1039
                                        ViewPort vp = viewPort.cloneViewPort();
1040
                                        vp.setImageSize(tam);
1041
                                        vp.setExtent(rectCuadricula);
1042
                                        vp.setAffineTransform(mat);
1043
                                        draw(null, g, vp, cancel, scale);
1044

    
1045
                                } catch (NoninvertibleTransformException e) {
1046
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
1047
                                }
1048
                                // Fin parte que dibuja
1049
                                xProv = xProv + A;
1050
                        }
1051
                        yProv = yProv + H;
1052
                }
1053
        }
1054

    
1055
        /**
1056
         * Borra de la lista de listeners el que se pasa como par?metro.
1057
         *
1058
         * @param o LayerListener a borrar.
1059
         *
1060
         * @return True si ha sido correcto el borrado del Listener.
1061
         */
1062
        public boolean removeLayerListener(LayerListener o) {
1063
                // Salva a RMF
1064
                if (this.getDataSource() != null) {
1065
                        // Guardamos la GeoReferenciacion de cada dataset
1066
                        try {
1067
                                for (int i = 0; i < getDataSource().getDatasetCount(); i++) {
1068
                                        getDataSource().saveObjectToRmf(i, RasterDataset.class, getDataSource().getDataset(i)[0]);
1069
                                }
1070
                        } catch (RmfSerializerException e) {
1071
                                RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
1072
                        }
1073
                }
1074

    
1075
                if (this.isRemoveRasterFlag()) {
1076
                        String[] files = (String[]) getFileName().clone();
1077
                        if (dataset != null)
1078
                                dataset.close();
1079
                        if (bufferFactory != null)
1080
                                bufferFactory.free();
1081
                        bufferFactory = null;
1082
                        dataset = null;
1083
                        render = null;
1084
                        try {
1085
                                enableClosed();
1086
                        } catch (NotAvailableStateException e1) {
1087
                                // No se ha podido cambiar el estado de la capa a cerrado
1088
                        }
1089

    
1090
                        // System.gc();
1091
                        this.setRemoveRasterFlag(true);
1092
                        
1093
                        for (int i = 0; i < files.length; i++) {
1094
                                File file = new File(files[i]);
1095
                                File dirTemp = RasterLibrary.getTemporalFile();
1096
                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
1097
                                        file.delete();
1098
                                        
1099
                                        // Borramos todos los ficheros que puedan tener relacion con el fichero actual
1100
                                        String basefile = file.getName();
1101
                                        File basepath = file.getParentFile();
1102
                                        int last = basefile.lastIndexOf(".");
1103
                                        if (last == -1) last = basefile.length();
1104
                                        basefile = basefile.substring(0, last + 1);
1105
                                        File[] list = basepath.listFiles();
1106
                                        for (int j = 0; j < list.length; j++)
1107
                                                if (list[j].getName().startsWith(basefile))
1108
                                                        list[j].delete();
1109
                                }
1110
                        }
1111
                }
1112
                return super.layerListeners.remove(o);
1113
        }
1114

    
1115
        /**
1116
         * @return Returns the removeRasterFlag.
1117
         */
1118
        public boolean isRemoveRasterFlag() {
1119
                return removeRasterFlag;
1120
        }
1121

    
1122
        /**
1123
         * Asigna el valor del flag que dice si destruimos la memoria del raster
1124
         * al eliminarlo del TOC o  no.
1125
         * @param removeRasterFlag The removeRasterFlag to set.
1126
         */
1127
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1128
                this.removeRasterFlag = removeRasterFlag;
1129
        }
1130

    
1131
        /*
1132
         * (non-Javadoc)
1133
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1134
         */
1135
        public ImageIcon getTocImageIcon() {
1136
                return new ImageIcon(getClass().getResource("images/map_ico_ok.gif"));
1137
        }
1138

    
1139
        /*
1140
         *  (non-Javadoc)
1141
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1142
         */
1143
        public int[] getTileSize() {
1144
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1145
                return size;
1146
        }
1147

    
1148
        /*
1149
         *  (non-Javadoc)
1150
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1151
         */
1152
        public boolean isTiled() {
1153
                return mustTileDraw;
1154
        }
1155

    
1156
        /**
1157
         * Obtiene el flag que dice si la imagen est? o no georreferenciada
1158
         * @return true si est? georreferenciada y false si no lo est?.
1159
         */
1160
        public boolean isGeoreferenced() {
1161
                return dataset.isGeoreferenced();
1162
        }
1163

    
1164
        /**
1165
         * Get datasource object
1166
         * @return
1167
         */
1168
        public BufferFactory getBufferFactory(){
1169
                return bufferFactory;
1170
        }
1171

    
1172
        /**
1173
         * Obtiene el valor NoData asociado al raster.
1174
         * @return double
1175
         */
1176
        public double getNoDataValue() {
1177
                if (dataset == null)
1178
                        return RasterLibrary.defaultNoDataValue;
1179
                return dataset.getNoDataValue();
1180
        }
1181

    
1182
        /**
1183
         * Asigna el valor no data asociado a la capa
1184
         * @param nd
1185
         */
1186
        public void setNoDataValue(double nd) {
1187
                if (bufferFactory != null)
1188
                        bufferFactory.setNoDataToFill(nd);
1189
                if (dataset != null)
1190
                        dataset.setNoDataValue(nd);
1191
        }
1192

    
1193
        /*
1194
         * (non-Javadoc)
1195
         * @see org.gvsig.fmap.raster.IRasterOperations#getPXHeight()
1196
         */
1197
        public double getPxHeight() {
1198
                return dataset.getHeight();
1199
        }
1200

    
1201
        /*
1202
         * (non-Javadoc)
1203
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
1204
         */
1205
        public double getPxWidth() {
1206
                return dataset.getWidth();
1207
        }
1208

    
1209
        /*
1210
         * (non-Javadoc)
1211
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCHeight()
1212
         */
1213
        public double getWCHeight() {
1214
                return getFullExtent().getHeight();
1215
        }
1216

    
1217
        /*
1218
         * (non-Javadoc)
1219
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
1220
         */
1221
        public double getWCWidth() {
1222
                return getFullExtent().getWidth();
1223
        }
1224

    
1225
        /*
1226
         * (non-Javadoc)
1227
         * @see org.gvsig.fmap.raster.IRasterFile#getFileSize()
1228
         */
1229
        public long[] getFileSize(){
1230
                int nFiles = dataset.getDatasetCount();
1231
                long[] s = new long[nFiles];
1232
                for (int i = 0; i < nFiles; i++)
1233
                        s[i] = dataset.getDataset(i)[0].getFileSize();
1234
                return s;
1235
        }
1236

    
1237
        /*
1238
         * (non-Javadoc)
1239
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
1240
         */
1241
        public String[] getFileName(){
1242
                int nFiles = 0;
1243
                if (dataset != null)
1244
                        nFiles = dataset.getDatasetCount();
1245
                String[] s = new String[nFiles];
1246
                for (int i = 0; i < nFiles; i++)
1247
                        s[i] = dataset.getDataset(i)[0].getFName();
1248
                return s;
1249
        }
1250

    
1251
        /*
1252
         * (non-Javadoc)
1253
         * @see org.gvsig.fmap.raster.IRasterFile#getFileCount()
1254
         */
1255
        public int getFileCount() {
1256
                return (dataset != null) ? dataset.getDatasetCount() : 0;
1257
        }
1258

    
1259
        /*
1260
         * (non-Javadoc)
1261
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
1262
         */
1263
        public String getFileFormat() {
1264
                String fName = dataset.getDataset(0)[0].getFName();
1265
                int index = fName.lastIndexOf(".") + 1;
1266
                String ext = null;
1267
                if (index > 0)
1268
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1269
                return ext;
1270
        }
1271

    
1272
        /*
1273
         * (non-Javadoc)
1274
         * @see org.gvsig.fmap.raster.IRasterOperations#getBandCount()
1275
         */
1276
        public int getBandCount() {
1277
                return (dataset != null) ? dataset.getBandCount() : 0;
1278
        }
1279

    
1280
        /*
1281
         * (non-Javadoc)
1282
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1283
         */
1284
        public int[] getDataType() {
1285
                return dataset.getDataType();
1286
        }
1287

    
1288
        /*
1289
         * (non-Javadoc)
1290
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
1291
         */
1292
        public GridTransparency getRenderTransparency() {
1293
                return getRender().getLastTransparency();
1294
        }
1295

    
1296
        /*
1297
         * (non-Javadoc)
1298
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1299
         */
1300
        public RasterFilterList getRenderFilterList() {
1301
                return getRender().getFilterList();
1302
        }
1303

    
1304
        /*
1305
         * (non-Javadoc)
1306
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
1307
         */
1308
        public int[] getRenderBands() {
1309
                return getRender().getRenderBands();
1310
        }
1311

    
1312
        /*
1313
         * (non-Javadoc)
1314
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
1315
         */
1316
        public void setRenderBands(int[] renderBands) {
1317
                getRender().setRenderBands(renderBands);
1318
        }
1319

    
1320
        /*
1321
         * (non-Javadoc)
1322
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
1323
         */
1324
        public void setRenderFilterList(RasterFilterList filterList) {
1325
                getRender().setFilterList(filterList);
1326
        }
1327

    
1328
        /*
1329
         * (non-Javadoc)
1330
         * @see org.gvsig.raster.hierarchy.IRasterDataset#getDataSource()
1331
         */
1332
        public IRasterDataSource getDataSource() {
1333
                return dataset;
1334
        }
1335

    
1336
        /*
1337
         * (non-Javadoc)
1338
         * @see org.gvsig.fmap.raster.IRasterDataset#addFile(java.lang.String)
1339
         */
1340
        public void addFile(String fileName) throws NotSupportedExtensionException, RasterDriverException {
1341
                if (getRender() != null)
1342
                        bufferFactory.addFile(RasterDataset.open(getProjection(), fileName));
1343
        }
1344

    
1345
        /*
1346
         * (non-Javadoc)
1347
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
1348
         */
1349
        public void delFile(String fileName) {
1350
                if (getRender() != null)
1351
                        bufferFactory.removeFile(fileName);
1352
        }
1353

    
1354
        /*
1355
         * (non-Javadoc)
1356
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1357
         */
1358
        public Object getInfo(String key) {
1359
                if (key.equals("DriverName"))
1360
                        return "gvSIG Raster Driver";
1361
                return null;
1362
        }
1363

    
1364
        /*
1365
         * (non-Javadoc)
1366
         * @see org.gvsig.raster.shared.IRasterOperations#getMetadata()
1367
         */
1368
        public DatasetMetadata[] getMetadata() {
1369
                int count = dataset.getDatasetCount();
1370
                DatasetMetadata[] metadata = new DatasetMetadata[count];
1371
                for (int i = 0; i < count; i++) {
1372
                        metadata[i] = dataset.getDataset(i)[0].getMetadata();
1373
                }
1374
                return metadata;
1375
        }
1376

    
1377
        /*
1378
         * (non-Javadoc)
1379
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
1380
         */
1381
        public int[] getBandCountFromDataset() {
1382
                int count = dataset.getDatasetCount();
1383
                int[] bands = new int[count];
1384
                for (int i = 0; i < count; i++)
1385
                        bands[i] = dataset.getDataset(i)[0].getBandCount();
1386
                return bands;
1387
        }
1388

    
1389
        /*
1390
         * (non-Javadoc)
1391
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1392
         */
1393
        public String getColorInterpretation(int band, int dataset) {
1394
                if (this.dataset.getDataset(dataset)[0].getColorInterpretation().get(band) == null)
1395
                        return "Undefined";
1396
                return this.dataset.getDataset(dataset)[0].getColorInterpretation().get(band);
1397
        }
1398

    
1399
        /*
1400
         * (non-Javadoc)
1401
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
1402
         */
1403
        public String getWktProjection() throws RasterDriverException {
1404
                return dataset.getWktProjection();
1405
        }
1406

    
1407
        /**
1408
         * Metodo para consultar si una capa puede ser un RGB. Suponemos que es un RGB
1409
         * si el tipo de datos es de tipo byte y su interpretacion de color tiene
1410
         * asignada los tres colores.
1411
         * @return boolean
1412
         */
1413
        public boolean isRGB() {
1414
                if ((dataset == null) || (render == null))
1415
                        return false;
1416

    
1417
// Quitado pq no necesariamente tiene pq tener 3 bandas para ser RGB
1418
//                if (dataset.getBandCount() < 3)
1419
//                        return false;
1420

    
1421
                if (dataset.getDataType()[0] != IBuffer.TYPE_BYTE)
1422
                        return false;
1423

    
1424
                boolean R = false;
1425
                boolean G = false;
1426
                boolean B = false;
1427

    
1428
                int[] renderBands = render.getRenderBands();
1429
                for (int i = 0; i < renderBands.length; i++) {
1430
                        if (renderBands[i] >= 0) {
1431
                                switch (i) {
1432
                                        case 0:
1433
                                                R = true;
1434
                                                break;
1435
                                        case 1:
1436
                                                G = true;
1437
                                                break;
1438
                                        case 2:
1439
                                                B = true;
1440
                                                break;
1441
                                }
1442
                        }
1443
                }
1444

    
1445
                if (R && G && B)
1446
                        return true;
1447

    
1448
                return false;
1449
        }
1450
        
1451
        /**
1452
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1453
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1454
         * cacheado o no dependiendo del tama?o de esta.
1455
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1456
         * @return Grid.
1457
         * @throws InterruptedException
1458
         */
1459
        public Grid getFullGrid(boolean interpolated) throws GridException, InterruptedException {
1460
                BufferFactory bf = getBufferFactory();
1461
                bf.clearDrawableBand();
1462
                bf.setAllDrawableBands();
1463
                try {
1464
                        bf.setAreaOfInterest();
1465
                } catch (RasterDriverException e) {
1466
                        throw new GridException("Error reading buffer");
1467
                }
1468
                return new Grid(bf, interpolated);
1469
        }
1470
        
1471
        /**
1472
         * Obtiene el tama?o de celda de la fuente de datos
1473
         * @return double con el tama?o de celda
1474
         */
1475
        public double getCellSize() {
1476
                return (getDataSource() != null) ? getDataSource().getCellSize() : 1;
1477
        }
1478
        
1479
        /*
1480
         * (non-Javadoc)
1481
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1482
         */
1483
        public Extent getFullRasterExtent() {
1484
                return this.getDataSource().getExtent();
1485
        }
1486

    
1487

    
1488
        /**
1489
         * Devuelve el fichero asociado a la capa o null si no tiene.
1490
         * @return Fichero.
1491
         */
1492
        public File getFile() {
1493
                return (params instanceof File) ? ((File)params) : null;
1494
        }
1495

    
1496
        /**
1497
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1498
         * @param file Fichero a consultar
1499
         * @return true si es aceptado y false si no lo es.
1500
         */
1501
        public static boolean isFileAccepted(File file) {
1502
                return RasterDataset.fileIsSupported(file.getName());
1503
        }
1504

    
1505
        /*
1506
         * (non-Javadoc)
1507
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1508
         */
1509
        public boolean existColorTable() {
1510
                return getRender().existColorTable();
1511
        }
1512
        
1513
        /*
1514
         * (non-Javadoc)
1515
         * @see org.gvsig.raster.hierarchy.IRasterRendering#existsAlphaBand()
1516
         */
1517
        public boolean existsAlphaBand() {
1518
                if(getDataSource().getColorInterpretation() != null)
1519
                        return getDataSource().getColorInterpretation().isAlphaBand();
1520
                else 
1521
                        return false;
1522
        }
1523
        
1524
        /*
1525
         * (non-Javadoc)
1526
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getAlphaBandNumber()
1527
         */
1528
        public int getAlphaBandNumber() {
1529
                if(getDataSource().getColorInterpretation() != null)
1530
                        return getDataSource().getColorInterpretation().getBand(DatasetColorInterpretation.ALPHA_BAND);
1531
                return -1;
1532
        }
1533

    
1534
        /**
1535
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1536
         * capa busque una leyenda valida.
1537
         * @param ct
1538
         */
1539
        public void setLastLegend(ColorTable ct) {
1540
                lastLegend = ColorTableLegend.createLegend(ct);
1541
        }
1542

    
1543
        /**
1544
         * Devuelve la Leyenda de la capa.
1545
         * @return Leyenda.
1546
         */
1547
        public ILegend getLegend() {
1548
                if (lastLegend != null)
1549
                        return lastLegend;
1550

    
1551
                return null;
1552
        }
1553

    
1554
        /*
1555
         * (non-Javadoc)
1556
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1557
         */
1558
        public void addLegendListener(LegendListener listener) {
1559
                layerChangeSupport.addLayerListener(listener);
1560
        }
1561

    
1562
        /*
1563
         *  (non-Javadoc)
1564
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1565
         */
1566
        public int getShapeType() throws ReadDriverException {
1567
                return FShape.POLYGON;
1568
        }
1569

    
1570
        /*
1571
         * (non-Javadoc)
1572
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1573
         */
1574
        public void removeLegendListener(LegendListener listener) {
1575
                layerChangeSupport.removeLayerListener(listener);
1576
        }
1577

    
1578
        /**
1579
         * Metodo que obtiene si un punto cae dentro de los l?mites de la capa
1580
         * o fuera de ellos.
1581
         * @param p Punto a calcular
1582
         * @return true si est? dentro de los l?mites y false si est? fuera
1583
         */
1584
        public boolean isInside(Point2D p) {
1585
                 return getDataSource().isInside(p);
1586
        }
1587

    
1588
        /**
1589
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1590
         * @return AffineTransform
1591
         */
1592
        public AffineTransform getAffineTransform() {
1593
                return getDataSource().getAffineTransform();
1594
        }
1595

    
1596
        /**
1597
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista
1598
         * @param transf
1599
         */
1600
        public void setAffineTransform(AffineTransform transf) {
1601
                if(transf == null)
1602
                        return;
1603
                affineTransformList.add(transf);
1604
                getDataSource().setAffineTransform(transf);
1605
        }
1606

    
1607
        /**
1608
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista.
1609
         * Esta versi?n no guarda en el historico.
1610
         * @param transf
1611
         */
1612
        public void setAT(AffineTransform transf) {
1613
                getDataSource().setAffineTransform(transf);
1614
        }
1615

    
1616
        /**
1617
         * Obtiene la lista de transformaciones que se han ido aplicando al raster.
1618
         * @return Historical. Lista de AffineTransform
1619
         */
1620
        public Historical getAffineTransformHistorical() {
1621
                return this.affineTransformList;
1622
        }
1623

    
1624
        /**
1625
         * Salva la georreferenciaci?n a fichero rmf.
1626
         * @param fName
1627
         * @throws RmfSerializerException 
1628
         */
1629
        public void saveGeoToRmf() throws RmfSerializerException {
1630
                if (!isOpen())
1631
                        return;
1632

    
1633
                // Guardamos la GeoReferenciacion de cada dataset
1634
                for (int i = 0; i < getDataSource().getDatasetCount(); i++)
1635
                        getDataSource().saveObjectToRmf(i, RasterDataset.class, getDataSource().getDataset(i)[0]);
1636
                
1637
                affineTransformList.clear();
1638
                affineTransformList.add(this.getAffineTransform());
1639
        }
1640

    
1641
        /*
1642
         * (non-Javadoc)
1643
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1644
         */
1645
        public boolean isActionEnabled(int action) {
1646
                switch (action) {
1647
                        case IRasterLayerActions.BANDS_FILE_LIST:
1648
                                if (existColorTable())
1649
                                        return false;
1650
                                break;
1651
                        case IRasterLayerActions.BANDS_RGB:
1652
                                if (existColorTable())
1653
                                        return false;
1654
                                break;
1655
                        case IRasterLayerActions.REPROJECT:
1656
                                if (!isReproyectable())
1657
                                        return false;
1658
                                break;
1659
                        case IRasterLayerActions.CREATEOVERVIEWS:
1660
                                return overviewsSupport();
1661
                        case IRasterLayerActions.OPACITY:
1662
                        case IRasterLayerActions.TRANSPARENCY:
1663
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1664
                        case IRasterLayerActions.ENHANCED:
1665
                        case IRasterLayerActions.PANSHARPENING:
1666
                                return true;
1667
                }
1668
                return true;
1669
        }
1670

    
1671
        /*
1672
         * (non-Javadoc)
1673
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1674
         */
1675
        public void setVisible(boolean visibility) {
1676
                if(visibility)
1677
                        state.disableStopped();
1678
                else
1679
                        enableStopped();
1680

    
1681
                if(isAwake() || isClosed())
1682
                        try {
1683
                                this.load();
1684
                        } catch (LoadLayerException e) {
1685
                                e.printStackTrace();
1686
                        }
1687
                super.setVisible(visibility);
1688
        }
1689

    
1690
        /**
1691
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1692
         * @return valor de transparencia
1693
         */
1694
        public int getTransparency() {
1695
                try {
1696
                        return getRenderTransparency().getOpacity();
1697
                } catch (NullPointerException e) {
1698
                        return super.getTransparency();
1699
                }
1700
        }
1701

    
1702
        /**
1703
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1704
         * o no.
1705
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1706
         */
1707
        public boolean isTransparent() {
1708
                return getRenderTransparency().isTransparencyActive();
1709
        }
1710

    
1711
        /**
1712
         * Asigna la transparencia de la siguiente renderizaci?n
1713
         * @param valor de transparencia
1714
         */
1715
        public void setTransparency(int trans) {
1716
                super.setTransparency(trans);
1717
                try {
1718
                        getRenderTransparency().setOpacity(trans);
1719
                        getRenderTransparency().activeTransparency();
1720
                } catch (NullPointerException e) {
1721
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1722
                }
1723
        }
1724

    
1725
        /*
1726
         * (non-Javadoc)
1727
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getLastRenderBuffer()
1728
         */
1729
        public IBuffer getLastRenderBuffer() {
1730
                return getRender().getLastRenderBuffer();
1731
        }
1732

    
1733
        /**
1734
         *
1735
         * @return ROIs asociadas a la capa raster.
1736
         */
1737
        public ArrayList getRois() {
1738
                return rois;
1739
        }
1740

    
1741
        /**
1742
         * Establece las ROI asociadas a la capa raster.
1743
         *
1744
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1745
         */
1746
        public void setRois(ArrayList rois) {
1747
                this.rois = rois;
1748
        }
1749

    
1750
        /**
1751
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1752
         * devolver? null.
1753
         * @return TreeMap con la lista de capas a dibujar
1754
         */
1755
        public HashMap getRasterStrategy() {
1756
                if(strategy != null)
1757
                        return strategy.getStrategy();
1758
                return null;
1759
        }
1760
        
1761
        /**
1762
         * Devuelve el tipo de valor de NoData asociado a la capa.
1763
         * Sirve para diferenciar los estados seleccionados por el usuario. Siendo
1764
         * estos '0: Sin Valor NoData', '1: NoData de Capa'(Por defecto) y '2: Personalizado'
1765
         */
1766
        /**
1767
         * @return the noDataType
1768
         */
1769
        public int getNoDataType() {
1770
                return noDataType;
1771
        }
1772

    
1773
        /**
1774
         * @param noDataType the noDataType to set
1775
         */
1776
        public void setNoDataType(int noDataType) {
1777
                this.noDataType = noDataType;
1778
                if (dataset != null)
1779
                        dataset.setNoDataEnabled(noDataType != RasterLibrary.NODATATYPE_DISABLED);
1780
        }
1781

    
1782
        /**
1783
         * @return the configuration
1784
         */
1785
        static public IConfiguration getConfiguration() {
1786
                return configuration;
1787
        }
1788

    
1789
        /**
1790
         * @param configuration the configuration to set
1791
         */
1792
        static public void setConfiguration(IConfiguration configuration) {
1793
                FLyrRasterSE.configuration = configuration;
1794
        }
1795
        
1796
        /*
1797
         * (non-Javadoc)
1798
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#reload()
1799
         */
1800
        public void reload() throws ReloadLayerException {
1801
                try {
1802
                        super.reload();
1803
                        if (getMapContext() == null)
1804
                                return;
1805
                        if (isStopped())
1806
                                disableStopped();
1807
                        load();
1808
                        getMapContext().invalidate();
1809
                } catch (LoadLayerException e) {
1810
                        setAvailable(false);
1811
                        throw new ReloadLayerException(getName(), e);
1812
                }
1813
        }
1814
        
1815
        /**
1816
         * Devuelve si la capa tiene soporte para poder generar overviews
1817
         * @return
1818
         */
1819
        public boolean overviewsSupport() {
1820
                if ((getDataSource() != null) && (getDataSource().overviewsSupport()))
1821
                        return true;
1822

    
1823
                return false;
1824
        }
1825

    
1826
        /**
1827
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1828
         * en escala de grises
1829
         * @return
1830
         */
1831
        public boolean isRenderingAsGray() {
1832
                int[] renderBands = getRenderBands();
1833
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1834
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1835
                        return true;
1836
                return false;
1837
        }
1838

    
1839
        /*****************************************************/
1840
        //Utils
1841

    
1842
        /**
1843
         * Ajusta las coordenadas especificadas en el par?metro al ?rea m?xima
1844
         * del raster en p?xeles.
1845
         * @param req Punto a ajustar dentro del extener del raster
1846
         */
1847
        public Point2D adjustWorldRequest(Point2D req) {
1848
                Rectangle2D ext = null;
1849

    
1850
                ext = getFullExtent();
1851
                req.setLocation(Math.max(ext.getMinX(), req.getX()), Math.max(ext.getMinY(), req.getY()));
1852
                req.setLocation(Math.min(ext.getMaxX(), req.getX()), Math.min(ext.getMaxY(), req.getY()));
1853
                return req;
1854
        }
1855
        
1856
        /*
1857
         * (non-Javadoc)
1858
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#cloneLayer()
1859
         */
1860
        public FLayer cloneLayer() throws Exception {
1861
                FLyrRasterSE newLayer = FLyrRasterSE.createLayer(this.getName(), params, this.getProjection());
1862
                for (int i = 0; i < dataset.getDatasetCount(); i++) {
1863
                        String name = dataset.getDataset(i)[0].getFName();
1864
                        if (!(dataset instanceof CompositeDataset) && !name.equals(this.getName()))
1865
                                newLayer.addFile(name);
1866
                }
1867
                ArrayList filters = getRender().getFilterList().getStatusCloned();
1868
        
1869
                //Hacemos una copia de las bandas a renderizar
1870
                if(getRenderBands() != null) {
1871
                        int[] rb = new int[getRenderBands().length];
1872
                        for (int i = 0; i < rb.length; i++) 
1873
                                rb[i] = getRenderBands()[i];
1874
                        newLayer.setRenderBands(rb);
1875
                }
1876
                
1877
                //Asignamos el entorno
1878
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());        
1879
                newLayer.getRender().getFilterList().setStatus(filters);
1880

    
1881
                // Asignamos los valores noData del original
1882
                newLayer.setNoDataValue(getNoDataValue());
1883
                newLayer.setNoDataType(getNoDataType());
1884
                newLayer.applyNoData();
1885

    
1886
                return newLayer;
1887
        }
1888
        
1889
        /*****************************************************/
1890

    
1891
        public void disableStopped() {state.disableStopped();}
1892

    
1893
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1894

    
1895
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
1896

    
1897
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1898

    
1899
        public void enableStopped() {state.enableStopped();}
1900

    
1901
        public boolean isAwake() {return state.isAwake();}
1902

    
1903
        public boolean isClosed() {return state.isClosed();}
1904

    
1905
        public boolean isOpen() {return state.isOpen();}
1906

    
1907
        public boolean isStopped() {return state.isStopped();}
1908
}