Statistics
| Revision:

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

History | View | Annotate | Download (59.1 KB)

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

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

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

    
40
import org.cresques.cts.IProjection;
41
import org.gvsig.fmap.raster.legend.ColorTableLegend;
42
import org.gvsig.raster.RasterLibrary;
43
import org.gvsig.raster.buffer.BufferFactory;
44
import org.gvsig.raster.dataset.CompositeDataset;
45
import org.gvsig.raster.dataset.FileNotOpenException;
46
import org.gvsig.raster.dataset.IBuffer;
47
import org.gvsig.raster.dataset.IRasterDataSource;
48
import org.gvsig.raster.dataset.InvalidSetViewException;
49
import org.gvsig.raster.dataset.MosaicNotValidException;
50
import org.gvsig.raster.dataset.MultiRasterDataset;
51
import org.gvsig.raster.dataset.NotSupportedExtensionException;
52
import org.gvsig.raster.dataset.RasterDataset;
53
import org.gvsig.raster.dataset.io.RasterDriverException;
54
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
55
import org.gvsig.raster.dataset.properties.DatasetMetadata;
56
import org.gvsig.raster.dataset.serializer.RmfSerializerException;
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.grid.render.VisualPropertyEvent;
73
import org.gvsig.raster.grid.render.VisualPropertyListener;
74
import org.gvsig.raster.hierarchy.IRasterDataset;
75
import org.gvsig.raster.hierarchy.IRasterOperations;
76
import org.gvsig.raster.hierarchy.IRasterProperties;
77
import org.gvsig.raster.hierarchy.IStatistics;
78
import org.gvsig.raster.process.RasterTask;
79
import org.gvsig.raster.process.RasterTaskQueue;
80
import org.gvsig.raster.projection.CRS;
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.cit.gvsig.exceptions.layers.LoadLayerException;
88
import com.iver.cit.gvsig.exceptions.layers.ReloadLayerException;
89
import com.iver.cit.gvsig.fmap.ViewPort;
90
import com.iver.cit.gvsig.fmap.core.FShape;
91
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
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.utiles.NotExistInXMLEntity;
107
import com.iver.utiles.XMLEntity;
108
import com.iver.utiles.swing.threads.Cancellable;
109
/**
110
 * Capa raster
111
 * @author Nacho Brodin (nachobrodin@gmail.com)
112
 */
113
public class FLyrRasterSE extends FLyrDefault implements IRasterProperties, IRasterDataset, InfoByPoint, Classifiable, IRasterOperations, IRasterLayerActions, ILayerState, VisualPropertyListener {
114
        private boolean               mustTileDraw        = false;
115
        private boolean               mustTilePrint       = true;
116
        private int                   maxTileDrawWidth    = 200;
117
        private int                   maxTileDrawHeight   = 200;
118
        private int                   maxTilePrintWidth   = 1500;
119
        private int                   maxTilePrintHeight  = 1500;
120
        protected IStatusRaster       status              = null;
121
        private boolean               firstLoad           = false;
122
        private boolean               removeRasterFlag    = true;
123
        private Object                params              = null;
124
        protected IRasterDataSource   dataset             = null;
125
        protected Rendering           render              = null;
126
        protected BufferFactory       bufferFactory       = null;
127
        private int                   posX                = 0;
128
        private int                   posY                = 0;
129
        private double                posXWC              = 0;
130
        private int                   posYWC              = 0;
131
        private int                   r                   = 0;
132
        private int                   g                   = 0;
133
        private int                   b                   = 0;
134
        private LayerChangeSupport    layerChangeSupport  = new LayerChangeSupport();
135
        private FLyrState             state               = new FLyrState();
136
        private ArrayList             filterArguments     = null;
137
        protected ILegend             lastLegend          = null;
138
        protected ColorTable          loadedFromProject   = null;
139
        private ArrayList             rois                = null;
140
        private RasterDrawStrategy    strategy            = null;
141
        static private IConfiguration configuration       = new DefaultLayerConfiguration();
142
        
143
        private BufferedImage         image               = null;
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 params Par?metros de carga del formato. El caso m?s simple es la ruta de la capa en disco.
167
         * @param d RasterDriver.
168
         * @param f Fichero.
169
         * @param proj Proyecci?n.
170
         * @return Nueva capa de tipo raster.
171
         * @throws DriverIOException
172
         */
173
        public static FLyrRasterSE createLayer(String layerName, Object params,
174
                        IProjection proj) throws LoadLayerException {
175
                FLyrRasterSE capa = new FLyrRasterSE();
176
                capa.setLoadParams(params);
177
                capa.setName(layerName);
178
                capa.setProjection(proj);
179
                capa.load();
180
                return capa;
181
        }
182

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

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

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

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

    
215
                //Si la capa tiene nombre acivamos el estado awake
216
                if(getLoadParams() != null && name != null) {
217
                        try {
218
                                if(isClosed())
219
                                        enableAwake();
220
                        } catch (NotAvailableStateException e) {
221
                                RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
222
                        }
223
                }
224
        }
225

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

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

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

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

    
263
                enableStopped(); // Paramos la capa mientras se hace un load
264

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

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

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

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

    
318
                //Inicializaci?n del historico de transformaciones
319
                affineTransformList.clear();
320
                affineTransformList.add(this.getAffineTransform());
321

    
322
                try {
323
                        enableOpen();
324
                } catch (NotAvailableStateException e) {
325
                        RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Awake=" + isAwake(), this, e);
326
                }
327
        }
328

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

    
372
        /**
373
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
374
         */
