Statistics
| Revision:

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

History | View | Annotate | Download (56.5 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.crs.repository.EpsgRepository;
43
import org.gvsig.fmap.raster.legend.ColorTableLegend;
44
import org.gvsig.jogr.CrsGdalException;
45
import org.gvsig.jogr.OGRException;
46
import org.gvsig.jogr.OGRSpatialReference;
47
import org.gvsig.raster.RasterLibrary;
48
import org.gvsig.raster.buffer.BufferFactory;
49
import org.gvsig.raster.dataset.CompositeDataset;
50
import org.gvsig.raster.dataset.FileNotOpenException;
51
import org.gvsig.raster.dataset.IBuffer;
52
import org.gvsig.raster.dataset.IRasterDataSource;
53
import org.gvsig.raster.dataset.InvalidSetViewException;
54
import org.gvsig.raster.dataset.MosaicNotValidException;
55
import org.gvsig.raster.dataset.MultiRasterDataset;
56
import org.gvsig.raster.dataset.NotSupportedExtensionException;
57
import org.gvsig.raster.dataset.RasterDataset;
58
import org.gvsig.raster.dataset.io.RasterDriverException;
59
import org.gvsig.raster.dataset.properties.DatasetMetadata;
60
import org.gvsig.raster.datastruct.ColorTable;
61
import org.gvsig.raster.datastruct.Extent;
62
import org.gvsig.raster.datastruct.ViewPortData;
63
import org.gvsig.raster.datastruct.serializer.ColorTableLibraryPersistence;
64
import org.gvsig.raster.grid.Grid;
65
import org.gvsig.raster.grid.GridException;
66
import org.gvsig.raster.grid.GridPalette;
67
import org.gvsig.raster.grid.GridTransparency;
68
import org.gvsig.raster.grid.filter.FilterTypeException;
69
import org.gvsig.raster.grid.filter.RasterFilterList;
70
import org.gvsig.raster.grid.filter.RasterFilterListManager;
71
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
72
import org.gvsig.raster.grid.filter.enhancement.EnhancementStretchListManager;
73
import org.gvsig.raster.grid.filter.enhancement.LinearStretchParams;
74
import org.gvsig.raster.grid.render.Rendering;
75
import org.gvsig.raster.hierarchy.IRasterDataset;
76
import org.gvsig.raster.hierarchy.IRasterOperations;
77
import org.gvsig.raster.hierarchy.IRasterProperties;
78
import org.gvsig.raster.hierarchy.IStatistics;
79
import org.gvsig.raster.process.RasterTask;
80
import org.gvsig.raster.process.RasterTaskQueue;
81
import org.gvsig.raster.util.ColorConversion;
82
import org.gvsig.raster.util.Historical;
83
import org.gvsig.raster.util.MathUtils;
84
import org.gvsig.raster.util.RasterToolsUtil;
85

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

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

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

    
159
        static {
160
                 RasterLibrary.wakeUp();
161
        }
162

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

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

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

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

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

    
214
                //Si la capa tiene nombre acivamos el estado awake
215
                if(getLoadParams() != null && name != null) {
216
                        try {
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
                String code = null;
330
                try {
331
                        if(dataset.getWktProjection() != null && !dataset.getWktProjection().equals("")) {
332
                                OGRSpatialReference oSRSSource = new OGRSpatialReference();
333
                                        try {
334
                                                OGRSpatialReference.importFromWkt(oSRSSource, dataset.getWktProjection());
335
                                        if(!oSRSSource.isGeographic())
336
                                                code = oSRSSource.getAuthorityCode("PROJCS");
337
                                        else
338
                                                code = oSRSSource.getAuthorityCode("GEOGCS");
339
                                        EpsgRepository epsgRep = new EpsgRepository();
340
                                        try {
341
                                                return epsgRep.getCrs(code);
342
                                        } catch (NumberFormatException ex) {
343
                                                return null;
344
                                        }
345
                                } catch (OGRException e) {
346
                                        Logger.getLogger(getClass().getName()).debug("Problemas obteniendo el c?digo EPSG", e);
347
                                } catch (CrsGdalException e) {
348
                                        Logger.getLogger(getClass().getName()).debug("Problemas obteniendo el c?digo EPSG", e);
349
                                }
350
                        }                                
351
                        
352
                } catch (RasterDriverException e1) {
353
                        Logger.getLogger(getClass().getName()).debug("Problemas accediendo a getWktProjection. Driver no inicializado", e1);
354
                }
355
                return null;
356
        }
357
        
358
        /**
359
         * Crea el objeto renderizador de raster
360
         * @return Rendering
361
         */
362
        public Rendering getRender() {
363
                if (render == null)
364
                        render = new Rendering(bufferFactory);
365
                return render;
366
        }
367
        
368
        /**
369
         * Aplica los filtros noData al layer
370
         * @param rasterSE
371
         * @param filterManager
372
         */
373
        public void applyNoData() {
374
                Boolean noDataEnabled = configuration.getValueBoolean("nodata_transparency_enabled", Boolean.FALSE);
375
                if (noDataEnabled.booleanValue() && getDataSource().isNoDataEnabled()) {
376
                        noDataType = RasterLibrary.NODATATYPE_LAYER;
377
                        Double noDataValue = Double.valueOf(getNoDataValue());
378
                        getDataSource().getTransparencyFilesStatus().setNoData(noDataValue.doubleValue());
379
                } else {
380
                        getDataSource().getTransparencyFilesStatus().activeNoData(false);
381
                        noDataType = RasterLibrary.NODATATYPE_DISABLED;
382
                }
383
        }
384

    
385
        /**
386
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
387
         */
388
        private void initFilters() {
389
                RasterFilterList filterList = new RasterFilterList();
390
                filterList.addEnvParam("IStatistics", getDataSource().getStatistics());
391
                filterList.addEnvParam("MultiRasterDataset", getDataSource());
392
                
393
                getDataSource().resetNoDataValue();
394
                applyNoData();
395
                GridTransparency gridTransparency = new GridTransparency(getDataSource().getTransparencyFilesStatus());
396

    
397
                filterList.setInitDataType(getDataType()[0]);
398
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
399

    
400
                try {
401
                        if (this.getDataSource().getColorTables()[0] != null) {
402
                                GridPalette p = new GridPalette(getDataSource().getColorTables()[0]);
403
                                setLastLegend(p);
404
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
405
                                ctm.addColorTableFilter(p);
406
                        } else {
407
                                if (getDataType()[0] != IBuffer.TYPE_BYTE) {
408
                                        loadEnhancedOrColorTable(filterManager);
409
                                }
410
                        }
411

    
412
                        getRender().setFilterList(filterList);
413
                        // Inicializo la transparencia para el render
414
                        getRender().setLastTransparency(gridTransparency);
415
                } catch (FilterTypeException e) {
416
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
417
                        RasterToolsUtil.debug("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
418
                }
419
        }
420

    
421
        /**
422
         * Mira la configuracion para saber si debe cargar un realce o una tabla
423
         * de color por defecto
424
         * @param filterManager
425
         * @throws FilterTypeException
426
         */
427
        private void loadEnhancedOrColorTable(RasterFilterListManager filterManager) throws FilterTypeException {
428
                String colorTableName = configuration.getValueString("loadlayer_usecolortable", (String) null);
429

    
430
                String palettesPath = System.getProperty("user.home") +
431
                        File.separator +
432
                        "gvSIG" + // PluginServices.getArguments()[0] +
433
                        File.separator + "colortable";
434

    
435
                IStatistics stats = getDataSource().getStatistics();
436

    
437
                if (colorTableName != null) {
438
                        try {
439
                                stats.calcFullStatistics();
440
                                if (getBandCount() == 1) {
441
                                        ArrayList fileList = ColorTableLibraryPersistence.getPaletteFileList(palettesPath);
442
                                        for (int i = 0; i < fileList.size(); i++) {
443
                                                ArrayList paletteItems = new ArrayList();
444
                                                String paletteName = ColorTableLibraryPersistence.loadPalette(palettesPath, (String) fileList.get(i), paletteItems);
445
                                                if (paletteName.equals(colorTableName)) {
446
                                                        if (paletteItems.size() <= 0)
447
                                                                continue;
448

    
449
                                                        ColorTable colorTable = new ColorTable();
450
                                                        colorTable.setName(paletteName);
451
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
452
                                                        colorTable.setInterpolated(true);
453

    
454
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
455

    
456
                                                        GridPalette p = new GridPalette(colorTable);
457
                                                        setLastLegend(p);
458

    
459
                                                        ColorTableListManager ctm = new ColorTableListManager(filterManager);
460
                                                        ctm.addColorTableFilter(p);
461
                                                        return;
462
                                                }
463
                                        }
464
                                }
465
                        } catch (FileNotOpenException e) {
466
                                // No podemos aplicar el filtro
467
                        } catch (RasterDriverException e) {
468
                                // No podemos aplicar el filtro
469
                        } catch (InterruptedException e) {
470
                                // El usuario ha cancelado el proceso
471
                        }
472
                }
473

    
474
                /*EnhancementListManager elm = new EnhancementListManager(filterManager);
475
                elm.addEnhancedFilter(false, stats, 0.0, getRender().getRenderBands());*/
476
                
477
                EnhancementStretchListManager elm = new EnhancementStretchListManager(filterManager);
478
                try {
479
                        elm.addEnhancedStretchFilter(LinearStretchParams.createStandardParam(getBandCount(), 0.0, stats, false), 
480
                                                                                stats, 
481
                                                                                getRender().getRenderBands(), 
482
                                                                                false);
483
                } catch (FileNotOpenException e) {
484
                        //No podemos aplicar el filtro
485
                } catch (RasterDriverException e) {
486
                        //No podemos aplicar el filtro
487
                }
488
        }
489

    
490
        /**
491
         * @throws ReadDriverException
492
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
493
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
494
         *                 com.iver.utiles.swing.threads.Cancellable)
495
         */
496
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadDriverException {
497
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
498
                task.setEvent(null);
499

    
500
                try {
501
                        if (!isOpen())
502
                                return;
503

    
504
                        enableStopped();
505
                        // callLegendChanged(null);
506

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

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

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

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

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

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

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

    
638
        /**
639
         * Obtiene el valor del pixel del Image en la posici?n real x,y
640
         * @param x Posici?n x
641
         * @param y Posici?n y
642
         * @return valor de pixel
643
         */
644
        public int[] getPixel(double wcx, double wcy) {
645
                if (!isOpen())
646
                        return null;
647

    
648
                int[] argb = { -1, -1, -1, -1 };
649
                if (wcx <= getMaxX() && wcx >= getMinX() && wcy <= getMaxY() && wcy >= getMinY()) {
650
                        View theView = (View) PluginServices.getMDIManager().getActiveWindow();
651
                        if (theView instanceof IView) {
652
                                // BufferedImage buf = ((IView) theView).getMapControl().getImage();
653
                                Point2D p = ((IView) theView).getMapControl().getViewPort().fromMapPoint(wcx, wcy);
654
                                return getPixel((int) p.getX(), (int) p.getY());
655
                        }
656
                }
657
                return argb;
658
        }
659

    
660
        /**
661
         * Obtiene el valor del pixel del Image en la posici?n x,y
662
         * @param x Posici?n x
663
         * @param y Posici?n y
664
         * @return valor de pixel
665
         */
666
        public int[] getPixel(int pxx, int pxy) {
667
                if (!isOpen())
668
                        return null;
669
                //TODO: Esto hay que rehacerlo ya que es dependiente de la vista
670
                int[] argb = { -1, -1, -1, -1 };
671
                View theView = (View) PluginServices.getMDIManager().getActiveWindow();
672
                BufferedImage buf = null;
673
                if (theView instanceof IView)
674
                        buf = ((IView) theView).getMapControl().getImage();
675
                if (pxx >= 0 && pxx < buf.getWidth() && pxy >= 0 && pxy < buf.getHeight()) {
676
                        if (theView instanceof IView) {
677
                                int value = buf.getRGB(pxx, pxy);
678
                                argb[0] = ((value & 0xff000000) >> 24);
679
                                argb[1] = ((value & 0x00ff0000) >> 16);
680
                                argb[2] = ((value & 0x0000ff00) >> 8);
681
                                argb[3] = (value & 0x000000ff);
682
                        }
683
                }
684
                return argb;
685
        }
686

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

    
697
        /*
698
         * (non-Javadoc)
699
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
700
         */
701
        public double getMaxY() {
702
                if(getFullExtent() != null)
703
                        return this.getFullExtent().getMaxY();
704
                return -1;
705
        }
706

    
707
        /*
708
         * (non-Javadoc)
709
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinX()
710
         */
711
        public double getMinX() {
712
                if(getFullExtent() != null)
713
                        return getFullExtent().getMinX();
714
                return -1;
715
        }
716

    
717
        /*
718
         * (non-Javadoc)
719
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinY()
720
         */
721
        public double getMinY() {
722
                if(getFullExtent() != null)
723
                        return getFullExtent().getMinY();
724
                return -1;
725
        }
726

    
727
        /* (non-Javadoc)
728
         * @deprecated. See String getInfo(Point p) throws DriverException
729
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
730
         */
731
        public String queryByPoint(Point p) {
732
                if (!isOpen())
733
                        return null;
734
                ColorConversion conv = new ColorConversion();
735

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

    
738
                ArrayList attr = getAttributes();
739
                data += "  <raster\n";
740
                data += "    File=\"" + getFile() + "\"\n";
741
                for (int i = 0; i < attr.size(); i++) {
742
                        Object[] a = (Object[]) attr.get(i);
743

    
744
                        data += "    " + a[0].toString() + "=";
745
                        if (a[1].toString() instanceof String)
746
                                data += "\"" + a[1].toString() + "\"\n";
747
                        else
748
                                data += a[1].toString() + "\n";
749
                }
750
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
751
                data += "    Point_WC=\"" + MathUtils.format(posXWC, 3) + " , " + MathUtils.format(posYWC, 3) + "\"\n";
752
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
753
                double[] cmyk = conv.RGBtoCMYK(r & 0xff, g & 0xff, b & 0xff, 1D);
754
                data += "    CMYK=\"" + MathUtils.format(cmyk[0], 4) + ", " + MathUtils.format(cmyk[1], 4) + ", " + MathUtils.format(cmyk[2], 4) + "," + MathUtils.format(cmyk[3], 4) + "\"\n";
755
                double[] hsl = conv.RGBtoHSL(r & 0xff, g & 0xff, b & 0xff);
756
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
757
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
758
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
759
                data += "    HSL=\"" + MathUtils.format(hsl[0], 4) + ", " + MathUtils.format(hsl[1], 4) + ", " + MathUtils.format(hsl[2], 4) + "\"\n";
760
                data += "  />\n";
761

    
762
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
763
                return data;
764
        }
765

    
766
        /*
767
         * (non-Javadoc)
768
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo(java.awt.Point, double, com.iver.utiles.swing.threads.Cancellable)
769
         */
770
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException {
771
                if (!isOpen()) {
772
                        StringXMLItem[] item = new StringXMLItem[1];
773
                        String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
774
                        data += "  <raster\n" + "  Layer=\" Not available\"\n" + "  />\n";
775
                        data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
776
                        item[0] = new StringXMLItem(data, this);
777
                        return item;
778
                }
779

    
780
                Point2D pReal = getMapContext().getViewPort().toMapPoint(p);
781
                Point2D px = new Point2D.Double();
782
                if(        pReal.getX() > this.getMinX() &&
783
                        pReal.getX() < this.getMaxX() &&
784
                        pReal.getY() > this.getMinY() &&
785
                        pReal.getY() < this.getMaxY()) {
786

    
787
                        AffineTransform at = this.getDataSource().getAffineTransform();
788
                        px = new Point2D.Double(pReal.getX(), pReal.getY());
789
                        try {
790
                                at.inverseTransform(px, px);
791
                        } catch (NoninvertibleTransformException e) {
792
                                throw new ReadDriverException("Error en la transformaci?n del punto", e);
793
                        }
794
                }
795
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
796
                ColorConversion conv = new ColorConversion();
797

    
798
                StringXMLItem[] item = new StringXMLItem[1];
799
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
800

    
801
                data += "  <raster\n";
802
                data += "    View_Point=\"" + p.getX() + " , " + p.getY() + "\"\n";
803
                data += "    World_Point=\"" + MathUtils.format(pReal.getX(), 3) + " , " + MathUtils.format(pReal.getY(), 3) + "\"\n";
804
                if (px == null)
805
                        data += "    Pixel_Point=\"Out\"\n";
806
                else
807
                        data += "    Pixel_Point=\"" + (int) px.getX() + " , " + (int) px.getY() + "\"\n";
808
                data += "    RGB=\"" + rgb[1] + "  " + rgb[2] + "  " + rgb[3] + "\"\n";
809
                double[] cmyk = conv.RGBtoCMYK(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff, 1D);
810
                data += "    CMYK=\"" + MathUtils.format(cmyk[0], 4) + ", " + MathUtils.format(cmyk[1], 4) + ", " + MathUtils.format(cmyk[2], 4) + "," + MathUtils.format(cmyk[3], 4) + "\"\n";
811
                double[] hsl = conv.RGBtoHSL(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff);
812
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
813
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
814
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
815
                data += "    HSL=\"" + MathUtils.format(hsl[0], 4) + ", " + MathUtils.format(hsl[1], 4) + ", " + MathUtils.format(hsl[2], 4) + "\"\n";
816
                data += "    Band_Value=\"";
817
                try {
818
                        if (px != null) {
819
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3){
820
                                        for(int i = 0; i < getBandCount(); i++)
821
                                                data += ((Integer)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).intValue() + "  ";
822
                                }
823
                                if(getDataType()[0] == 4){
824
                                        for(int i = 0; i < getBandCount(); i++)
825
                                                data += ((Float)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).floatValue() + "  ";
826
                                }
827
                                if(getDataType()[0] == 5){
828
                                        for(int i = 0; i < getBandCount(); i++)
829
                                                data += ((Double)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).doubleValue() + "  ";
830
                                }
831
                        }
832
                } catch (RasterDriverException ex) {
833
                        throw new ReadDriverException("Error en el acceso al dataset", ex);
834
                } catch (InvalidSetViewException ex) {
835
                        throw new ReadDriverException("Error en la asignaci?n de la vista en getData", ex);
836
                } catch (FileNotOpenException ex) {
837
                        throw new ReadDriverException("Fichero no abierto en el dataset", ex);
838
                }
839
                data += "\"\n";
840
                data += "  />\n";
841
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
842

    
843
                item[0] = new StringXMLItem(data, this);
844
                return item;
845
        }
846

    
847
        /**
848
         * Filters a string for being suitable as XML Tag, erasing
849
         * all not alphabetic or numeric characters.
850
         * @param s
851
         * @return string normalized
852
         */
853
        private String normalizeAsXMLTag(String s) {
854
                return s.replaceAll("[^a-zA-Z0-9]", "");
855
        }
856

    
857
        /**
858
         * Obtiene atributos a partir de un georasterfile
859
         * @return
860
         */
861
        public ArrayList getAttributes() {
862
                ArrayList attr = new ArrayList();
863
                if(!isOpen())
864
                        return attr;
865
                Object [][] a = {
866
                        {"Filename", dataset.getDataset(0)[0].getFName()},
867
                        {"Filesize", new Long(dataset.getFileSize())},
868
                        {"Width", new Integer((int)dataset.getWidth())},
869
                        {"Height", new Integer((int)dataset.getHeight())},
870
                        {"Bands", new Integer(dataset.getBandCount())}
871
                };
872
                for (int i = 0; i < a.length; i++)
873
                        attr.add(a[i]);
874
                return attr;
875
        }
876

    
877
        /**
878
         * Escribe en el proyecto la capa actual
879
         * @throws XMLException
880
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
881
         */
882
        public XMLEntity getXMLEntity() throws XMLException {
883
                if(isClosed() || isAwake())
884
                        return null;
885

    
886
                XMLEntity xml = super.getXMLEntity();
887
                if(getFile() != null)
888
                        xml.putProperty("file", getFile());
889
                xml.putProperty("driverName", "gvSIG Raster Driver");
890

    
891
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
892
                if (status == null)
893
                        status = new StatusLayerRaster();
894
                status.getXMLEntity(xml, true, this);
895

    
896
                return xml;
897
        }
898

    
899
        public void setXMLEntity03(XMLEntity xml) throws XMLException {
900
        }
901

    
902
        /**
903
         * Recupera de disco los datos de la capa.
904
         */
905
        public void setXMLEntity(XMLEntity xml) throws XMLException {
906
                super.setXMLEntity(xml);
907

    
908
                try {
909
                        params = new File(xml.getStringProperty("file"));
910

    
911
                        if(params != null && getName() != null && getName().compareTo("") != 0) {
912
                                try {
913
                                        enableAwake();
914
                                } catch (NotAvailableStateException e) {
915
                                        Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
916
                                }
917
                        }
918
                        if(!super.getFLayerStatus().visible)
919
                                enableStopped();
920

    
921
                        // Para notificar al adapter-driver cual es la proyecci?n.
922
                        setProjection(super.getProjection());
923

    
924
                        //Inicializamos la clase a la que se usa por defecto para
925
                        //compatibilidad con proyectos antiguos
926
                        String claseStr = StatusLayerRaster.defaultClass;
927
                        if (xml.contains("raster.class"))
928
                                claseStr = xml.getStringProperty("raster.class");
929

    
930
                        if (status != null)
931
                                status.setXMLEntity(xml, this);
932
                        else {
933
                                // Cuando cargamos un proyecto
934

    
935
                                if (claseStr != null && !claseStr.equals("")) {
936
                                        try {
937
                                                Class clase = LayerFactory.getLayerClassForLayerClassName(claseStr);
938
                                                Constructor constr = clase.getConstructor(null);
939
                                                status = (IStatusRaster) constr.newInstance(null);
940
                                                if (status != null) {
941
                                                        ((StatusLayerRaster)status).setNameClass(claseStr);
942
                                                        status.setXMLEntity(xml, this);
943
                                                        filterArguments = status.getFilterArguments();
944
                                                        crearColorTable();
945
                                                }
946
                                        } catch (ClassNotFoundException exc) {
947
                                                throw new XMLException(exc);
948
                                        } catch (InstantiationException exc) {
949
                                                throw new XMLException(exc);
950
                                        } catch (IllegalAccessException exc) {
951
                                                throw new XMLException(exc);
952
                                        } catch (NoSuchMethodException exc) {
953
                                                throw new XMLException(exc);
954
                                        } catch (InvocationTargetException exc) {
955
                                                throw new XMLException(exc);
956
                                        }
957
                                }
958
                        }
959
                        firstLoad = true;
960
                } catch (NotExistInXMLEntity e) {
961

    
962
                }
963
        }
964

    
965
        private void crearColorTable() {
966
                ArrayList color = (ArrayList) filterArguments.clone();
967
                setLastLegend(ColorTableListManager.createColorTableFromArray(color));
968
        }
969

    
970
        /* (non-Javadoc)
971
         * @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)
972
         */
973
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet propeties) throws ReadDriverException {
974

    
975
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
976
                        return;
977

    
978
                isPrinting = true;
979
                if (!mustTilePrint) {
980
                        draw(null, g, viewPort, cancel,scale);
981
                } else {
982
                        // Para no pedir imagenes demasiado grandes, vamos
983
                        // a hacer lo mismo que hace EcwFile: chunkear.
984
                        // Llamamos a drawView con cuadraditos m?s peque?os
985
                        // del BufferedImage ni caso, cuando se imprime viene con null
986
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
987
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
988

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

    
992
                        //RasterStats stats = getSource().getFilterStack().getStats();
993
                        //if(stats != null)
994
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
995

    
996

    
997
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
998
                                // Parte que dibuja
999
                                try {
1000
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1001
                                        draw(null, g, vp, cancel, scale);
1002
                                } catch (NoninvertibleTransformException e) {
1003
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
1004
                                }
1005
                        }
1006
                        /*if(stats != null){
1007
                                getSource().getFilterStack().getStats().history.clear();
1008
                                stats = getSource().getFilterStack().getStats();
1009
                        }*/
1010
                }
1011
                isPrinting = false;
1012
        }
1013

    
1014
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale) throws ReadDriverException {
1015
                if(!isOpen())
1016
                        return;
1017

    
1018
                // Para no pedir imagenes demasiado grandes, vamos
1019
                // a hacer lo mismo que hace EcwFile: chunkear.
1020
                // Llamamos a drawView con cuadraditos m?s peque?os
1021
                // del BufferedImage ni caso, cuando se imprime viene con null
1022

    
1023
                int numW, numH;
1024
                int stepX, stepY;
1025
                int xProv, yProv;
1026
                int A = 1500;
1027
                int H = 1500;
1028
                int altoAux, anchoAux;
1029

    
1030
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
1031

    
1032
                // Vamos a hacerlo en trozos de AxH
1033
                Rectangle r = g.getClipBounds();
1034
                numW = (int) (r.width) / A;
1035
                numH = (int) (r.height) / H;
1036

    
1037
                double[] srcPts = new double[8];
1038
                double[] dstPts = new double[8];
1039

    
1040
                yProv = (int) r.y;
1041
                for (stepY = 0; stepY < numH + 1; stepY++) {
1042
                        if ((yProv + H) > r.getMaxY())
1043
                                altoAux = (int) r.getMaxY() - yProv;
1044
                        else
1045
                                altoAux = H;
1046

    
1047
                        xProv = (int) r.x;
1048
                        for (stepX = 0; stepX < numW + 1; stepX++) {
1049
                                if ((xProv + A) > r.getMaxX())
1050
                                        anchoAux = (int) r.getMaxX() - xProv;
1051
                                else
1052
                                        anchoAux = A;
1053

    
1054
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
1055

    
1056
                                // Parte que dibuja
1057
                                srcPts[0] = xProv;
1058
                                srcPts[1] = yProv;
1059
                                srcPts[2] = xProv + anchoAux + 1;
1060
                                srcPts[3] = yProv;
1061
                                srcPts[4] = xProv + anchoAux + 1;
1062
                                srcPts[5] = yProv + altoAux + 1;
1063
                                srcPts[6] = xProv;
1064
                                srcPts[7] = yProv + altoAux + 1;
1065

    
1066
                                try {
1067
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
1068
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
1069
                                        // Extent extent = new Extent(rectCuadricula);
1070

    
1071
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
1072
                                        ViewPort vp = viewPort.cloneViewPort();
1073
                                        vp.setImageSize(tam);
1074
                                        vp.setExtent(rectCuadricula);
1075
                                        vp.setAffineTransform(mat);
1076
                                        draw(null, g, vp, cancel, scale);
1077

    
1078
                                } catch (NoninvertibleTransformException e) {
1079
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
1080
                                }
1081
                                // Fin parte que dibuja
1082
                                xProv = xProv + A;
1083
                        }
1084
                        yProv = yProv + H;
1085
                }
1086
        }
1087

    
1088
        /**
1089
         * Borra de la lista de listeners el que se pasa como par?metro.
1090
         *
1091
         * @param o LayerListener a borrar.
1092
         *
1093
         * @return True si ha sido correcto el borrado del Listener.
1094
         */
1095
        public boolean removeLayerListener(LayerListener o) {
1096
                //Salva a RMF
1097
                try {
1098
                        if(this.getDataSource() != null)
1099
                                this.getDataSource().saveRmfModification();
1100
                } catch (IOException e) {
1101
                        //No se ha salvado nada
1102
                }
1103

    
1104
                if (this.isRemoveRasterFlag()) {
1105
                        if(dataset != null)
1106
                                dataset.close();
1107
                        if(bufferFactory != null)
1108
                                bufferFactory.free();
1109
                        bufferFactory = null;
1110
                        dataset = null;
1111
                        render = null;
1112
                        try {
1113
                                enableClosed();
1114
                        } catch (NotAvailableStateException e1) {
1115
                                // No se ha podido cambiar el estado de la capa a cerrado
1116
                        }
1117

    
1118
                        //System.gc();
1119
                        this.setRemoveRasterFlag(true);
1120
                }
1121
                return super.layerListeners.remove(o);
1122
        }
1123

    
1124
        /**
1125
         * @return Returns the removeRasterFlag.
1126
         */
1127
        public boolean isRemoveRasterFlag() {
1128
                return removeRasterFlag;
1129
        }
1130

    
1131
        /**
1132
         * Asigna el valor del flag que dice si destruimos la memoria del raster
1133
         * al eliminarlo del TOC o  no.
1134
         * @param removeRasterFlag The removeRasterFlag to set.
1135
         */
1136
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1137
                this.removeRasterFlag = removeRasterFlag;
1138
        }
