Statistics
| Revision:

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

History | View | Annotate | Download (59.9 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
                updateDrawVersion();
1131
                return super.layerListeners.remove(o);
1132
        }
1133

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1506

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

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

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

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

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

    
1570
                return null;
1571
        }
1572

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

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

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

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

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

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

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

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

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

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

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

    
1702
                if(isAwake() || isClosed()) {
1703
                        try {
1704
                                this.load();
1705
                        } catch (LoadLayerException e) {
1706
                                e.printStackTrace();
1707
                        }
1708
                }
1709

    
1710
                /*
1711
                 * Cuando se modifica la visibilidad de una capa raster se hace un updateDrawVersion de todas las
1712
                 * capas raster de ese MapContext. Esto es porque la estrategia utilizada por RasterDrawStrategy hace
1713
                 * que se cacheen en blanco las capas raster que est?n ocultas debajo de otras. Al hacer invisibles las
1714
                 * de arriba la cache que estaba en blanco hace que no se pinte nada. Para evitar esto las marcamos todas
1715
                 * como que han sido modificadas para que se vuelvan a leer.
1716
                 */
1717
                if(getMapContext() != null) {
1718
                        ArrayList listLayers = new ArrayList();
1719
                        listLayers = RasterDrawStrategy.getLayerList(getMapContext().getLayers(), listLayers);
1720
                        for (int i = 0; i < listLayers.size(); i++) {
1721
                                if(listLayers.get(i) instanceof FLyrRasterSE)
1722
                                        ((FLyrRasterSE)listLayers.get(i)).updateDrawVersion();
1723
                        }
1724
                }
1725

    
1726
                super.setVisible(visibility);
1727
        }
1728

    
1729
        /**
1730
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1731
         * @return valor de transparencia
1732
         */
1733
        public int getTransparency() {
1734
                try {
1735
                        return getRenderTransparency().getOpacity();
1736
                } catch (NullPointerException e) {
1737
                        return super.getTransparency();
1738
                }
1739
        }
1740

    
1741
        /**
1742
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1743
         * o no.
1744
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1745
         */
1746
        public boolean isTransparent() {
1747
                return getRenderTransparency().isTransparencyActive();
1748
        }
1749

    
1750
        /**
1751
         * Asigna la transparencia de la siguiente renderizaci?n
1752
         * @param valor de transparencia
1753
         */
1754
        public void setTransparency(int trans) {
1755
                super.setTransparency(trans);
1756
                try {
1757
                        getRenderTransparency().setOpacity(trans);
1758
                        getRenderTransparency().activeTransparency();
1759
                } catch (NullPointerException e) {
1760
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1761
                }
1762
        }
1763

    
1764
        /*
1765
         * (non-Javadoc)
1766
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getLastRenderBuffer()
1767
         */
1768
        public IBuffer getLastRenderBuffer() {
1769
                return getRender().getLastRenderBuffer();
1770
        }
1771

    
1772
        /**
1773
         *
1774
         * @return ROIs asociadas a la capa raster.
1775
         */
1776
        public ArrayList getRois() {
1777
                return rois;
1778
        }
1779

    
1780
        /**
1781
         * Establece las ROI asociadas a la capa raster.
1782
         *
1783
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1784
         */
1785
        public void setRois(ArrayList rois) {
1786
                this.rois = rois;
1787
        }
1788

    
1789
        /**
1790
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1791
         * devolver? null.
1792
         * @return TreeMap con la lista de capas a dibujar
1793
         */
1794
        public HashMap getRasterStrategy() {
1795
                if(strategy != null)
1796
                        return strategy.getStrategy();
1797
                return null;
1798
        }
1799
        
1800
        /**
1801
         * Devuelve el tipo de valor de NoData asociado a la capa.
1802
         * Sirve para diferenciar los estados seleccionados por el usuario. Siendo
1803
         * estos '0: Sin Valor NoData', '1: NoData de Capa'(Por defecto) y '2: Personalizado'
1804
         */
1805
        /**
1806
         * @return the noDataType
1807
         */
1808
        public int getNoDataType() {
1809
                return noDataType;
1810
        }
1811

    
1812
        /**
1813
         * @param noDataType the noDataType to set
1814
         */
1815
        public void setNoDataType(int noDataType) {
1816
                this.noDataType = noDataType;
1817
                if (dataset != null)
1818
                        dataset.setNoDataEnabled(noDataType != RasterLibrary.NODATATYPE_DISABLED);
1819
        }
1820

    
1821
        /**
1822
         * @return the configuration
1823
         */