375
        private void initFilters() {
376
                RasterFilterList filterList = new RasterFilterList();
377
                filterList.addEnvParam("IStatistics", getDataSource().getStatistics());
378
                filterList.addEnvParam("MultiRasterDataset", getDataSource());
379
                
380
                getDataSource().resetNoDataValue();
381
                applyNoData();
382
                GridTransparency gridTransparency = new GridTransparency(getDataSource().getTransparencyFilesStatus());
383

    
384
                filterList.setInitDataType(getDataType()[0]);
385
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
386

    
387
                // Quitamos la leyenda
388
                lastLegend = null;
389

    
390
                try {
391
                        //Si en la carga del proyecto se carg? una tabla de color asignamos esta
392
                        if(loadedFromProject != null) {
393
                                GridPalette p = new GridPalette(loadedFromProject);
394
                                setLastLegend(p);
395
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
396
                                ctm.addColorTableFilter(p);
397
                        } else 
398
                                //sino ponemos la tabla asociada al raster
399
                                if (this.getDataSource().getColorTables()[0] != null) {
400
                                GridPalette p = new GridPalette(getDataSource().getColorTables()[0]);
401
                                setLastLegend(p);
402
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
403
                                ctm.addColorTableFilter(p);
404
                        } else {
405
                                //sino hace lo que dice en las preferencias
406
                                if (getDataType()[0] != IBuffer.TYPE_BYTE) 
407
                                        loadEnhancedOrColorTable(filterManager);
408
                                
409
                        }
410
                        loadedFromProject = null;
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(getRenderBands(), 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
         * Devuelve si es reproyectable o no la capa
492
         * @return
493
         */
494
        public boolean isReproyectable() {
495
                if (dataset == null)
496
                        return false;
497

    
498
                int nFiles = dataset.getDatasetCount();
499
                for (int i = 0; i < nFiles; i++)
500
                        if (!dataset.getDataset(i)[0].isReproyectable())
501
                                return false;
502
                return true;
503
        }
504
        
505
        /**
506
         * @throws ReadDriverException
507
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
508
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
509
         *                 com.iver.utiles.swing.threads.Cancellable)
510
         */
511
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadDriverException {
512
                this.image = image;
513
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
514
                task.setEvent(null);
515

    
516
                try {
517
                        if (!isOpen())
518
                                return;
519

    
520
                        enableStopped();
521
                        // callLegendChanged(null);
522

    
523
                        strategy = new RasterDrawStrategy(getMapContext(), this);
524
                        strategy.stackStrategy();
525
                        HashMap tStr = strategy.getStrategy();
526
                        if (tStr != null && 
527
                                tStr.get(this) != null && 
528
                                ((Boolean) (tStr.get(this))).booleanValue() == false) {
529
                                disableStopped();
530
                                return;
531
                        }
532

    
533
                        if (isWithinScale(scale)) {
534
                                if (status != null && firstLoad) {
535
                                        if (mustTileDraw) {
536
                                                Point2D p = vp.getOffset();
537
                                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
538
                                                Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
539
                                                tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
540
                                                for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
541
                                                        // drawing part
542
                                                        try {
543
                                                                ViewPort vport = tiles.getTileViewPort(vp, tileNr);
544
//                                                                g.setClip(tiles.getClip(tileNr).x, tiles.getClip(tileNr).y, tiles.getClip(tileNr).width - 5, tiles.getClip(tileNr).height);
545
                                                                draw(image, g, vport, cancel);
546
                                                        } catch (RasterDriverException e) {
547
                                                                throw new ReadDriverException("", e);
548
                                                        } catch (InvalidSetViewException e) {
549
                                                                throw new ReadDriverException("Error al asignar la vista en el draw.", e);
550
                                                        } catch (InterruptedException e) {
551
                                                                System.out.println("Se ha cancelado el pintado");
552
//                                                                throw new ReadDriverException("Dibujado interrumpido.", e);
553
                                                        } catch (NoninvertibleTransformException e) {
554
                                                                throw new ReadDriverException("Error en la transformaci?n", e);
555
                                                        }
556
                                                }
557
                                        } else {
558
                                                try {
559
                                                        draw(image, g, vp, cancel);
560
                                                } catch (RasterDriverException e) {
561
                                                        throw new ReadDriverException("", e);
562
                                                } catch (InvalidSetViewException e) {
563
                                                        throw new ReadDriverException("Error al asignar la vista en el draw.", e);
564
                                                } catch (InterruptedException e) {
565
                                                        System.out.println("Se ha cancelado el pintado");
566
//                                                throw new ReadDriverException("Dibujado interrumpido.", e);
567
                                                }
568
                                        }
569
                                        try {
570
                                                status.applyStatus(this);
571
                                        } catch (NotSupportedExtensionException e) {
572
                                                throw new ReadDriverException("Error setting filters from a project.", e);
573
                                        } catch (RasterDriverException e) {
574
                                                throw new ReadDriverException("Error reading file from a project.", e);
575
                                        } catch (FilterTypeException e) {
576
                                                throw new ReadDriverException("Error adding filters.", e);
577
                                        }
578
                                        firstLoad = false;
579
                                }
580

    
581
                                if (mustTileDraw) {
582
                                        Point2D p = vp.getOffset();
583
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
584
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
585
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
586
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
587
                                                // drawing part
588
                                                try {
589
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
590
                                                        draw(image, g, vport, cancel);
591
                                                } catch (RasterDriverException e) {
592
                                                        throw new ReadDriverException("", e);
593
                                                } catch (InvalidSetViewException e) {
594
                                                        throw new ReadDriverException("Error al asignar la vista en el draw.", e);
595
                                                } catch (InterruptedException e) {
596
                                                        System.out.println("Se ha cancelado el pintado");
597
//                                                        throw new ReadDriverException("Dibujado interrumpido.", e);
598
                                                } catch (NoninvertibleTransformException e) {
599
                                                        throw new ReadDriverException("Error en la transformaci?n", e);
600
                                                }
601
                                        }
602
                                } else {
603
                                        try {
604
                                                draw(image, g, vp, cancel);
605
                                        } catch (RasterDriverException e) {
606
                                                throw new ReadDriverException("", e);
607
                                        } catch (InvalidSetViewException e) {
608
                                                throw new ReadDriverException("Error al asignar la vista en el draw.", e);
609
                                        } catch (InterruptedException e) {
610
                                                System.out.println("Se ha cancelado el pintado");
611
//                                        throw new ReadDriverException("Dibujado interrumpido.", e);
612
                                        }
613
                                }
614

    
615
                                if (getVirtualLayers() != null) {
616
                                        getVirtualLayers().draw(image, g, vp, cancel, scale);
617
                                }
618
                        }
619
                        //callLegendChanged(null);
620
                } finally {
621
                        disableStopped();
622
                        task.setEvent(null);
623
                }
624
        }
625

    
626
        private void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws RasterDriverException, InvalidSetViewException, InterruptedException {
627
                Rectangle2D adjustedExtent = vp.getAdjustedExtent();
628
                if (adjustedExtent == null) return;
629
                Extent e = new Extent(adjustedExtent);
630
                Dimension imgSz = vp.getImageSize();
631
                ViewPortData vp2 = new ViewPortData(vp.getProjection(), e, imgSz );
632
                vp2.setMat(vp.getAffineTransform());
633
                getRender().draw(g, vp2);
634
        }
635

    
636
        /**
637
         * Inserta la proyecci?n.
638
         *
639
         * @param proj Proyecci?n.
640
         */
641
        public void setProjection(IProjection proj) {
642
                super.setProjection(proj);
643
        }
644

    
645
        /*
646
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
647
         */
648
        public Rectangle2D getFullExtent() {
649
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
650
                //un extent aunque la capa no est? abierta
651
                if(/*!isOpen() || */dataset == null || dataset.getExtent() == null)
652
                        return null;
653
                return dataset.getExtent().toRectangle2D();
654
        }
655

    
656
        /**
657
         * Obtiene el valor del pixel del Image en la posici?n x,y
658
         * @param x Posici?n x
659
         * @param y Posici?n y
660
         * @return valor de pixel
661
         */
662
        public int[] getPixel(int pxx, int pxy) {
663
                int[] argb = { -1, -1, -1, -1 };
664
                if (!isOpen() || (image == null))
665
                        return argb;
666
                if (pxx >= 0 && pxx < image.getWidth() && pxy >= 0 && pxy < image.getHeight()) {
667
                        int value = image.getRGB(pxx, pxy);
668
                        argb[0] = ((value & 0xff000000) >> 24);
669
                        argb[1] = ((value & 0x00ff0000) >> 16);
670
                        argb[2] = ((value & 0x0000ff00) >> 8);
671
                        argb[3] = (value & 0x000000ff);
672
                }
673
                return argb;
674
        }
675

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

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

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

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

    
716
        /* (non-Javadoc)
717
         * @deprecated. See String getInfo(Point p) throws DriverException
718
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
719
         */
720
        public String queryByPoint(Point p) {
721
                if (!isOpen())
722
                        return null;
723
                ColorConversion conv = new ColorConversion();
724

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

    
727
                ArrayList attr = getAttributes();
728
                data += "  <raster\n";
729
                data += "    File=\"" + getFile() + "\"\n";
730
                for (int i = 0; i < attr.size(); i++) {
731
                        Object[] a = (Object[]) attr.get(i);
732

    
733
                        data += "    " + a[0].toString() + "=";
734
                        if (a[1].toString() instanceof String)
735
                                data += "\"" + a[1].toString() + "\"\n";
736
                        else
737
                                data += a[1].toString() + "\n";
738
                }
739
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
740
                data += "    Point_WC=\"" + MathUtils.format(posXWC, 3) + " , " + MathUtils.format(posYWC, 3) + "\"\n";
741
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
742
                double[] cmyk = conv.RGBtoCMYK(r & 0xff, g & 0xff, b & 0xff, 1D);
743
                data += "    CMYK=\"" + MathUtils.format(cmyk[0], 4) + ", " + MathUtils.format(cmyk[1], 4) + ", " + MathUtils.format(cmyk[2], 4) + "," + MathUtils.format(cmyk[3], 4) + "\"\n";
744
                double[] hsl = conv.RGBtoHSL(r & 0xff, g & 0xff, b & 0xff);
745
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
746
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
747
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
748
                data += "    HSL=\"" + MathUtils.format(hsl[0], 4) + ", " + MathUtils.format(hsl[1], 4) + ", " + MathUtils.format(hsl[2], 4) + "\"\n";
749
                data += "  />\n";
750

    
751
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
752
                return data;
753
        }
754

    
755
        /*
756
         * (non-Javadoc)
757
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo(java.awt.Point, double, com.iver.utiles.swing.threads.Cancellable)
758
         */
759
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException {
760
                if (!isOpen()) {
761
                        StringXMLItem[] item = new StringXMLItem[1];
762
                        String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
763
                        data += "  <raster\n" + "  Layer=\" Not available\"\n" + "  />\n";
764
                        data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
765
                        item[0] = new StringXMLItem(data, this);
766
                        return item;
767
                }
768

    
769
                Point2D pReal = getMapContext().getViewPort().toMapPoint(p);
770
                Point2D px = new Point2D.Double();
771
                if(        pReal.getX() > this.getMinX() &&
772
                        pReal.getX() < this.getMaxX() &&
773
                        pReal.getY() > this.getMinY() &&
774
                        pReal.getY() < this.getMaxY()) {
775

    
776
                        AffineTransform at = this.getDataSource().getAffineTransform();
777
                        px = new Point2D.Double(pReal.getX(), pReal.getY());
778
                        try {
779
                                at.inverseTransform(px, px);
780
                        } catch (NoninvertibleTransformException e) {
781
                                throw new ReadDriverException("Error en la transformaci?n del punto", e);
782
                        }
783
                }
784
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
785
                ColorConversion conv = new ColorConversion();
786

    
787
                StringXMLItem[] item = new StringXMLItem[1];
788
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
789

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

    
832
                item[0] = new StringXMLItem(data, this);
833
                return item;
834
        }
835

    
836
        /**
837
         * Filters a string for being suitable as XML Tag, erasing
838
         * all not alphabetic or numeric characters.
839
         * @param s
840
         * @return string normalized
841
         */
842
        private String normalizeAsXMLTag(String s) {
843
                return s.replaceAll("[^a-zA-Z0-9]", "");
844
        }
845

    
846
        /**
847
         * Obtiene atributos a partir de un georasterfile
848
         * @return
849
         */
850
        public ArrayList getAttributes() {
851
                ArrayList attr = new ArrayList();
852
                if(!isOpen())
853
                        return attr;
854
                Object [][] a = {
855
                        {"Filename", dataset.getDataset(0)[0].getFName()},
856
                        {"Filesize", new Long(dataset.getFileSize())},
857
                        {"Width", new Integer((int)dataset.getWidth())},
858
                        {"Height", new Integer((int)dataset.getHeight())},
859
                        {"Bands", new Integer(dataset.getBandCount())}
860
                };
861
                for (int i = 0; i < a.length; i++)
862
                        attr.add(a[i]);
863
                return attr;
864
        }
865

    
866
        /**
867
         * Escribe en el proyecto la capa actual
868
         * @throws XMLException
869
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
870
         */
871
        public XMLEntity getXMLEntity() throws XMLException {
872
                if(isClosed() || isAwake())
873
                        return null;
874

    
875
                XMLEntity xml = super.getXMLEntity();
876
                if(getFile() != null)
877
                        xml.putProperty("file", getFile());
878
                xml.putProperty("driverName", "gvSIG Raster Driver");
879

    
880
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
881
                if (status == null)
882
                        status = new StatusLayerRaster();
883
                status.getXMLEntity(xml, true, this);
884

    
885
                return xml;
886
        }
887

    
888
        public void setXMLEntity03(XMLEntity xml) throws XMLException {
889
        }
890

    
891
        /**
892
         * Recupera de disco los datos de la capa.
893
         */
894
        public void setXMLEntity(XMLEntity xml) throws XMLException {
895
                super.setXMLEntity(xml);
896

    
897
                try {
898
                        params = new File(xml.getStringProperty("file"));
899

    
900
                        if(params != null && getName() != null && getName().compareTo("") != 0) {
901
                                try {
902
                                        enableAwake();
903
                                } catch (NotAvailableStateException e) {
904
                                        RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
905
                                }
906
                        }
907
                        if(!super.getFLayerStatus().visible)
908
                                enableStopped();
909

    
910
                        // Para notificar al adapter-driver cual es la proyecci?n.
911
                        setProjection(super.getProjection());
912

    
913
                        //Inicializamos la clase a la que se usa por defecto para
914
                        //compatibilidad con proyectos antiguos
915
                        String claseStr = StatusLayerRaster.defaultClass;
916
                        if (xml.contains("raster.class"))
917
                                claseStr = xml.getStringProperty("raster.class");
918

    
919
                        if (status != null)
920
                                status.setXMLEntity(xml, this);
921
                        else {
922
                                // Cuando cargamos un proyecto
923

    
924
                                if (claseStr != null && !claseStr.equals("")) {
925
                                        try {
926
                                                Class clase = LayerFactory.getLayerClassForLayerClassName(claseStr);
927
                                                Constructor constr = clase.getConstructor(null);
928
                                                status = (IStatusRaster) constr.newInstance(null);
929
                                                if (status != null) {
930
                                                        ((StatusLayerRaster)status).setNameClass(claseStr);
931
                                                        status.setXMLEntity(xml, this);
932
                                                        filterArguments = status.getFilterArguments();
933
                                                        
934
                                                        //Creamos la tabla de color
935
                                                        ArrayList color = (ArrayList) filterArguments.clone();
936
                                                        loadedFromProject = ColorTableListManager.createColorTableFromArray(color);
937
                                                }
938
                                        } catch (ClassNotFoundException exc) {
939
                                                throw new XMLException(exc);
940
                                        } catch (InstantiationException exc) {
941
                                                throw new XMLException(exc);
942
                                        } catch (IllegalAccessException exc) {
943
                                                throw new XMLException(exc);
944
                                        } catch (NoSuchMethodException exc) {
945
                                                throw new XMLException(exc);
946
                                        } catch (InvocationTargetException exc) {
947
                                                throw new XMLException(exc);
948
                                        }
949
                                }
950
                        }
951
                        firstLoad = true;
952
                } catch (NotExistInXMLEntity e) {
953

    
954
                }
955
        }
956

    
957
        /* (non-Javadoc)
958
         * @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)
959
         */
960
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet propeties) throws ReadDriverException {
961

    
962
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
963
                        return;
964

    
965
                if (!mustTilePrint) {
966
                        draw(null, g, viewPort, cancel,scale);
967
                } else {
968
                        // Para no pedir imagenes demasiado grandes, vamos
969
                        // a hacer lo mismo que hace EcwFile: chunkear.
970
                        // Llamamos a drawView con cuadraditos m?s peque?os
971
                        // del BufferedImage ni caso, cuando se imprime viene con null
972
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
973
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
974

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

    
978
                        //RasterStats stats = getSource().getFilterStack().getStats();
979
                        //if(stats != null)
980
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
981

    
982

    
983
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
984
                                // Parte que dibuja
985
                                try {
986
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
987
                                        draw(null, g, vp, cancel, scale);
988
                                } catch (NoninvertibleTransformException e) {
989
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
990
                                }
991
                        }
992
                        /*if(stats != null){
993
                                getSource().getFilterStack().getStats().history.clear();
994
                                stats = getSource().getFilterStack().getStats();
995
                        }*/
996
                }