1139

    
1140
        /*
1141
         * (non-Javadoc)
1142
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1143
         */
1144
        public ImageIcon getTocImageIcon() {
1145
                /*if(!isOpen())
1146
                        return new ImageIcon(MapControl.class.getResource("images/map_ico_ko.gif"));*/
1147
                return PluginServices.getIconTheme().get("map-ok-ico");
1148
        }
1149

    
1150
        /*
1151
         *  (non-Javadoc)
1152
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1153
         */
1154
        public int[] getTileSize() {
1155
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1156
                return size;
1157
        }
1158

    
1159
        /*
1160
         *  (non-Javadoc)
1161
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1162
         */
1163
        public boolean isTiled() {
1164
                return mustTileDraw;
1165
        }
1166

    
1167
        /**
1168
         * Obtiene el flag que dice si la imagen est? o no georreferenciada
1169
         * @return true si est? georreferenciada y false si no lo est?.
1170
         */
1171
        public boolean isGeoreferenced() {
1172
                return dataset.isGeoreferenced();
1173
        }
1174

    
1175
        /**
1176
         * Get datasource object
1177
         * @return
1178
         */
1179
        public BufferFactory getBufferFactory(){
1180
                return bufferFactory;
1181
        }
1182

    
1183
        /**
1184
         * Obtiene el valor NoData asociado al raster.
1185
         * @return double
1186
         */