1824
        static public IConfiguration getConfiguration() {
1825
                return configuration;
1826
        }
1827

    
1828
        /**
1829
         * @param configuration the configuration to set
1830
         */
1831
        static public void setConfiguration(IConfiguration configuration) {
1832
                FLyrRasterSE.configuration = configuration;
1833
        }
1834
        
1835
        /*
1836
         * (non-Javadoc)
1837
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#reload()
1838
         */
1839
        public void reload() throws ReloadLayerException {
1840
                try {
1841
                        super.reload();
1842
                        if (getMapContext() == null)
1843
                                return;
1844
                        if (isStopped())
1845
                                disableStopped();
1846
                        load();
1847
                        getMapContext().invalidate();
1848
                } catch (LoadLayerException e) {
1849
                        setAvailable(false);
1850
                        throw new ReloadLayerException(getName(), e);
1851
                }
1852
        }
1853
        
1854
        /**
1855
         * Devuelve si la capa tiene soporte para poder generar overviews
1856
         * @return
1857
         */
1858
        public boolean overviewsSupport() {
1859
                if ((getDataSource() != null) && (getDataSource().overviewsSupport()))
1860
                        return true;
1861

    
1862
                return false;
1863
        }
1864

    
1865
        /**
1866
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1867
         * en escala de grises
1868
         * @return
1869
         */
1870
        public boolean isRenderingAsGray() {
1871
                int[] renderBands = getRenderBands();
1872
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1873
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1874
                        return true;
1875
                return false;
1876
        }
1877
        
1878
        /*
1879
         * (non-Javadoc)
1880
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
1881
         */
1882
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1883
                updateDrawVersion();
1884
        }
1885
        
1886
        /*****************************************************/
1887
        //Utils
1888

    
1889
        /**
1890
         * Ajusta las coordenadas especificadas en el par?metro al ?rea m?xima
1891
         * del raster en p?xeles.
1892
         * @param req Punto a ajustar dentro del extener del raster
1893
         */
1894
        public Point2D adjustWorldRequest(Point2D req) {
1895
                Rectangle2D ext = null;
1896

    
1897
                ext = getFullExtent();
1898
                req.setLocation(Math.max(ext.getMinX(), req.getX()), Math.max(ext.getMinY(), req.getY()));
1899
                req.setLocation(Math.min(ext.getMaxX(), req.getX()), Math.min(ext.getMaxY(), req.getY()));
1900
                return req;
1901
        }
1902
        
1903
        /*
1904
         * (non-Javadoc)
1905
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#cloneLayer()
1906
         */
1907
        public FLayer cloneLayer() throws Exception {
1908
                FLyrRasterSE newLayer = FLyrRasterSE.createLayer(this.getName(), params, this.getProjection());
1909
                for (int i = 0; i < dataset.getDatasetCount(); i++) {
1910
                        String name = dataset.getDataset(i)[0].getFName();
1911
                        if (!(dataset instanceof CompositeDataset) && !name.equals(this.getName()))
1912
                                newLayer.addFile(name);
1913
                }
1914
                ArrayList filters = getRender().getFilterList().getStatusCloned();
1915
        
1916
                //Hacemos una copia de las bandas a renderizar
1917
                if(getRenderBands() != null) {
1918
                        int[] rb = new int[getRenderBands().length];
1919
                        for (int i = 0; i < rb.length; i++) 
1920
                                rb[i] = getRenderBands()[i];
1921
                        newLayer.setRenderBands(rb);
1922
                }
1923
                
1924
                //Asignamos el entorno
1925
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());        
1926
                newLayer.getRender().getFilterList().setStatus(filters);
1927

    
1928
                // Asignamos los valores noData del original
1929
                newLayer.setNoDataValue(getNoDataValue());
1930
                newLayer.setNoDataType(getNoDataType());
1931
                newLayer.applyNoData();
1932

    
1933
                return newLayer;
1934
        }
1935
        
1936
        /*****************************************************/
1937

    
1938
        public void disableStopped() {state.disableStopped();}
1939

    
1940
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1941

    
1942
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
1943

    
1944
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1945

    
1946
        public void enableStopped() {state.enableStopped();}
1947

    
1948
        public boolean isAwake() {return state.isAwake();}
1949

    
1950
        public boolean isClosed() {return state.isClosed();}
1951

    
1952
        public boolean isOpen() {return state.isOpen();}
1953

    
1954
        public boolean isStopped() {return state.isStopped();}
1955

    
1956
}