997
        }
998

    
999
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale) throws ReadDriverException {
1000
                if(!isOpen())
1001
                        return;
1002

    
1003
                // Para no pedir imagenes demasiado grandes, vamos
1004
                // a hacer lo mismo que hace EcwFile: chunkear.
1005
                // Llamamos a drawView con cuadraditos m?s peque?os
1006
                // del BufferedImage ni caso, cuando se imprime viene con null
1007

    
1008
                int numW, numH;
1009
                int stepX, stepY;
1010
                int xProv, yProv;
1011
                int A = 1500;
1012
                int H = 1500;
1013
                int altoAux, anchoAux;
1014

    
1015
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
1016

    
1017
                // Vamos a hacerlo en trozos de AxH
1018
                Rectangle r = g.getClipBounds();
1019
                numW = (int) (r.width) / A;
1020
                numH = (int) (r.height) / H;
1021

    
1022
                double[] srcPts = new double[8];
1023
                double[] dstPts = new double[8];
1024

    
1025
                yProv = (int) r.y;
1026
                for (stepY = 0; stepY < numH + 1; stepY++) {
1027
                        if ((yProv + H) > r.getMaxY())
1028
                                altoAux = (int) r.getMaxY() - yProv;
1029
                        else
1030
                                altoAux = H;
1031

    
1032
                        xProv = (int) r.x;
1033
                        for (stepX = 0; stepX < numW + 1; stepX++) {
1034
                                if ((xProv + A) > r.getMaxX())
1035
                                        anchoAux = (int) r.getMaxX() - xProv;
1036
                                else
1037
                                        anchoAux = A;
1038

    
1039
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
1040

    
1041
                                // Parte que dibuja
1042
                                srcPts[0] = xProv;
1043
                                srcPts[1] = yProv;
1044
                                srcPts[2] = xProv + anchoAux + 1;
1045
                                srcPts[3] = yProv;
1046
                                srcPts[4] = xProv + anchoAux + 1;
1047
                                srcPts[5] = yProv + altoAux + 1;
1048
                                srcPts[6] = xProv;
1049
                                srcPts[7] = yProv + altoAux + 1;
1050

    
1051
                                try {
1052
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
1053
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
1054
                                        // Extent extent = new Extent(rectCuadricula);
1055

    
1056
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
1057
                                        ViewPort vp = viewPort.cloneViewPort();
1058
                                        vp.setImageSize(tam);
1059
                                        vp.setExtent(rectCuadricula);
1060
                                        vp.setAffineTransform(mat);
1061
                                        draw(null, g, vp, cancel, scale);
1062

    
1063
                                } catch (NoninvertibleTransformException e) {
1064
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
1065
                                }
1066
                                // Fin parte que dibuja
1067
                                xProv = xProv + A;
1068
                        }
1069
                        yProv = yProv + H;
1070
                }
1071
        }