1187
        public double getNoDataValue() {
1188
                if (dataset == null)
1189
                        return RasterLibrary.defaultNoDataValue;
1190
                return dataset.getNoDataValue();
1191
        }
1192

    
1193
        /**
1194
         * Asigna el valor no data asociado a la capa
1195
         * @param nd
1196
         */
1197
        public void setNoDataValue(double nd) {
1198
                if (bufferFactory != null)
1199
                        bufferFactory.setNoDataToFill(nd);
1200
                if (dataset != null)
1201
                        dataset.setNoDataValue(nd);
1202
        }
1203

    
1204
        /*
1205
         * (non-Javadoc)
1206
         * @see org.gvsig.fmap.raster.IRasterOperations#getPXHeight()
1207
         */
1208
        public double getPxHeight() {
1209
                return dataset.getHeight();
1210
        }
1211

    
1212
        /*
1213
         * (non-Javadoc)
1214
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
1215
         */
1216
        public double getPxWidth() {
1217
                return dataset.getWidth();
1218
        }
1219

    
1220
        /*
1221
         * (non-Javadoc)
1222
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCHeight()
1223
         */
1224
        public double getWCHeight() {
1225
                return getFullExtent().getHeight();
1226
        }
1227

    
1228
        /*
1229
         * (non-Javadoc)
1230
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
1231
         */
