Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRasterTools-SE / src / org / gvsig / fmap / raster / layers / FLyrRasterSE.java @ 22307

History | View | Annotate | Download (57.7 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.datastruct.ColorTable;
58
import org.gvsig.raster.datastruct.Extent;
59
import org.gvsig.raster.datastruct.ViewPortData;
60
import org.gvsig.raster.datastruct.persistence.ColorTableLibraryPersistence;
61
import org.gvsig.raster.grid.Grid;
62
import org.gvsig.raster.grid.GridException;
63
import org.gvsig.raster.grid.GridPalette;
64
import org.gvsig.raster.grid.GridTransparency;
65
import org.gvsig.raster.grid.filter.FilterTypeException;
66
import org.gvsig.raster.grid.filter.RasterFilterList;
67
import org.gvsig.raster.grid.filter.RasterFilterListManager;
68
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
69
import org.gvsig.raster.grid.filter.enhancement.EnhancementStretchListManager;
70
import org.gvsig.raster.grid.filter.enhancement.LinearStretchParams;
71
import org.gvsig.raster.grid.render.Rendering;
72
import org.gvsig.raster.hierarchy.IRasterDataset;
73
import org.gvsig.raster.hierarchy.IRasterOperations;
74
import org.gvsig.raster.hierarchy.IRasterProperties;
75
import org.gvsig.raster.hierarchy.IStatistics;
76
import org.gvsig.raster.process.RasterTask;
77
import org.gvsig.raster.process.RasterTaskQueue;
78
import org.gvsig.raster.projection.CRS;
79
import org.gvsig.raster.util.ColorConversion;
80
import org.gvsig.raster.util.Historical;
81
import org.gvsig.raster.util.MathUtils;
82
import org.gvsig.raster.util.RasterToolsUtil;
83

    
84
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
85
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
86
import com.iver.cit.gvsig.exceptions.layers.ReloadLayerException;
87
import com.iver.cit.gvsig.fmap.ViewPort;
88
import com.iver.cit.gvsig.fmap.core.FShape;
89
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
90
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
91
import com.iver.cit.gvsig.fmap.layers.FLayer;
92
import com.iver.cit.gvsig.fmap.layers.FLyrDefault;
93
import com.iver.cit.gvsig.fmap.layers.LayerChangeSupport;
94
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
95
import com.iver.cit.gvsig.fmap.layers.LayerListener;
96
import com.iver.cit.gvsig.fmap.layers.Tiling;
97
import com.iver.cit.gvsig.fmap.layers.XMLException;
98
import com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable;
99
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
100
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
101
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
102
import com.iver.cit.gvsig.fmap.rendering.ILegend;
103
import com.iver.cit.gvsig.fmap.rendering.LegendListener;
104
import com.iver.utiles.NotExistInXMLEntity;
105
import com.iver.utiles.XMLEntity;
106
import com.iver.utiles.swing.threads.Cancellable;
107
/**
108
 * Capa raster
109
 * @author Nacho Brodin (nachobrodin@gmail.com)
110
 */
111
public class FLyrRasterSE extends FLyrDefault implements IRasterProperties, IRasterDataset, InfoByPoint, Classifiable, IRasterOperations, IRasterLayerActions, ILayerState {
112
        protected boolean           isPrinting          = false;
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
                isPrinting = true;
948
                if (!mustTilePrint) {
949
                        draw(null, g, viewPort, cancel,scale);
950
                } else {
951
                        // Para no pedir imagenes demasiado grandes, vamos
952
                        // a hacer lo mismo que hace EcwFile: chunkear.
953
                        // Llamamos a drawView con cuadraditos m?s peque?os
954
                        // del BufferedImage ni caso, cuando se imprime viene con null
955
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
956
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
957

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

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

    
965

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

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

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

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

    
999
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
1000

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

    
1006
                double[] srcPts = new double[8];
1007
                double[] dstPts = new double[8];
1008

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

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

    
1023
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
1024

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

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

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

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

    
1057
        /**
1058
         * Borra de la lista de listeners el que se pasa como par?metro.
1059
         *
1060
         * @param o LayerListener a borrar.
1061
         *
1062
         * @return True si ha sido correcto el borrado del Listener.
1063
         */
1064
        public boolean removeLayerListener(LayerListener o) {
1065
                // Salva a RMF
1066
                try {
1067
                        if (this.getDataSource() != null)
1068
                                this.getDataSource().saveRmfModification();
1069
                } catch (IOException e) {
1070
                        // No se ha salvado nada
1071
                }
1072

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1422
                boolean R = false;
1423
                boolean G = false;
1424
                boolean B = false;
1425

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

    
1443
                if (R && G && B)
1444
                        return true;
1445

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

    
1485

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

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

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

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

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

    
1549
                return null;
1550
        }
1551

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

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

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

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

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

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

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

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

    
1622
        /**
1623
         * Salva la georreferenciaci?n a fichero rmf.
1624
         * @param fName
1625
         * @throws IOException
1626
         */
1627
        public void saveGeoToRmf() throws IOException {
1628
                if (!isOpen())
1629
                        return;
1630
                getDataSource().saveGeoToRmf();
1631
                affineTransformList.clear();
1632
                affineTransformList.add(this.getAffineTransform());
1633
        }
1634

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

    
1665
        /*
1666
         * (non-Javadoc)
1667
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1668
         */
1669
        public void setVisible(boolean visibility) {
1670
                if(visibility)
1671
                        state.disableStopped();
1672
                else
1673
                        enableStopped();
1674

    
1675
                if(isAwake() || isClosed())
1676
                        try {
1677
                                this.load();
1678
                        } catch (LoadLayerException e) {
1679
                                e.printStackTrace();
1680
                        }
1681
                super.setVisible(visibility);
1682
        }
1683

    
1684
        /**
1685
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1686
         * @return valor de transparencia
1687
         */
1688
        public int getTransparency() {
1689
                try {
1690
                        return getRenderTransparency().getOpacity();
1691
                } catch (NullPointerException e) {
1692
                        return super.getTransparency();
1693
                }
1694
        }
1695

    
1696
        /**
1697
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1698
         * o no.
1699
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1700
         */
1701
        public boolean isTransparent() {
1702
                return getRenderTransparency().isTransparencyActive();
1703
        }
1704

    
1705
        /**
1706
         * Asigna la transparencia de la siguiente renderizaci?n
1707
         * @param valor de transparencia
1708
         */
1709
        public void setTransparency(int trans) {
1710
                super.setTransparency(trans);
1711
                try {
1712
                        getRenderTransparency().setOpacity(trans);
1713
                        getRenderTransparency().activeTransparency();
1714
                } catch (NullPointerException e) {
1715
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1716
                }
1717
        }
1718

    
1719
        /*
1720
         * (non-Javadoc)
1721
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getLastRenderBuffer()
1722
         */
1723
        public IBuffer getLastRenderBuffer() {
1724
                return getRender().getLastRenderBuffer();
1725
        }
1726

    
1727
        /**
1728
         *
1729
         * @return ROIs asociadas a la capa raster.
1730
         */
1731
        public ArrayList getRois() {
1732
                return rois;
1733
        }
1734

    
1735
        /**
1736
         * Establece las ROI asociadas a la capa raster.
1737
         *
1738
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1739
         */
1740
        public void setRois(ArrayList rois) {
1741
                this.rois = rois;
1742
        }
1743

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

    
1767
        /**
1768
         * @param noDataType the noDataType to set
1769
         */
1770
        public void setNoDataType(int noDataType) {
1771
                this.noDataType = noDataType;
1772
                if (dataset != null)
1773
                        dataset.setNoDataEnabled(noDataType != RasterLibrary.NODATATYPE_DISABLED);
1774
        }
1775

    
1776
        /**
1777
         * @return the configuration
1778
         */
1779
        static public IConfiguration getConfiguration() {
1780
                return configuration;
1781
        }
1782

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

    
1817
                return false;
1818
        }
1819

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

    
1833
        /*****************************************************/
1834
        //Utils
1835

    
1836
        /**
1837
         * Ajusta las coordenadas especificadas en el par?metro al ?rea m?xima
1838
         * del raster en p?xeles.
1839
         * @param req Punto a ajustar dentro del extener del raster
1840
         */
1841
        public Point2D adjustWorldRequest(Point2D req) {
1842
                Rectangle2D ext = null;
1843

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

    
1875
                // Asignamos los valores noData del original
1876
                newLayer.setNoDataValue(getNoDataValue());
1877
                newLayer.setNoDataType(getNoDataType());
1878
                newLayer.applyNoData();
1879

    
1880
                return newLayer;
1881
        }
1882
        
1883
        /*****************************************************/
1884

    
1885
        public void disableStopped() {state.disableStopped();}
1886

    
1887
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1888

    
1889
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
1890

    
1891
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1892

    
1893
        public void enableStopped() {state.enableStopped();}
1894

    
1895
        public boolean isAwake() {return state.isAwake();}
1896

    
1897
        public boolean isClosed() {return state.isClosed();}
1898

    
1899
        public boolean isOpen() {return state.isOpen();}
1900

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