1072

    
1073
        /**
1074
         * Borra de la lista de listeners el que se pasa como par?metro.
1075
         *
1076
         * @param o LayerListener a borrar.
1077
         *
1078
         * @return True si ha sido correcto el borrado del Listener.
1079
         */
1080
        public boolean removeLayerListener(LayerListener o) {
1081
                // Salva a RMF
1082
                if (this.getDataSource() != null) {
1083
                        // Guardamos la GeoReferenciacion de cada dataset
1084
                        try {
1085
                                for (int i = 0; i < getDataSource().getDatasetCount(); i++) {
1086
                                        getDataSource().saveObjectToRmf(i, RasterDataset.class, getDataSource().getDataset(i)[0]);
1087
                                }
1088
                        } catch (RmfSerializerException e) {
1089
                                RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
1090
                        }
1091
                }
1092

    
1093
                if (this.isRemoveRasterFlag()) {
1094
                        String[] files = (String[]) getFileName().clone();
1095
                        if (dataset != null)
1096
                                dataset.close();
1097
                        if (bufferFactory != null)
1098
                                bufferFactory.free();
1099
                        bufferFactory = null;
1100
                        dataset = null;
1101
                        render = null;
1102
                        try {
1103
                                enableClosed();
1104
                        } catch (NotAvailableStateException e1) {
1105
                                // No se ha podido cambiar el estado de la capa a cerrado
1106
                        }
1107

    
1108
                        // System.gc();
1109
                        this.setRemoveRasterFlag(true);
1110
                        
1111
                        for (int i = 0; i < files.length; i++) {
1112
                                File file = new File(files[i]);
1113
                                File dirTemp = RasterLibrary.getTemporalFile();
1114
                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
1115
                                        file.delete();
1116
                                        
1117
                                        // Borramos todos los ficheros que puedan tener relacion con el fichero actual
1118
                                        String basefile = file.getName();
1119
                                        File basepath = file.getParentFile();
1120
                                        int last = basefile.lastIndexOf(".");
1121
                                        if (last != -1)
1122
                                                basefile = basefile.substring(0, last + 1);
1123
                                        File[] list = basepath.listFiles();
1124
                                        for (int j = 0; j < list.length; j++)
1125
                                                if (list[j].getName().startsWith(basefile))
1126
                                                        list[j].delete();
1127
                                }
1128
                        }
1129
                }