1232
        public double getWCWidth() {
1233
                return getFullExtent().getWidth();
1234
        }
1235

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

    
1248
        /*
1249
         * (non-Javadoc)
1250
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
1251
         */
1252
        public String[] getFileName(){
1253
                int nFiles = dataset.getDatasetCount();
1254
                String[] s = new String[nFiles];
1255
                for (int i = 0; i < nFiles; i++)
1256
                        s[i] = dataset.getDataset(i)[0].getFName();
1257
                return s;
1258
        }
1259

    
1260
        /*
1261
         * (non-Javadoc)
1262
         * @see org.gvsig.fmap.raster.IRasterFile#getFileCount()
1263
         */
1264
        public int getFileCount() {
1265
                return (dataset != null) ? dataset.getDatasetCount() : 0;
1266
        }
1267

    
1268
        /*
1269
         * (non-Javadoc)
1270
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
1271
         */
1272
        public String getFileFormat() {
1273
                String fName = dataset.getDataset(0)[0].getFName();
1274
                int index = fName.lastIndexOf(".") + 1;
1275
                String ext = null;
1276
                if (index > 0)
1277
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1278
                return ext;
1279
        }
1280

    
1281
        /*
1282
         * (non-Javadoc)
1283
         * @see org.gvsig.fmap.raster.IRasterOperations#getBandCount()
1284
         */