1130
                return super.layerListeners.remove(o);
1131
        }
1132

    
1133
        /**
1134
         * @return Returns the removeRasterFlag.
1135
         */
1136
        public boolean isRemoveRasterFlag() {
1137
                return removeRasterFlag;
1138
        }
1139

    
1140
        /**
1141
         * Asigna el valor del flag que dice si destruimos la memoria del raster
1142
         * al eliminarlo del TOC o  no.
1143
         * @param removeRasterFlag The removeRasterFlag to set.
1144
         */
1145
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1146
                this.removeRasterFlag = removeRasterFlag;
1147
        }
1148

    
1149
        /*
1150
         * (non-Javadoc)
1151
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1152
         */
1153
        public ImageIcon getTocImageIcon() {
1154
                return new ImageIcon(getClass().getResource("images/map_ico_ok.gif"));
1155
        }
1156

    
1157
        /*
1158
         *  (non-Javadoc)
1159
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1160
         */
1161
        public int[] getTileSize() {
1162
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1163
                return size;
1164
        }
1165

    
1166
        /*
1167
         *  (non-Javadoc)
1168
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1169
         */
1170
        public boolean isTiled() {
1171
                return mustTileDraw;
1172
        }
1173

    
1174
        /**
1175
         * Obtiene el flag que dice si la imagen est? o no georreferenciada
1176
         * @return true si est? georreferenciada y false si no lo est?.
1177
         */
1178
        public boolean isGeoreferenced() {
1179
                return dataset.isGeoreferenced();
1180
        }
1181

    
1182
        /**
1183
         * Get datasource object
1184
         * @return
1185
         */
1186
        public BufferFactory getBufferFactory(){
1187
                return bufferFactory;
1188
        }
1189

    
1190
        /**
1191
         * Obtiene el valor NoData asociado al raster.
1192
         * @return double
1193
         */
1194
        public double getNoDataValue() {
1195
                if (dataset == null)
1196
                        return RasterLibrary.defaultNoDataValue;
1197
                return dataset.getNoDataValue();
1198
        }
1199

    
1200
        /**
1201
         * Asigna el valor no data asociado a la capa
1202
         * @param nd
1203
         */
1204
        public void setNoDataValue(double nd) {
1205
                if (bufferFactory != null)
1206
                        bufferFactory.setNoDataToFill(nd);
1207
                if (dataset != null)
1208
                        dataset.setNoDataValue(nd);
1209
        }
1210

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

    
1219
        /*
1220
         * (non-Javadoc)
1221
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
1222
         */
1223
        public double getPxWidth() {
1224
                return dataset.getWidth();
1225
        }
1226

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

    
1235
        /*
1236
         * (non-Javadoc)
1237
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
1238
         */
1239
        public double getWCWidth() {
1240
                return getFullExtent().getWidth();
1241
        }