1285
        public int getBandCount() {
1286
                return (dataset != null) ? dataset.getBandCount() : 0;
1287
        }
1288

    
1289
        /*
1290
         * (non-Javadoc)
1291
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1292
         */
1293
        public int[] getDataType() {
1294
                return dataset.getDataType();
1295
        }
1296

    
1297
        /*
1298
         * (non-Javadoc)
1299
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
1300
         */
1301
        public GridTransparency getRenderTransparency() {
1302
                return getRender().getLastTransparency();
1303
        }
1304

    
1305
        /*
1306
         * (non-Javadoc)
1307
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1308
         */
1309
        public RasterFilterList getRenderFilterList() {
1310
                return getRender().getFilterList();
1311
        }
1312

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

    
1321
        /*
1322
         * (non-Javadoc)
1323
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
1324
         */
1325
        public void setRenderBands(int[] renderBands) {
1326
                getRender().setRenderBands(renderBands);
1327
        }
1328

    
1329
        /*
1330
         * (non-Javadoc)
1331
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
1332
         */
1333
        public void setRenderFilterList(RasterFilterList filterList) {
1334
                getRender().setFilterList(filterList);
1335
        }
1336

    
1337
        /*
1338
         * (non-Javadoc)
1339
         * @see org.gvsig.raster.hierarchy.IRasterDataset#getDataSource()
1340
         */
1341
        public IRasterDataSource getDataSource() {
1342
                return dataset;
1343
        }
1344

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

    
1354
        /*
1355
         * (non-Javadoc)
1356
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
1357
         */
1358
        public void delFile(String fileName) {
1359
                if (getRender() != null)
1360
                        bufferFactory.removeFile(fileName);
1361
        }
1362

    
1363
        /*
1364
         * (non-Javadoc)
1365
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1366
         */
1367
        public Object getInfo(String key) {
1368
                if (key.equals("DriverName"))
1369
                        return "gvSIG Raster Driver";
1370
                return null;
1371
        }
1372

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

    
1386
        /*
1387
         * (non-Javadoc)
1388
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
1389
         */
1390
        public int[] getBandCountFromDataset() {
1391
                int count = dataset.getDatasetCount();
1392
                int[] bands = new int[count];
1393
                for (int i = 0; i < count; i++)
1394
                        bands[i] = dataset.getDataset(i)[0].getBandCount();
1395
                return bands;
1396
        }
1397

    
1398
        /*
1399
         * (non-Javadoc)
1400
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1401
         */
1402
        public String getColourInterpretation(int band, int dataset) {
1403
                if (this.dataset.getColorInterpretation(dataset) == null)
1404
                        return "Undefined";
1405
                return this.dataset.getColorInterpretation(dataset).get(band);
1406
        }
1407

    
1408
        /*
1409
         * (non-Javadoc)
1410
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
1411
         */
1412
        public String getWktProjection() throws RasterDriverException {
1413
                return dataset.getWktProjection();
1414
        }
1415

    
1416
        /**
1417
         * Metodo para consultar si una capa puede ser un RGB. Suponemos que es un RGB
1418
         * si tiene mas de 3 bandas, el tipo de datos es de tipo byte y su
1419
         * interpretacion de color tiene asignada los tres colores.
1420
         * @return boolean
1421
         */