1242

    
1243
        /*
1244
         * (non-Javadoc)
1245
         * @see org.gvsig.fmap.raster.IRasterFile#getFileSize()
1246
         */
1247
        public long[] getFileSize(){
1248
                int nFiles = dataset.getDatasetCount();
1249
                long[] s = new long[nFiles];
1250
                for (int i = 0; i < nFiles; i++)
1251
                        s[i] = dataset.getDataset(i)[0].getFileSize();
1252
                return s;
1253
        }
1254

    
1255
        /*
1256
         * (non-Javadoc)
1257
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
1258
         */
1259
        public String[] getFileName(){
1260
                int nFiles = 0;
1261
                if (dataset != null)
1262
                        nFiles = dataset.getDatasetCount();
1263
                String[] s = new String[nFiles];
1264
                for (int i = 0; i < nFiles; i++)
1265
                        s[i] = dataset.getDataset(i)[0].getFName();
1266
                return s;
1267
        }
1268

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

    
1277
        /*
1278
         * (non-Javadoc)
1279
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
1280
         */
1281
        public String getFileFormat() {
1282
                String fName = dataset.getDataset(0)[0].getFName();
1283
                int index = fName.lastIndexOf(".") + 1;
1284
                String ext = null;
1285
                if (index > 0)
1286
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1287
                return ext;
1288
        }
1289

    
1290
        /*
1291
         * (non-Javadoc)
1292
         * @see org.gvsig.fmap.raster.IRasterOperations#getBandCount()
1293
         */
1294
        public int getBandCount() {
1295
                return (dataset != null) ? dataset.getBandCount() : 0;
1296
        }
1297

    
1298
        /*
1299
         * (non-Javadoc)
1300
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1301
         */
1302
        public int[] getDataType() {
1303
                return dataset.getDataType();
1304
        }
1305

    
1306
        /*
1307
         * (non-Javadoc)
1308
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
1309
         */
1310
        public GridTransparency getRenderTransparency() {
1311
                return getRender().getLastTransparency();
1312
        }
1313

    
1314
        /*
1315
         * (non-Javadoc)
1316
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1317
         */
1318
        public RasterFilterList getRenderFilterList() {
1319
                return getRender().getFilterList();
1320
        }
1321

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

    
1330
        /*
1331
         * (non-Javadoc)
1332
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
1333
         */
1334
        public void setRenderBands(int[] renderBands) {
1335
                getRender().setRenderBands(renderBands);
1336
        }
1337

    
1338
        /*
1339
         * (non-Javadoc)
1340
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
1341
         */
1342
        public void setRenderFilterList(RasterFilterList filterList) {
1343
                getRender().setFilterList(filterList);
1344
        }
1345

    
1346
        /*
1347
         * (non-Javadoc)
1348
         * @see org.gvsig.raster.hierarchy.IRasterDataset#getDataSource()
1349
         */
1350
        public IRasterDataSource getDataSource() {
1351
                return dataset;
1352
        }
1353

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

    
1363
        /*
1364
         * (non-Javadoc)
1365
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
1366
         */
1367
        public void delFile(String fileName) {
1368
                if (getRender() != null)
1369
                        bufferFactory.removeFile(fileName);
1370
        }
1371

    
1372
        /*
1373
         * (non-Javadoc)
1374
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1375
         */
1376
        public Object getInfo(String key) {
1377
                if (key.equals("DriverName"))
1378
                        return "gvSIG Raster Driver";
1379
                return null;
1380
        }
1381

    
1382
        /*
1383
         * (non-Javadoc)
1384
         * @see org.gvsig.raster.shared.IRasterOperations#getMetadata()
1385
         */
1386
        public DatasetMetadata[] getMetadata() {
1387
                int count = dataset.getDatasetCount();
1388
                DatasetMetadata[] metadata = new DatasetMetadata[count];
1389
                for (int i = 0; i < count; i++) {
1390
                        metadata[i] = dataset.getDataset(i)[0].getMetadata();
1391
                }
1392
                return metadata;
1393
        }
1394

    
1395
        /*
1396
         * (non-Javadoc)
1397
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
1398
         */
1399
        public int[] getBandCountFromDataset() {
1400
                int count = dataset.getDatasetCount();
1401
                int[] bands = new int[count];
1402
                for (int i = 0; i < count; i++)
1403
                        bands[i] = dataset.getDataset(i)[0].getBandCount();
1404
                return bands;
1405
        }
1406

    
1407
        /*
1408
         * (non-Javadoc)
1409
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1410
         */
1411
        public String getColorInterpretation(int band, int dataset) {
1412
                if (this.dataset.getDataset(dataset)[0].getColorInterpretation().get(band) == null)
1413
                        return "Undefined";
1414
                return this.dataset.getDataset(dataset)[0].getColorInterpretation().get(band);
1415
        }
1416

    
1417
        /*
1418
         * (non-Javadoc)
1419
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
1420
         */
1421
        public String getWktProjection() throws RasterDriverException {
1422
                return dataset.getWktProjection();
1423
        }
1424

    
1425
        /**
1426
         * Metodo para consultar si una capa puede ser un RGB. Suponemos que es un RGB
1427
         * si el tipo de datos es de tipo byte y su interpretacion de color tiene
1428
         * asignada los tres colores.
1429
         * @return boolean
1430
         */