1422
        public boolean isRGB() {
1423
                if ((dataset == null) || (render == null))
1424
                        return false;
1425
                
1426
                if (dataset.getBandCount() < 3)
1427
                        return false;
1428

    
1429
                if (dataset.getDataType()[0] != IBuffer.TYPE_BYTE)
1430
                        return false;
1431

    
1432
                boolean R = false;
1433
                boolean G = false;
1434
                boolean B = false;
1435

    
1436
                int[] renderBands = render.getRenderBands();
1437
                for (int i = 0; i < renderBands.length; i++) {
1438
                        if (renderBands[i] >= 0) {
1439
                                switch (i) {
1440
                                        case 0:
1441
                                                R = true;
1442
                                                break;
1443
                                        case 1:
1444
                                                G = true;
1445
                                                break;
1446
                                        case 2:
1447
                                                B = true;
1448
                                                break;
1449
                                }
1450
                        }
1451
                }
1452

    
1453
                if (R && G && B)
1454
                        return true;
1455

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

    
1495

    
1496
        /**
1497
         * Devuelve el fichero asociado a la capa o null si no tiene.
1498
         * @return Fichero.
1499
         */
1500
        public File getFile() {
1501
                return (params instanceof File) ? ((File)params) : null;
1502
        }
1503

    
1504
        /**
1505
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1506
         * @param file Fichero a consultar
1507
         * @return true si es aceptado y false si no lo es.
1508
         */
1509
        public static boolean isFileAccepted(File file) {
1510
                return RasterDataset.fileIsSupported(file.getName());
1511
        }
1512

    
1513
        /*
1514
         * (non-Javadoc)
1515
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1516
         */
1517
        public boolean existColorTable() {
1518
                return getRender().existColorTable();
1519
        }
1520

    
1521
        /**
1522
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1523
         * capa busque una leyenda valida.
1524
         * @param ct
1525
         */
1526
        public void setLastLegend(ColorTable ct) {
1527
                lastLegend = ColorTableLegend.createLegend(ct);
1528
        }
1529

    
1530
        /**
1531
         * Devuelve la Leyenda de la capa.
1532
         * @return Leyenda.
1533
         */
1534
        public ILegend getLegend() {
1535
                if (lastLegend != null)
1536
                        return lastLegend;
1537

    
1538
                return null;
1539
        }
1540

    
1541
        /*
1542
         * (non-Javadoc)
1543
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1544
         */
1545
        public void addLegendListener(LegendListener listener) {
1546
                layerChangeSupport.addLayerListener(listener);
1547
        }
1548

    
1549
        /*
1550
         *  (non-Javadoc)
1551
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1552
         */
1553
        public int getShapeType() throws ReadDriverException {
1554
                return FShape.POLYGON;
1555
        }
1556

    
1557
        /*
1558
         * (non-Javadoc)
1559
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1560
         */
1561
        public void removeLegendListener(LegendListener listener) {
1562
                layerChangeSupport.removeLayerListener(listener);
1563
        }
1564

    
1565
        /**
1566
         * Metodo que obtiene si un punto cae dentro de los l?mites de la capa
1567
         * o fuera de ellos.
1568
         * @param p Punto a calcular
1569
         * @return true si est? dentro de los l?mites y false si est? fuera
1570
         */
1571
        public boolean isInside(Point2D p) {
1572
                 return getDataSource().isInside(p);
1573
        }
1574

    
1575
        /**
1576
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1577
         * @return AffineTransform
1578
         */
1579
        public AffineTransform getAffineTransform() {
1580
                return getDataSource().getAffineTransform();
1581
        }
1582

    
1583
        /**
1584
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista
1585
         * @param transf
1586
         */
1587
        public void setAffineTransform(AffineTransform transf) {
1588
                affineTransformList.add(transf);
1589
                getDataSource().setAffineTransform(transf);
1590
        }
1591

    
1592
        /**
1593
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista.
1594
         * Esta versi?n no guarda en el historico.
1595
         * @param transf
1596
         */
1597
        public void setAT(AffineTransform transf) {
1598
                getDataSource().setAffineTransform(transf);
1599
        }
1600

    
1601
        /**
1602
         * Obtiene la lista de transformaciones que se han ido aplicando al raster.
1603
         * @return Historical. Lista de AffineTransform
1604
         */
1605
        public Historical getAffineTransformHistorical() {
1606
                return this.affineTransformList;
1607
        }
1608

    
1609
        /**
1610
         * Salva la georreferenciaci?n a fichero rmf.
1611
         * @param fName
1612
         * @throws IOException
1613
         */
1614
        public void saveGeoToRmf() throws IOException {
1615
                if(!isOpen())
1616
                        return;
1617
                getDataSource().saveGeoToRmf();
1618
                affineTransformList.clear();
1619
                affineTransformList.add(this.getAffineTransform());
1620
        }
1621

    
1622
        /*
1623
         * (non-Javadoc)
1624
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1625
         */
1626
        public boolean isActionEnabled(int action) {
1627
                switch (action) {
1628
                        case IRasterLayerActions.BANDS_FILE_LIST:
1629
                                if (existColorTable())
1630
                                        return false;
1631
                                break;
1632
                        case IRasterLayerActions.BANDS_RGB:
1633
                                if (existColorTable())
1634
                                        return false;
1635
                                break;
1636
                        case IRasterLayerActions.CREATEOVERVIEWS:
1637
                                if ((getDataSource() != null) && (getDataSource().overviewsSupport()))
1638
                                        return true;
1639
                                else
1640
                                        return false;
1641
                        case IRasterLayerActions.OPACITY:
1642
                        case IRasterLayerActions.TRANSPARENCY:
1643
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1644
                        case IRasterLayerActions.ENHANCED:
1645
                        case IRasterLayerActions.PANSHARPENING:
1646
                                return true;
1647
                }
1648
                return true;
1649
        }
1650

    
1651
        /*
1652
         * (non-Javadoc)
1653
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1654
         */
1655
        public void setVisible(boolean visibility) {
1656
                if(visibility)
1657
                        state.disableStopped();
1658
                else
1659
                        enableStopped();
1660

    
1661
                if(isAwake() || isClosed())
1662
                        try {
1663
                                this.load();
1664
                        } catch (LoadLayerException e) {
1665
                                e.printStackTrace();
1666
                        }
1667
                super.setVisible(visibility);
1668
        }
1669

    
1670
        /**
1671
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1672
         * @return valor de transparencia
1673
         */
1674
        public int getTransparency() {
1675
                try {
1676
                        return getRenderTransparency().getOpacity();
1677
                } catch (NullPointerException e) {
1678
                        return super.getTransparency();
1679
                }
1680
        }
1681

    
1682
        /**
1683
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1684
         * o no.
1685
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1686
         */
1687
        public boolean isTransparent() {
1688
                return getRenderTransparency().isTransparencyActive();
1689
        }
1690

    
1691
        /**
1692
         * Asigna la transparencia de la siguiente renderizaci?n
1693
         * @param valor de transparencia
1694
         */
1695
        public void setTransparency(int trans) {
1696
                super.setTransparency(trans);
1697
                try {
1698
                        getRenderTransparency().setOpacity(trans);
1699
                        getRenderTransparency().activeTransparency();
1700
                } catch (NullPointerException e) {
1701
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1702
                }
1703
        }
1704

    
1705
        /*
1706
         * (non-Javadoc)
1707
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getLastRenderBuffer()
1708
         */
1709
        public IBuffer getLastRenderBuffer() {
1710
                return getRender().getLastRenderBuffer();
1711
        }
1712

    
1713
        /*
1714
         * (non-Javadoc)
1715
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#cloneLayer()
1716
         */
1717
        public FLayer cloneLayer() throws Exception {
1718
                FLyrRasterSE newLayer = FLyrRasterSE.createLayer(this.getName(), params, this.getProjection());
1719
                for (int i = 0; i < dataset.getDatasetCount(); i++) {
1720
                        String name = dataset.getDataset(i)[0].getFName();
1721
                        if (!(dataset instanceof CompositeDataset) && !name.equals(this.getName()))
1722
                                newLayer.addFile(name);
1723
                }
1724
                ArrayList filters = getRender().getFilterList().getStatusCloned();
1725
        
1726
                //Hacemos una copia de las bandas a renderizar
1727
                if(getRenderBands() != null) {
1728
                        int[] rb = new int[getRenderBands().length];
1729
                        for (int i = 0; i < rb.length; i++) 
1730
                                rb[i] = getRenderBands()[i];
1731
                        newLayer.setRenderBands(rb);
1732
                }
1733
                
1734
                //Asignamos el entorno
1735
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());        
1736
                newLayer.getRender().getFilterList().setStatus(filters);
1737

    
1738
                // Asignamos los valores noData del original
1739
                newLayer.setNoDataValue(getNoDataValue());
1740
                newLayer.setNoDataType(getNoDataType());
1741
                newLayer.applyNoData();
1742

    
1743
                return newLayer;
1744
        }