1431
        public boolean isRGB() {
1432
                if ((dataset == null) || (render == null))
1433
                        return false;
1434

    
1435
// Quitado pq no necesariamente tiene pq tener 3 bandas para ser RGB
1436
//                if (dataset.getBandCount() < 3)
1437
//                        return false;
1438

    
1439
                if (dataset.getDataType()[0] != IBuffer.TYPE_BYTE)
1440
                        return false;
1441

    
1442
                boolean R = false;
1443
                boolean G = false;
1444
                boolean B = false;
1445

    
1446
                int[] renderBands = render.getRenderBands();
1447
                for (int i = 0; i < renderBands.length; i++) {
1448
                        if (renderBands[i] >= 0) {
1449
                                switch (i) {
1450
                                        case 0:
1451
                                                R = true;
1452
                                                break;
1453
                                        case 1:
1454
                                                G = true;
1455
                                                break;
1456
                                        case 2:
1457
                                                B = true;
1458
                                                break;
1459
                                }
1460
                        }
1461
                }
1462

    
1463
                if (R && G && B)
1464
                        return true;
1465

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

    
1505

    
1506
        /**
1507
         * Devuelve el fichero asociado a la capa o null si no tiene.
1508
         * @return Fichero.
1509
         */
1510
        public File getFile() {
1511
                return (params instanceof File) ? ((File)params) : null;
1512
        }
1513

    
1514
        /**
1515
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1516
         * @param file Fichero a consultar
1517
         * @return true si es aceptado y false si no lo es.
1518
         */
1519
        public static boolean isFileAccepted(File file) {
1520
                return RasterDataset.fileIsSupported(file.getName());
1521
        }
1522

    
1523
        /*
1524
         * (non-Javadoc)
1525
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1526
         */
1527
        public boolean existColorTable() {
1528
                return getRender().existColorTable();
1529
        }
1530
        
1531
        /*
1532
         * (non-Javadoc)
1533
         * @see org.gvsig.raster.hierarchy.IRasterRendering#existsAlphaBand()
1534
         */
1535
        public boolean existsAlphaBand() {
1536
                if(getDataSource().getColorInterpretation() != null)
1537
                        return getDataSource().getColorInterpretation().isAlphaBand();
1538
                else 
1539
                        return false;
1540
        }
1541
        
1542
        /*
1543
         * (non-Javadoc)
1544
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getAlphaBandNumber()
1545
         */
1546
        public int getAlphaBandNumber() {
1547
                if(getDataSource().getColorInterpretation() != null)
1548
                        return getDataSource().getColorInterpretation().getBand(DatasetColorInterpretation.ALPHA_BAND);
1549
                return -1;
1550
        }
1551

    
1552
        /**
1553
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1554
         * capa busque una leyenda valida.
1555
         * @param ct
1556
         */
1557
        public void setLastLegend(ColorTable ct) {
1558
                lastLegend = ColorTableLegend.createLegend(ct);
1559
        }
1560

    
1561
        /**
1562
         * Devuelve la Leyenda de la capa.
1563
         * @return Leyenda.
1564
         */
1565
        public ILegend getLegend() {
1566
                if (lastLegend != null)
1567
                        return lastLegend;
1568

    
1569
                return null;
1570
        }
1571

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

    
1580
        /*
1581
         *  (non-Javadoc)
1582
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1583
         */
1584
        public int getShapeType() throws ReadDriverException {
1585
                return FShape.POLYGON;
1586
        }
1587

    
1588
        /*
1589
         * (non-Javadoc)
1590
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1591
         */
1592
        public void removeLegendListener(LegendListener listener) {
1593
                layerChangeSupport.removeLayerListener(listener);
1594
        }
1595

    
1596
        /**
1597
         * Metodo que obtiene si un punto cae dentro de los l?mites de la capa
1598
         * o fuera de ellos.
1599
         * @param p Punto a calcular
1600
         * @return true si est? dentro de los l?mites y false si est? fuera
1601
         */
1602
        public boolean isInside(Point2D p) {
1603
                 return getDataSource().isInside(p);
1604
        }
1605

    
1606
        /**
1607
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1608
         * @return AffineTransform
1609
         */
1610
        public AffineTransform getAffineTransform() {
1611
                return getDataSource().getAffineTransform();
1612
        }
1613

    
1614
        /**
1615
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista
1616
         * @param transf
1617
         */
1618
        public void setAffineTransform(AffineTransform transf) {
1619
                if(transf == null)
1620
                        return;
1621
                affineTransformList.add(transf);
1622
                getDataSource().setAffineTransform(transf);
1623
        }
1624

    
1625
        /**
1626
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista.
1627
         * Esta versi?n no guarda en el historico.
1628
         * @param transf
1629
         */
1630
        public void setAT(AffineTransform transf) {
1631
                getDataSource().setAffineTransform(transf);
1632
        }
1633

    
1634
        /**
1635
         * Obtiene la lista de transformaciones que se han ido aplicando al raster.
1636
         * @return Historical. Lista de AffineTransform
1637
         */
1638
        public Historical getAffineTransformHistorical() {
1639
                return this.affineTransformList;
1640
        }
1641
        
1642
        /**
1643
         * Salva la georreferenciaci?n a fichero rmf.
1644
         * @param fName
1645
         * @throws RmfSerializerException 
1646
         */
1647
        public void saveGeoToRmf() throws RmfSerializerException {
1648
                if (!isOpen())
1649
                        return;
1650

    
1651
                // Guardamos la GeoReferenciacion de cada dataset
1652
                for (int i = 0; i < getDataSource().getDatasetCount(); i++)
1653
                        getDataSource().saveObjectToRmf(i, RasterDataset.class, getDataSource().getDataset(i)[0]);
1654
                
1655
                affineTransformList.clear();
1656
                affineTransformList.add(this.getAffineTransform());
1657
        }
1658

    
1659
        /*
1660
         * (non-Javadoc)
1661
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1662
         */
1663
        public boolean isActionEnabled(int action) {
1664
                switch (action) {
1665
                        case IRasterLayerActions.BANDS_FILE_LIST:
1666
                                if (existColorTable())
1667
                                        return false;
1668
                                break;
1669
                        case IRasterLayerActions.BANDS_RGB:
1670
                                if (existColorTable())
1671
                                        return false;
1672
                                break;
1673
                        case IRasterLayerActions.REPROJECT:
1674
                                if (!isReproyectable())
1675
                                        return false;
1676
                                break;
1677
                        case IRasterLayerActions.CREATEOVERVIEWS:
1678
                                return overviewsSupport();
1679
                        case IRasterLayerActions.OPACITY:
1680
                        case IRasterLayerActions.TRANSPARENCY:
1681
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1682
                        case IRasterLayerActions.ENHANCED:
1683
                        case IRasterLayerActions.PANSHARPENING:
1684
                                return true;
1685
                }
1686
                return true;
1687
        }
1688

    
1689
        /*
1690
         * (non-Javadoc)
1691
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1692
         */
1693
        public void setVisible(boolean visibility) {
1694
                if(visibility)
1695
                        state.disableStopped();
1696
                else
1697
                        enableStopped();
1698

    
1699
                if(isAwake() || isClosed())
1700
                        try {
1701
                                this.load();
1702
                        } catch (LoadLayerException e) {
1703
                                e.printStackTrace();
1704
                        }
1705
                super.setVisible(visibility);
1706
        }
1707

    
1708
        /**
1709
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1710
         * @return valor de transparencia
1711
         */
1712
        public int getTransparency() {
1713
                try {
1714
                        return getRenderTransparency().getOpacity();
1715
                } catch (NullPointerException e) {
1716
                        return super.getTransparency();
1717
                }
1718
        }
1719

    
1720
        /**
1721
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1722
         * o no.
1723
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1724
         */
1725
        public boolean isTransparent() {
1726
                return getRenderTransparency().isTransparencyActive();
1727
        }
1728

    
1729
        /**
1730
         * Asigna la transparencia de la siguiente renderizaci?n
1731
         * @param valor de transparencia
1732
         */
1733
        public void setTransparency(int trans) {
1734
                super.setTransparency(trans);
1735
                try {
1736
                        getRenderTransparency().setOpacity(trans);
1737
                        getRenderTransparency().activeTransparency();
1738
                } catch (NullPointerException e) {
1739
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1740
                }
1741
        }
1742

    
1743
        /*
1744
         * (non-Javadoc)
1745
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getLastRenderBuffer()
1746
         */
1747
        public IBuffer getLastRenderBuffer() {
1748
                return getRender().getLastRenderBuffer();
1749
        }
1750

    
1751
        /**
1752
         *
1753
         * @return ROIs asociadas a la capa raster.
1754
         */
1755
        public ArrayList getRois() {
1756
                return rois;
1757
        }
1758

    
1759
        /**
1760
         * Establece las ROI asociadas a la capa raster.
1761
         *
1762
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1763
         */
1764
        public void setRois(ArrayList rois) {
1765
                this.rois = rois;
1766
        }
1767

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

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

    
1800
        /**
1801
         * @return the configuration
1802
         */
1803
        static public IConfiguration getConfiguration() {
1804
                return configuration;
1805
        }
1806

    
1807
        /**
1808
         * @param configuration the configuration to set
1809
         */
1810
        static public void setConfiguration(IConfiguration configuration) {
1811
                FLyrRasterSE.configuration = configuration;
1812
        }
1813
        
1814
        /*
1815
         * (non-Javadoc)
1816
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#reload()
1817
         */
1818
        public void reload() throws ReloadLayerException {
1819
                try {
1820
                        super.reload();
1821
                        if (getMapContext() == null)
1822
                                return;
1823
                        if (isStopped())
1824
                                disableStopped();
1825
                        load();
1826
                        getMapContext().invalidate();
1827
                } catch (LoadLayerException e) {
1828
                        setAvailable(false);
1829
                        throw new ReloadLayerException(getName(), e);
1830
                }
1831
        }
1832
        
1833
        /**
1834
         * Devuelve si la capa tiene soporte para poder generar overviews
1835
         * @return
1836
         */
1837
        public boolean overviewsSupport() {
1838
                if ((getDataSource() != null) && (getDataSource().overviewsSupport()))
1839
                        return true;
1840

    
1841
                return false;
1842
        }
1843

    
1844
        /**
1845
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1846
         * en escala de grises
1847
         * @return
1848
         */
1849
        public boolean isRenderingAsGray() {
1850
                int[] renderBands = getRenderBands();
1851
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1852
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1853
                        return true;
1854
                return false;
1855
        }
1856
        
1857
        /*
1858
         * (non-Javadoc)
1859
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
1860
         */
1861
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1862
                updateDrawVersion();
1863
        }