1745

    
1746
        /**
1747
         *
1748
         * @return ROIs asociadas a la capa raster.
1749
         */
1750
        public ArrayList getRois() {
1751
                return rois;
1752
        }
1753

    
1754
        /**
1755
         * Establece las ROI asociadas a la capa raster.
1756
         *
1757
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1758
         */
1759
        public void setRois(ArrayList rois) {
1760
                this.rois = rois;
1761
        }
1762

    
1763
        /**
1764
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1765
         * devolver? null.
1766
         * @return TreeMap con la lista de capas a dibujar
1767
         */
1768
        public HashMap getRasterStrategy() {
1769
                if(strategy != null)
1770
                        return strategy.getStrategy();
1771
                return null;
1772
        }
1773
        
1774
        
1775
        /**
1776
         * Devuelve el tipo de valor de NoData asociado a la capa.
1777
         * Sirve para diferenciar los estados seleccionados por el usuario. Siendo
1778
         * estos '0: Sin Valor NoData', '1: NoData de Capa'(Por defecto) y '2: Personalizado'
1779
         */
1780
        /**
1781
         * @return the noDataType
1782
         */
1783
        public int getNoDataType() {
1784
                return noDataType;
1785
        }
1786

    
1787
        /**
1788
         * @param noDataType the noDataType to set
1789
         */
1790
        public void setNoDataType(int noDataType) {
1791
                this.noDataType = noDataType;
1792
                if (dataset != null)
1793
                        dataset.setNoDataEnabled(noDataType != RasterLibrary.NODATATYPE_DISABLED);
1794
        }
1795

    
1796
        /**
1797
         * @return the configuration
1798
         */
1799
        static public IConfiguration getConfiguration() {
1800
                return configuration;
1801
        }
1802

    
1803
        /**
1804
         * @param configuration the configuration to set
1805
         */
1806
        static public void setConfiguration(IConfiguration configuration) {
1807
                FLyrRasterSE.configuration = configuration;
1808
        }
1809
        
1810
        /*
1811
         * (non-Javadoc)
1812
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#reload()
1813
         */
1814
        public void reload() throws ReloadLayerException {
1815
                try {
1816
                        super.reload();
1817
                        if (getMapContext() == null)
1818
                                return;
1819
                        if (isStopped())
1820
                                disableStopped();
1821
                        load();
1822
                        getMapContext().invalidate();
1823
                } catch (LoadLayerException e) {
1824
                        setAvailable(false);
1825
                        throw new ReloadLayerException(getName(), e);
1826
                }
1827
        }
1828

    
1829
        /*****************************************************/
1830

    
1831
        public void disableStopped() {state.disableStopped();}
1832

    
1833
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1834

    
1835
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
1836

    
1837
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1838

    
1839
        public void enableStopped() {state.enableStopped();}
1840

    
1841
        public boolean isAwake() {return state.isAwake();}
1842

    
1843
        public boolean isClosed() {return state.isClosed();}
1844

    
1845
        public boolean isOpen() {return state.isOpen();}
1846

    
1847
        public boolean isStopped() {return state.isStopped();}
1848
}