1864
        
1865
        /*****************************************************/
1866
        //Utils
1867

    
1868
        /**
1869
         * Ajusta las coordenadas especificadas en el par?metro al ?rea m?xima
1870
         * del raster en p?xeles.
1871
         * @param req Punto a ajustar dentro del extener del raster
1872
         */
1873
        public Point2D adjustWorldRequest(Point2D req) {
1874
                Rectangle2D ext = null;
1875

    
1876
                ext = getFullExtent();
1877
                req.setLocation(Math.max(ext.getMinX(), req.getX()), Math.max(ext.getMinY(), req.getY()));
1878
                req.setLocation(Math.min(ext.getMaxX(), req.getX()), Math.min(ext.getMaxY(), req.getY()));
1879
                return req;
1880
        }
1881
        
1882
        /*
1883
         * (non-Javadoc)
1884
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#cloneLayer()
1885
         */
1886
        public FLayer cloneLayer() throws Exception {
1887
                FLyrRasterSE newLayer = FLyrRasterSE.createLayer(this.getName(), params, this.getProjection());
1888
                for (int i = 0; i < dataset.getDatasetCount(); i++) {
1889
                        String name = dataset.getDataset(i)[0].getFName();
1890
                        if (!(dataset instanceof CompositeDataset) && !name.equals(this.getName()))
1891
                                newLayer.addFile(name);
1892
                }
1893
                ArrayList filters = getRender().getFilterList().getStatusCloned();
1894
        
1895
                //Hacemos una copia de las bandas a renderizar
1896
                if(getRenderBands() != null) {
1897
                        int[] rb = new int[getRenderBands().length];
1898
                        for (int i = 0; i < rb.length; i++) 
1899
                                rb[i] = getRenderBands()[i];
1900
                        newLayer.setRenderBands(rb);
1901
                }
1902
                
1903
                //Asignamos el entorno
1904
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());        
1905
                newLayer.getRender().getFilterList().setStatus(filters);
1906

    
1907
                // Asignamos los valores noData del original
1908
                newLayer.setNoDataValue(getNoDataValue());
1909
                newLayer.setNoDataType(getNoDataType());
1910
                newLayer.applyNoData();
1911

    
1912
                return newLayer;
1913
        }
1914
        
1915
        /*****************************************************/
1916

    
1917
        public void disableStopped() {state.disableStopped();}
1918

    
1919
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1920

    
1921
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
1922

    
1923
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1924

    
1925
        public void enableStopped() {state.enableStopped();}
1926

    
1927
        public boolean isAwake() {return state.isAwake();}
1928

    
1929
        public boolean isClosed() {return state.isClosed();}
1930

    
1931
        public boolean isOpen() {return state.isOpen();}
1932

    
1933
        public boolean isStopped() {return state.isStopped();}
1934

    
1935
}