Statistics
| Revision:

gvsig-raster / org.gvsig.raster / trunk / org.gvsig.raster / org.gvsig.raster.fmap / src / main / java / org / gvsig / raster / fmap / layers / DefaultFLyrRaster.java @ 1791

History | View | Annotate | Download (68.7 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
* 
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
* 
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
* 
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
19
* MA  02110-1301, USA.
20
* 
21
*/
22
package org.gvsig.raster.fmap.layers;
23

    
24
import java.awt.Dimension;
25
import java.awt.Graphics2D;
26
import java.awt.Point;
27
import java.awt.Rectangle;
28
import java.awt.geom.AffineTransform;
29
import java.awt.geom.NoninvertibleTransformException;
30
import java.awt.geom.Point2D;
31
import java.awt.geom.Rectangle2D;
32
import java.awt.image.BufferedImage;
33
import java.io.File;
34
import java.io.IOException;
35
import java.util.ArrayList;
36
import java.util.HashMap;
37
import java.util.List;
38
import java.util.Set;
39

    
40
import org.cresques.cts.IProjection;
41
import org.gvsig.compat.print.PrintAttributes;
42
import org.gvsig.fmap.crs.CRSFactory;
43
import org.gvsig.fmap.dal.DataStore;
44
import org.gvsig.fmap.dal.DataStoreParameters;
45
import org.gvsig.fmap.dal.coverage.RasterLibrary;
46
import org.gvsig.fmap.dal.coverage.RasterLocator;
47
import org.gvsig.fmap.dal.coverage.RasterManager;
48
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
49
import org.gvsig.fmap.dal.coverage.datastruct.ColorItem;
50
import org.gvsig.fmap.dal.coverage.datastruct.ColorTableLibrary;
51
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
52
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
53
import org.gvsig.fmap.dal.coverage.datastruct.Params;
54
import org.gvsig.fmap.dal.coverage.datastruct.ViewPortData;
55
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
56
import org.gvsig.fmap.dal.coverage.exception.FilePaletteException;
57
import org.gvsig.fmap.dal.coverage.exception.FilterManagerException;
58
import org.gvsig.fmap.dal.coverage.exception.FilterTypeException;
59
import org.gvsig.fmap.dal.coverage.exception.GridException;
60
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
61
import org.gvsig.fmap.dal.coverage.exception.InvalidSourceException;
62
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
63
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
64
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
65
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
66
import org.gvsig.fmap.dal.coverage.grid.Grid;
67
import org.gvsig.fmap.dal.coverage.grid.ROI;
68
import org.gvsig.fmap.dal.coverage.grid.RasterFilter;
69
import org.gvsig.fmap.dal.coverage.grid.RasterFilterList;
70
import org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager;
71
import org.gvsig.fmap.dal.coverage.grid.render.Render;
72
import org.gvsig.fmap.dal.coverage.grid.render.VisualPropertyEvent;
73
import org.gvsig.fmap.dal.coverage.grid.render.VisualPropertyListener;
74
import org.gvsig.fmap.dal.coverage.process.TaskEventManager;
75
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
76
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
77
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
78
import org.gvsig.fmap.dal.coverage.store.parameter.RasterFileStoreParameters;
79
import org.gvsig.fmap.dal.coverage.store.parameter.TileDataParameters;
80
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
81
import org.gvsig.fmap.dal.coverage.store.props.ColorTable;
82
import org.gvsig.fmap.dal.coverage.store.props.Statistics;
83
import org.gvsig.fmap.dal.coverage.util.CRSUtils;
84
import org.gvsig.fmap.dal.coverage.util.ColorConversion;
85
import org.gvsig.fmap.dal.coverage.util.FileUtils;
86
import org.gvsig.fmap.dal.coverage.util.Historical;
87
import org.gvsig.fmap.dal.coverage.util.MathUtils;
88
import org.gvsig.fmap.dal.coverage.util.ProviderServices;
89
import org.gvsig.fmap.dal.coverage.util.RasterUtils;
90
import org.gvsig.fmap.dal.exception.CloseException;
91
import org.gvsig.fmap.dal.exception.DataException;
92
import org.gvsig.fmap.dal.exception.InitializeException;
93
import org.gvsig.fmap.dal.exception.ReadException;
94
import org.gvsig.fmap.dal.raster.spi.CoverageStoreProviderServices;
95
import org.gvsig.fmap.geom.GeometryLocator;
96
import org.gvsig.fmap.geom.GeometryManager;
97
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
98
import org.gvsig.fmap.geom.Geometry.TYPES;
99
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
100
import org.gvsig.fmap.geom.primitive.Envelope;
101
import org.gvsig.fmap.geom.type.GeometryType;
102
import org.gvsig.fmap.geom.type.GeometryTypeNotSupportedException;
103
import org.gvsig.fmap.geom.type.GeometryTypeNotValidException;
104
import org.gvsig.fmap.mapcontext.MapContextLocator;
105
import org.gvsig.fmap.mapcontext.MapContextManager;
106
import org.gvsig.fmap.mapcontext.ViewPort;
107
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
108
import org.gvsig.fmap.mapcontext.exceptions.ReloadLayerException;
109
import org.gvsig.fmap.mapcontext.layers.FLayer;
110
import org.gvsig.fmap.mapcontext.layers.FLyrDefault;
111
import org.gvsig.fmap.mapcontext.layers.LayerChangeSupport;
112
import org.gvsig.fmap.mapcontext.layers.LayerListener;
113
import org.gvsig.fmap.mapcontext.layers.Tiling;
114
import org.gvsig.fmap.mapcontext.layers.operations.Classifiable;
115
import org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint;
116
import org.gvsig.fmap.mapcontext.layers.operations.SingleLayer;
117
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
118
import org.gvsig.fmap.mapcontext.rendering.legend.events.listeners.LegendListener;
119
import org.gvsig.raster.fmap.legend.ColorTableLegend;
120
import org.gvsig.raster.util.RasterNotLoadException;
121
import org.gvsig.tools.ToolsLocator;
122
import org.gvsig.tools.dynobject.DynClass;
123
import org.gvsig.tools.dynobject.DynObjectManager;
124
import org.gvsig.tools.dynobject.DynObjectSet;
125
import org.gvsig.tools.dynobject.DynStruct;
126
import org.gvsig.tools.exception.BaseException;
127
import org.gvsig.tools.persistence.PersistenceManager;
128
import org.gvsig.tools.persistence.PersistentState;
129
import org.gvsig.tools.persistence.exception.PersistenceException;
130
import org.gvsig.tools.task.Cancellable;
131
import org.gvsig.tools.task.SimpleTaskStatus;
132
import org.gvsig.tools.task.TaskStatusManager;
133
import org.gvsig.tools.task.impl.BaseTaskStatus;
134
import org.slf4j.Logger;
135
import org.slf4j.LoggerFactory;
136

    
137
/**
138
 * Raster layer
139
 * 
140
 * @author Nacho Brodin (nachobrodin@gmail.com)
141
 */
142
@SuppressWarnings("deprecation")
143
public class DefaultFLyrRaster extends FLyrDefault implements FLyrRaster, Multiresolution, InfoByPoint, Classifiable,
144
                IRasterLayerActions, ILayerState, VisualPropertyListener, SingleLayer {
145
        public static final String      PERSISTENT_NAME                = "FLyrRasterSE_Persistent";
146
    public static final String      PERSISTENT_DESCRIPTION         = "FLyrRasterSE Persistent";
147
    private RasterManager           rManager                       = RasterLocator.getManager();
148
        private boolean                 mustTileDraw                   = false;
149
        private boolean                 mustTilePrint                  = true;
150
        private int                     maxTileDrawWidth               = 200;
151
        private int                     maxTileDrawHeight              = 200;
152
        private int                     maxTilePrintWidth              = 1500;
153
        private int                     maxTilePrintHeight             = 1500;
154
        private boolean                 firstLoad                      = false;
155
        private boolean                 removeRasterFlag               = true;
156
        protected RasterDataStore       dataStore                      = null;
157
        protected Render                render                         = null;
158
        private int                     posX                           = 0;
159
        private int                     posY                           = 0;
160
        private double                  posXWC                         = 0;
161
        private int                     posYWC                         = 0;
162
        private int                     r                              = 0;
163
        private int                     g                              = 0;
164
        private int                     b                              = 0;
165
        private LayerChangeSupport      layerChangeSupport             = new LayerChangeSupport();
166
        private FLyrState               state                          = new FLyrState();
167
        protected ILegend               lastLegend                     = null;
168
        protected ColorTable            colorTableLoadedFromProject    = null;
169
        protected boolean               loadedFromProject              = false;
170
        private ArrayList<ROI>          rois                           = null;
171
        private RasterDrawStrategy      strategy                       = null;
172
        static private IConfiguration   configuration                  = new DefaultLayerConfiguration();
173
        protected int                   zoomLevel                      =  1;
174
        public boolean                  recalcLevel                    = true;
175
        private String                  uri                            = null;
176
        
177
        private static GeometryManager  geomManager                          = GeometryLocator.getGeometryManager();
178
        private static final Logger     logger                         = LoggerFactory.getLogger(DefaultFLyrRaster.class);
179
        protected FileUtils             fileUtil                       = RasterLocator.getManager().getFileUtils();
180
        protected RasterUtils           rasterUtil                     = RasterLocator.getManager().getRasterUtils();
181
        protected CRSUtils              crsUtil                        = RasterLocator.getManager().getCRSUtils();
182
        protected MathUtils             mathUtil                       = RasterLocator.getManager().getMathUtils();
183

    
184
        
185
        public class RasterTaskStatus extends BaseTaskStatus {
186
                Cancellable c = null;
187
                
188
                public RasterTaskStatus(String tittle, Cancellable c) {
189
                        super(tittle);
190
                        this.c = c;
191
                }
192
                
193
                public boolean isCancellationRequested() {
194
                        if(c != null)
195
                                return this.c.isCanceled();
196
                        return false;
197
                }
198
                
199
                public void cancelRequest() {
200
                        if(c != null)
201
                                this.c.setCanceled(true);
202
                }
203
        }
204

    
205
        /**
206
         * Lista de transformaciones afines que son aplicadas. Esta lista es
207
         * simplemente un historico que no se utiliza. Es posible utilizarlo para
208
         * recuperar transformaciones anteriores.
209
         */
210
        private Historical              affineTransformList    = null;
211
        protected String                readingData            = null;
212
        //It is set to true if the method init has been called at least once
213
        protected boolean               layerInitialize        = false;
214
        
215
        public DefaultFLyrRaster() {
216
                affineTransformList = rManager.createHistoricalService();
217
        }
218
        
219
        public static void registerDynClass() {
220
                DynObjectManager manager = ToolsLocator.getDynObjectManager();
221
            DynClass dynClass = manager.add("RasterInfo", "Raster layer Info by point");
222
            dynClass.setNamespace("InfoByPoint");
223
            dynClass.addDynFieldString("File");
224
            dynClass.addDynFieldString("View Point");
225
            dynClass.addDynFieldString("Pixel Point");
226
            dynClass.addDynFieldString("RGB");
227
            dynClass.addDynFieldString("CMYK");
228
            dynClass.addDynFieldString("HSL");
229
            dynClass.addDynFieldString("Band Value");
230
            dynClass.addDynFieldString("World Point");
231
        }
232
        
233
        /**
234
         * Builds a new raster layer
235
         * @param fileName
236
         * @return
237
         * @throws RasterNotLoadException 
238
         * @throws LoadLayerException 
239
         */
240
        public static DefaultFLyrRaster createLayer(String layerName, File file) throws LoadLayerException {
241
                ProviderServices provServ = RasterLocator.getManager().getProviderServices();
242
                RasterDataParameters storeParameters = provServ.createParameters(file.getName());
243
                storeParameters.setURI(file.getPath());
244
                
245
                MapContextManager mcm = MapContextLocator.getMapContextManager();
246
                DefaultFLyrRaster lyr = (DefaultFLyrRaster) mcm.createLayer(layerName, storeParameters);
247

    
248
                return lyr;
249
        }
250

    
251
        /*
252
         * (non-Javadoc)
253
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setName(java.lang.String)
254
         */
255
        public void setName(String name) {
256
                super.setName(name);
257

    
258
                //Si la capa tiene nombre acivamos el estado awake
259
                if(name != null)
260
                        try {
261
                                if(isClosed())
262
                                        enableAwake();
263
                        } catch (NotAvailableStateException e) {
264
                                logger.error("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
265
                        }
266
        }
267

    
268
        /*
269
         * (non-Javadoc)
270
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#wakeUp()
271
         */
272
        public void wakeUp(){
273
                try {
274
                        reload();
275
                } catch (ReloadLayerException e) {
276
                        // No se ha podido recuperar la capa con exito
277
                }
278
        }
279

    
280
        /*
281
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
282
         */
283
        public void load() throws LoadLayerException {
284
                if (isStopped() || getDataStore() == null)
285
                        return;
286

    
287
                enableStopped(); // Paramos la capa mientras se hace un load
288

    
289
                int test = -1;
290
                DataStoreParameters params = getDataStore().getParameters();
291
                DataStoreParameters p = params;
292
                if (params != null) {
293
                        if(params instanceof TileDataParameters) {
294
                                uri = ((RasterDataParameters)params).getURI();
295
                                if(uri == null)
296
                                        p = (DataStoreParameters)((TileDataParameters)params).getDataParameters();
297
                        }
298
                        if(uri == null) {
299
                                if(params instanceof RasterDataParameters)
300
                                        uri = ((RasterDataParameters)p).getURI();
301
                        }
302
                        test = uri.indexOf("ecwp:");
303
                }
304

    
305
                if (test != -1) {
306
                        String urlECW = uri.substring(test + 6);
307
                        uri = "ecwp://" + urlECW;
308
                        System.err.println(test + " " + uri);
309
                }
310

    
311
                try {
312
                        if(!getDataStore().isOpen())
313
                                dataStore = rManager.open(params);
314
                } catch (NotSupportedExtensionException e) {
315
                        throw new LoadLayerException(this.getName());
316
                } catch (RasterDriverException e) {
317
                        throw new LoadLayerException(this.getName());
318
                }
319
        }
320

    
321
        /**
322
         * Acciones de inicializaci?n despu?s de que la fuente de datos
323
         * de la capa est? asignada. El tipo de fuente de datos es variable
324
         * puede ser MultiRasterDataset, CompositeDataset u otras que existan e
325
         * implementen IRasterDatasource.
326
         * @throws FilePaletteException 
327
         */
328
        public void init() throws LoadLayerException, FilePaletteException {
329
                layerInitialize = true;
330
                
331
                if (getDataStore() == null)
332
                        throw new LoadLayerException("Formato no valido", new IOException());
333

    
334
                render = getDataStore().getRender();
335
                render.addVisualPropertyListener(this);
336
                initFilters();
337

    
338
                //Inicializaci?n del historico de transformaciones
339
                affineTransformList.clear();
340
                affineTransformList.add(this.getAffineTransform());
341

    
342
                try {
343
                        if(!isOpen())
344
                                enableOpen();
345
                } catch (NotAvailableStateException e) {
346
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Awake=" + isAwake(), e);
347
                }
348
        }
349

    
350
        /*
351
         * (non-Javadoc)
352
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#readProjection()
353
         */
354
        public IProjection readProjection() throws RasterDriverException {
355
                try {
356
                        crsUtil.setCRSFactory(CRSFactory.cp);
357
                        if( getDataStore() == null )
358
                                return null;
359
                        return crsUtil.convertWktToIProjection(getDataStore().getWktProjection());
360
                } catch (Exception e) {
361
                        throw new RasterDriverException("Problems converting from WKT to IProjection", e);
362
                } catch (Error e) {
363
                        e.printStackTrace();
364
                        return null;
365
                }
366
        }
367

    
368
        /**
369
         * Crea el objeto renderizador de raster
370
         * @return Rendering
371
         */
372
        public Render getRender() {
373
                if (render == null) {
374
                        if(getDataStore() != null) {
375
                                render = getDataStore().getRender();
376
                                render.addVisualPropertyListener(this);
377
                        }
378
                }
379
                return render;
380
        }
381
        
382
        /*
383
         * (non-Javadoc)
384
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getURI()
385
         */
386
        public String getURI() {
387
                return uri;
388
        }
389

    
390
        /*
391
         * (non-Javadoc)
392
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setNoDataTransparent(boolean)
393
         */
394
        public void setNoDataTransparent(boolean t) {
395
                getNoDataValue().setNoDataTransparent(t);
396
                if(getRender().getLastTransparency() != null) {
397
                        getRender().getLastTransparency().setNoData(getDataStore().getNoDataValue());
398
                        getRender().getLastTransparency().activeTransparency();
399
                }
400
        }
401

    
402
        /**
403
         * Initializes the filter list to render this raster layer
404
         * @throws FilePaletteException 
405
         */
406
        protected void initFilters() throws FilePaletteException {
407
                if(getDataType() == null)
408
                        return;
409
                        
410
                RasterFilterList filterList = rManager.createEmptyFilterList(getDataType()[0]);
411
                if(loadedFromProject) {
412
                        filterList = getDataStore().getRender().getFilterList();
413
                }
414
                filterList.addEnvParam("IStatistics", getDataStore().getStatistics());
415
                filterList.addEnvParam("MultiRasterDataset", getDataStore());
416

    
417
                if(getDataStore() == null)
418
                        return;
419
                
420
                if(getDataStore().getNoDataValue() != null) {
421
                        getDataStore().getNoDataValue().load();
422
                        if(getDataStore().getNoDataValue().isDefined())
423
                                setNoDataTransparent(true);
424
                }
425

    
426
                filterList.setInitDataType(getDataType()[0]);
427

    
428
                // Quitamos la leyenda
429
                lastLegend = null;
430

    
431
                try {
432
                        //Si en la carga del proyecto se carg? una tabla de color asignamos esta
433
                        if(colorTableLoadedFromProject != null) {
434
                                setLastLegend(colorTableLoadedFromProject);
435
                                RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
436
                                Params params = filterList.createEmptyFilterParams();
437
                                params.setParam("colorTable", colorTableLoadedFromProject);
438
                                colorTableManager.addFilter(params);
439
                        } else
440
                                //sino ponemos la tabla asociada al raster
441
                                if (getDataStore().getColorTable() != null) {
442
                                        ColorTable table = getDataStore().getColorTable();
443
                                        setLastLegend(table);
444
                                        RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
445
                                        Params params = filterList.createEmptyFilterParams();
446
                                        params.setParam("colorTable", table);
447
                                        colorTableManager.addFilter(params);
448
                                } else //sino hace lo que dice en las preferencias
449
                                        if(getDataStore().needEnhanced() || 
450
                                                        (loadedFromProject && filterList.get("enhanced_stretch") != null)) 
451
                                                loadEnhancedOrColorTable(filterList);
452
                        colorTableLoadedFromProject = null;
453

    
454
                        getRender().setFilterList(filterList);
455
                        // Inicializo la transparencia para el render
456
                        if(!loadedFromProject) {
457
                                getRender().setLastTransparency(getDataStore().getTransparency().cloneTransparency());
458
                        }
459
                        loadedFromProject = false;
460
                } catch (FilterTypeException e) {
461
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
462
                        logger.error("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
463
                } catch (FilterManagerException e) {
464
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
465
                        logger.error("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
466
                }
467
        }
468

    
469
        /**
470
         * Mira la configuracion para saber si debe cargar un realce o una tabla
471
         * de color por defecto
472
         * @param filterManager
473
         * @throws FilterTypeException
474
         * @throws FilePaletteException 
475
         */
476
        private void loadEnhancedOrColorTable(RasterFilterList filterList) throws FilterTypeException, FilterManagerException, FilePaletteException {
477
                String colorTableName = null;
478
                if(configuration != null)
479
                        colorTableName = configuration.getValueString("loadlayer_usecolortable", (String) null);
480

    
481
                String palettesPath = System.getProperty("user.home") +
482
                File.separator +
483
                "gvSIG" + // PluginServices.getArguments()[0] +
484
                File.separator + "colortable";
485

    
486
                Statistics stats = getDataStore().getStatistics();
487
                ColorTableLibrary colorTableLibrary = rManager.getDataStructFactory().getColorTableLibrary();
488

    
489
                if (colorTableName != null)
490
                        try {
491
                                stats.calculate(RasterLibrary.statisticsScale);
492
                                if (getDataStore().getBandCount() == 1) {
493
                                        ArrayList<String> fileList = colorTableLibrary.getPaletteFileList(palettesPath);
494
                                        for (int i = 0; i < fileList.size(); i++) {
495
                                                ArrayList<ColorItem> paletteItems = new ArrayList<ColorItem>();
496
                                                String paletteName = colorTableLibrary.loadPalette(palettesPath, (String) fileList.get(i), paletteItems);
497
                                                if (paletteName.equals(colorTableName)) {
498
                                                        if (paletteItems.size() <= 0)
499
                                                                continue;
500

    
501
                                                        ColorTable colorTable = colorTableLibrary.createColorTable();
502
                                                        colorTable.setName(paletteName);
503
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
504
                                                        colorTable.setInterpolated(true);
505

    
506
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
507

    
508
                                                        setLastLegend(colorTable);
509

    
510
                                                        RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
511
                                                        Params params = filterList.createEmptyFilterParams();
512
                                                        params.setParam("colorTable", colorTable);
513
                                                        colorTableManager.addFilter(params);
514
                                                        return;
515
                                                }
516
                                        }
517
                                }
518
                        } catch (FileNotOpenException e) {
519
                                // No podemos aplicar el filtro
520
                        } catch (RasterDriverException e) {
521
                                // No podemos aplicar el filtro
522
                        } catch (ProcessInterruptedException e) {
523
                                // El usuario ha cancelado el proceso
524
                        }
525

    
526
                        RasterFilterListManager enhancementManager = filterList.getManagerByID("EnhancementStretch");
527
                        RasterFilter f = filterList.getByName("enhanced_stretch");
528
                        if(f == null) {
529
                                Params params = filterList.createEmptyFilterParams();
530
                                params.setParam("stats", stats);
531
                                params.setParam("remove", new Boolean(false));
532
                                params.setParam("renderBands", getRender().getRenderBands());
533
                                params.setParam("stretchs", null);//coge el LinearStretchParams por defecto
534
                                params.setParam("rgb", new Boolean(true));
535
                                enhancementManager.addFilter(params);
536
                        }
537
        }
538

    
539
        /*
540
         * (non-Javadoc)
541
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isReproyectable()
542
         */
543
        public boolean isReproyectable() {
544
                if (getDataStore() == null)
545
                        return false;
546
                return getDataStore().isReproyectable();
547
        }
548

    
549
        /**
550
         * @throws ReadException
551
         * @throws ReadDriverException
552
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
553
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
554
         *                 com.iver.utiles.swing.threads.Cancellable)
555
         */
556
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadException {
557
                TaskEventManager task = rManager.getRasterTask();
558
                task.setEvent(null);
559
                
560
                if(!layerInitialize) {
561
                        if (getDataStore() != null)
562
                                try {
563
                                        this.init();
564
                                } catch (FilePaletteException e) {
565
                                        throw new ReadException("Error in raster legend", e);
566
                                } catch (LoadLayerException e) {
567
                                        throw new ReadException("Error initializing the layer", e);
568
                                }
569
                }
570

    
571
                try {
572
                        if (!isOpen())
573
                                return;
574

    
575
                        enableStopped();
576
                        // callLegendChanged(null);
577
                        
578
                        //Solo el zoom normal recalcula el nivel dependiendo de la escala. El zoom por niveles asigna
579
                        //?l el nivel de zoom por lo que no habr? que recalcularlo.
580
                        if(recalcLevel) {
581
                                double pixelSize = vp.getEnvelope().getLength(0) / (double)vp.getImageWidth();
582
                                zoomLevel = getDataStore().getNearestLevel(pixelSize);
583
                        }
584
                        recalcLevel = true;
585

    
586
                        strategy = new RasterDrawStrategy(getMapContext(), this);
587
                        strategy.stackStrategy();
588
                        HashMap<DefaultFLyrRaster, Boolean> tStr = strategy.getStrategy();
589
                        if (tStr != null &&
590
                                tStr.get(this) != null &&
591
                                ((Boolean) (tStr.get(this))).booleanValue() == false) {
592
                                disableStopped();
593
                                return;
594
                        }
595

    
596
                        if (isWithinScale(scale)) {
597
                                
598
                                if (mustTileDraw) {
599
                                        Point2D p = vp.getOffset();
600
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
601
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
602
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
603
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
604
                                                // drawing part
605
                                                try {
606
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
607
                                                        draw(image, g, vport, cancel);
608
                                                } catch (InterruptedException e) {
609
                                                        System.out.println("Se ha cancelado el pintado");
610
                                                } catch (InvalidSetViewException e) {
611
                                                        throw new ReadException("Error reading file.", e);
612
                                                } catch (RasterDriverException e) {
613
                                                        throw new ReadException("Error reading file.", e);
614
                                                }  catch (NoninvertibleTransformException e) {
615
                                                        throw new ReadException("Error in the transformation.", e);
616
                                                }
617
                                } else
618
                                        try {
619
                                                draw(image, g, vp, cancel);
620
                                        } catch (InterruptedException e) {
621
                                                System.out.println("Se ha cancelado el pintado");
622
                                        } catch (InvalidSetViewException e) {
623
                                                throw new ReadException("Error reading file.", e);
624
                                        } catch (RasterDriverException e) {
625
                                                throw new ReadException("Error reading file.", e);
626
                                        }
627

    
628
                        }
629
                        
630
                        //callLegendChanged(null);
631
                } finally {
632
                        disableStopped();
633
                        task.setEvent(null);
634
                }
635
        }
636

    
637
        protected void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws RasterDriverException, InvalidSetViewException, InterruptedException {
638
                Envelope adjustedExtent = vp.getAdjustedExtent();
639
                if (adjustedExtent == null)
640
                        return;
641
                Extent e = rManager.getDataStructFactory().createExtent(adjustedExtent.getLowerCorner().getX(),
642
                                adjustedExtent.getUpperCorner().getY(), adjustedExtent
643
                                                .getUpperCorner().getX(),
644
                                adjustedExtent
645
                                                .getLowerCorner().getY());
646
                Dimension imgSz = vp.getImageSize();
647
                ViewPortData vp2 = rManager.createViewPortData(vp.getProjection(), e, imgSz );
648
                vp2.setMat(vp.getAffineTransform());
649
                //vp2.setTime(vp.getTime()); 
650
                
651
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
652
                SimpleTaskStatus taskStatus = new RasterTaskStatus("Drawing " + getName() + "...", cancel);
653
                manager.add(taskStatus);
654
                taskStatus.setAutoremove(true);
655
                
656
                //Crea la reproyecci?n al vuelo la primera vez
657
                RasterDataParameters params = (RasterDataParameters)getDataStore().getParameters();
658
                if(!getRender().isReprojectingOnTheFly() && 
659
                        getDataStore().getProjection() != null &&
660
                        params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
661
                        getRender().createReprojectionOnTheFly(getDataStore(), getCoordTrans(), taskStatus);
662
                }
663
                
664
                try {
665
                        if(getDataStore().isTiled()) {
666
                                getRender().drawTiledService(g, vp2, vp.getImageSize(), taskStatus);
667
                        } else {
668
                                getRender().draw(g, vp2, taskStatus);
669
                        }
670
                } catch (ProcessInterruptedException e1) {
671
                } finally {
672
                        taskStatus.terminate();
673
                }
674
        }
675

    
676
        /**
677
         * Inserta la proyecci?n.
678
         *
679
         * @param proj Proyecci?n.
680
         */
681
        public void setProjection(IProjection proj) {
682
                try {
683
                        getDataStore().setProjection(proj);
684
                        super.setProjection(proj);
685
                } catch (RmfSerializerException e) {
686
                        logger.error("Error saving the projection", e);
687
                }
688
                
689
        }
690

    
691
        /*
692
         * (non-Javadoc)
693
         * @see org.gvsig.fmap.mapcontext.layers.FLayer#getFullEnvelope()
694
         */
695
        public Envelope getFullEnvelope() {
696
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
697
                //un extent aunque la capa no est? abierta
698
                if(/*!isOpen() || */getDataStore() == null || getDataStore().getExtent() == null)
699
                        return null;
700

    
701
                Rectangle2D e = getDataStore().getExtent().toRectangle2D();
702
                try {
703
                        return geomManager.createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
704
                                        .getMaxY(), SUBTYPES.GEOM2D);
705

    
706
                        /*
707
                        No es necesario 
708
                        ICoordTrans ct = getCoordTrans();
709
                        RasterDataParameters params = (RasterDataParameters)getDataStore().getParameters();
710
                        if (ct != null && params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
711
                                env = env.convert(ct);
712
                        }
713
                        return env;*/
714

    
715
                } catch (CreateEnvelopeException e1) {
716
                        logger.error("Error creating the envelope", e);
717
                        return null;
718
                }
719
        }
720
        
721
        /**
722
         * Obtiene el valor del pixel del Image en la posici?n x,y
723
         * @param x Posici?n x
724
         * @param y Posici?n y
725
         * @return valor de pixel
726
         */
727
//        public int[] getPixel(int pxx, int pxy) {
728
//                int[] argb = { -1, -1, -1, -1 };
729
//                if (!isOpen() || (image == null))
730
//                        return argb;
731
//                if (pxx >= 0 && pxx < image.getWidth() && pxy >= 0 && pxy < image.getHeight()) {
732
//                        int value = image.getRGB(pxx, pxy);
733
//                        argb[0] = ((value & 0xff000000) >> 24);
734
//                        argb[1] = ((value & 0x00ff0000) >> 16);
735
//                        argb[2] = ((value & 0x0000ff00) >> 8);
736
//                        argb[3] = (value & 0x000000ff);
737
//                }
738
//                return argb;
739
//        }
740

    
741
        /*
742
         * (non-Javadoc)
743
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
744
         */
745
        public double getMaxX() {
746
                if(getFullEnvelope() != null)
747
                        return getFullEnvelope().getMaximum(0);
748
                return -1;
749
        }
750

    
751
        /*
752
         * (non-Javadoc)
753
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
754
         */
755
        public double getMaxY() {
756
                if(getFullEnvelope() != null)
757
                        return this.getFullEnvelope().getMaximum(1);
758
                return -1;
759
        }
760

    
761
        /*
762
         * (non-Javadoc)
763
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinX()
764
         */
765
        public double getMinX() {
766
                if(getFullEnvelope() != null)
767
                        return getFullEnvelope().getMinimum(0);
768
                return -1;
769
        }
770

    
771
        /*
772
         * (non-Javadoc)
773
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinY()
774
         */
775
        public double getMinY() {
776
                if(getFullEnvelope() != null)
777
                        return getFullEnvelope().getMinimum(1);
778
                return -1;
779
        }
780

    
781
        /* (non-Javadoc)
782
         * @deprecated. See String getInfo(Point p) throws DriverException
783
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
784
         */
785
        public String queryByPoint(Point p) {
786
                if (!isOpen())
787
                        return null;
788
                ColorConversion conv = rManager.getColorConversion();
789

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

    
792
                ArrayList<Object> attr = getAttributes();
793
                data += "  <raster\n";
794
                data += "    File=\"" + getFile() + "\"\n";
795
                for (int i = 0; i < attr.size(); i++) {
796
                        Object[] a = (Object[]) attr.get(i);
797

    
798
                        data += "    " + a[0].toString() + "=";
799
                        if (a[1].toString() instanceof String)
800
                                data += "\"" + a[1].toString() + "\"\n";
801
                        else
802
                                data += a[1].toString() + "\n";
803
                }
804
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
805
                data += "    Point_WC=\"" + mathUtil.format(posXWC, 3) + " , " + mathUtil.format(posYWC, 3) + "\"\n";
806
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
807
                double[] cmyk = conv.RGBtoCMYK(r & 0xff, g & 0xff, b & 0xff, 1D);
808
                data += "    CMYK=\"" + mathUtil.format(cmyk[0], 4) + ", " + mathUtil.format(cmyk[1], 4) + ", " + mathUtil.format(cmyk[2], 4) + "," + mathUtil.format(cmyk[3], 4) + "\"\n";
809
                double[] hsl = conv.RGBtoHSL(r & 0xff, g & 0xff, b & 0xff);
810
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
811
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
812
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
813
                data += "    HSL=\"" + mathUtil.format(hsl[0], 4) + ", " + mathUtil.format(hsl[1], 4) + ", " + mathUtil.format(hsl[2], 4) + "\"\n";
814
                data += "  />\n";
815

    
816
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
817
                return data;
818
        }
819

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

    
830
        /*
831
         * (non-Javadoc)
832
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAttributes()
833
         */
834
        public ArrayList<Object> getAttributes() {
835
                ArrayList<Object> attr = new ArrayList<Object>();
836
                if(!isOpen())
837
                        return attr;
838
                Object [][] a = {
839
                        {"Filename", getDataStore().getName()},
840
                        {"Filesize", new Long(getDataStore().getFileSize())},
841
                        {"Width", new Integer((int)getDataStore().getWidth())},
842
                        {"Height", new Integer((int)getDataStore().getHeight())},
843
                        {"Bands", new Integer(getDataStore().getBandCount())}
844
                };
845
                for (int i = 0; i < a.length; i++)
846
                        attr.add(a[i]);
847
                return attr;
848
        }
849

    
850

    
851
        /* (non-Javadoc)
852
         * @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)
853
         */
854
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
855
                        double scale, PrintAttributes propeties) throws ReadException {
856

    
857
                if (/*!isOpen() ||*/ !isVisible() || !isWithinScale(scale))
858
                        return;
859
                
860
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
861
                SimpleTaskStatus taskStatus = new RasterTaskStatus("Printing raster " + getName() + "...", cancel);
862
                manager.add(taskStatus);
863
                taskStatus.setAutoremove(true);
864

    
865
                if (!mustTilePrint)
866
                        draw(null, g, viewPort, cancel,scale);
867
                else {
868
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
869
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
870
                        taskStatus.setRangeOfValues(0, tiles.getNumTiles());
871
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
872
                                // Parte que dibuja
873
                                try {
874
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
875
                                        draw(null, g, vp, cancel, scale);
876
                                        taskStatus.setCurValue(tileNr);
877
                                } catch (NoninvertibleTransformException e) {
878
                                        throw new ReadException("Error en la transformaci?n.", e);
879
                                } finally {
880
                                        taskStatus.terminate();
881
                                }
882
                        }
883
                }
884
                
885
                taskStatus.terminate();
886
        }
887

    
888
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
889
                        double scale) throws ReadException {
890
                if(!isOpen())
891
                        return;
892

    
893
                // Para no pedir imagenes demasiado grandes, vamos
894
                // a hacer lo mismo que hace EcwFile: chunkear.
895
                // Llamamos a drawView con cuadraditos m?s peque?os
896
                // del BufferedImage ni caso, cuando se imprime viene con null
897

    
898
                int numW, numH;
899
                int stepX, stepY;
900
                int xProv, yProv;
901
                int A = 1500;
902
                int H = 1500;
903
                int altoAux, anchoAux;
904

    
905
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
906

    
907
                // Vamos a hacerlo en trozos de AxH
908
                Rectangle r = g.getClipBounds();
909
                numW = (r.width) / A;
910
                numH = (r.height) / H;
911

    
912
                double[] srcPts = new double[8];
913
                double[] dstPts = new double[8];
914

    
915
                yProv = r.y;
916
                for (stepY = 0; stepY < numH + 1; stepY++) {
917
                        if ((yProv + H) > r.getMaxY())
918
                                altoAux = (int) r.getMaxY() - yProv;
919
                        else
920
                                altoAux = H;
921

    
922
                        xProv = r.x;
923
                        for (stepX = 0; stepX < numW + 1; stepX++) {
924
                                if ((xProv + A) > r.getMaxX())
925
                                        anchoAux = (int) r.getMaxX() - xProv;
926
                                else
927
                                        anchoAux = A;
928

    
929
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
930

    
931
                                // Parte que dibuja
932
                                srcPts[0] = xProv;
933
                                srcPts[1] = yProv;
934
                                srcPts[2] = xProv + anchoAux + 1;
935
                                srcPts[3] = yProv;
936
                                srcPts[4] = xProv + anchoAux + 1;
937
                                srcPts[5] = yProv + altoAux + 1;
938
                                srcPts[6] = xProv;
939
                                srcPts[7] = yProv + altoAux + 1;
940

    
941
                                try {
942
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
943
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
944
                                        // Extent extent = new Extent(rectCuadricula);
945

    
946
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
947
                                        ViewPort vp = (ViewPort)viewPort.clone();
948
                                        vp.setImageSize(tam);
949
                                        Envelope env = geomManager.createEnvelope(rectCuadricula
950
                                                        .getMinX(), rectCuadricula.getMinY(),
951
                                                        rectCuadricula.getMaxX(), rectCuadricula.getMaxY(),
952
                                                        SUBTYPES.GEOM2D);
953
                                        vp.setEnvelope(env);
954
                                        vp.setAffineTransform(mat);
955
                                        draw(null, g, vp, cancel, scale);
956

    
957
                                } catch (NoninvertibleTransformException e) {
958
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
959
                                } catch (ReadException e) {
960
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
961
                                } catch (CreateEnvelopeException e) {
962
                                        logger.error("Error creating the envelope", e);
963
                                } catch (CloneNotSupportedException e) {
964
                                        logger.error("Error cloning the viewport", e);
965
                                }
966
                                // Fin parte que dibuja
967
                                xProv = xProv + A;
968
                        }
969
                        yProv = yProv + H;
970
                }
971
        }
972

    
973
        /**
974
         * Borra de la lista de listeners el que se pasa como par?metro.
975
         *
976
         * @param o LayerListener a borrar.
977
         *
978
         * @return True si ha sido correcto el borrado del Listener.
979
         */
980
        public boolean removeLayerListener(LayerListener o) {
981
                if (this.isRemoveRasterFlag()) {
982
                        try {
983
                                enableClosed();
984
                        } catch (NotAvailableStateException e1) {
985
                                // No se ha podido cambiar el estado de la capa a cerrado
986
                        }
987
                }
988

    
989
                // Salva a RMF
990
                if (getDataStore() != null)
991
                        // Guardamos la GeoReferenciacion de cada dataset
992
                        try {
993
                                getDataStore().saveGeoreferencingToRmf();
994
                        } catch (Exception e) {
995
                                logger.info("error_salvando_rmf", e);
996
                        }
997

    
998
                        if (this.isRemoveRasterFlag()) {
999
                                if (getDataStore() != null) {
1000
                                        String[] files = getFileName().clone();
1001

    
1002
                                        try {
1003
                                                getDataStore().close();
1004
                                        } catch (CloseException e) {
1005
                                        }
1006

    
1007
                                        dataStore = null;
1008
                                        if(render != null)
1009
                                                render.dispose();
1010
                                        render = null;
1011
                                        // System.gc();
1012
                                        this.setRemoveRasterFlag(true);
1013

    
1014
                                        for (int i = 0; i < files.length; i++) {
1015
                                                File file = new File(files[i]);
1016
                                                File dirTemp = fileUtil.getTemporalFile();
1017
                                                if(!file.exists())
1018
                                                        continue;
1019
                                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
1020
                                                        file.delete();
1021

    
1022
                                                        // Borramos todos los ficheros que puedan tener relacion con el fichero actual
1023
                                                        String basefile = file.getName();
1024
                                                        File basepath = file.getParentFile();
1025
                                                        int last = basefile.lastIndexOf(".");
1026
                                                        if (last != -1)
1027
                                                                basefile = basefile.substring(0, last + 1);
1028
                                                        File[] list = basepath.listFiles();
1029
                                                        for (int j = 0; j < list.length; j++)
1030
                                                                if (list[j].getName().startsWith(basefile))
1031
                                                                        list[j].delete();
1032
                                                }
1033
                                        }
1034
                                }
1035
                        }
1036
                        updateDrawVersion();
1037
                        return super.layerListeners.remove(o);
1038
        }
1039

    
1040
        /*
1041
         * (non-Javadoc)
1042
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRemoveRasterFlag()
1043
         */
1044
        public boolean isRemoveRasterFlag() {
1045
                return removeRasterFlag;
1046
        }
1047

    
1048
        /*
1049
         * (non-Javadoc)
1050
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setRemoveRasterFlag(boolean)
1051
         */
1052
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1053
                this.removeRasterFlag = removeRasterFlag;
1054
        }
1055

    
1056
        /*
1057
         * (non-Javadoc)
1058
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1059
         */
1060
        public String getTocImageIcon() {
1061
                return "map-ok-ico";
1062
        }
1063

    
1064
        /*
1065
         * (non-Javadoc)
1066
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getTileSize()
1067
         */
1068
        public int[] getTileSize() {
1069
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1070
                return size;
1071
        }
1072

    
1073
        /*
1074
         * (non-Javadoc)
1075
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isTiled()
1076
         */
1077
        public boolean isTiled() {
1078
                return mustTileDraw;
1079
        }
1080

    
1081
        /*
1082
         * (non-Javadoc)
1083
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isGeoreferenced()
1084
         */
1085
        public boolean isGeoreferenced() {
1086
                return getDataStore().isGeoreferenced();
1087
        }
1088

    
1089
        /*
1090
         * (non-Javadoc)
1091
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getNoDataValue()
1092
         */
1093
        public NoData getNoDataValue() {
1094
                return getDataStore().getNoDataValue();
1095
        }
1096

    
1097
        /**
1098
         * Sets the nodata value for this layer
1099
         * @param nd
1100
         */
1101
        public void setNoDataValue(NoData nd) {
1102
                if (getDataStore() != null)
1103
                        getDataStore().setNoDataValue(nd);
1104
        }
1105

    
1106
        /*
1107
         * (non-Javadoc)
1108
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getPxHeight()
1109
         */
1110
        public double getPxHeight() {
1111
                return getDataStore().getHeight();
1112
        }
1113

    
1114
        /*
1115
         * (non-Javadoc)
1116
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getPxWidth()
1117
         */
1118
        public double getPxWidth() {
1119
                return getDataStore().getWidth();
1120
        }
1121

    
1122
        /**
1123
         * Gets the height in world coordinates of this raster layer
1124
         */
1125
        public double getWCHeight() {
1126
                return getFullEnvelope().getMaximum(1);
1127
        }
1128

    
1129
        /**
1130
         * Gets the width in world coordinates of this raster layer
1131
         */
1132
        public double getWCWidth() {
1133
                return getFullEnvelope().getMaximum(0);
1134
        }
1135

    
1136
        /**
1137
         * Gets the size of all files of this raster layer
1138
         */
1139
        public long[] getFileSize() {
1140
                if (getDataStore() == null)
1141
                        return null;
1142

    
1143
                return getDataStore().getFileSizeByProvider();
1144
        }
1145

    
1146
        /**
1147
         * Gets the list of file names
1148
         */
1149
        public String[] getFileName() {
1150
                if (getDataStore() == null)
1151
                        return null;
1152

    
1153
                return getDataStore().getURIByProvider();
1154
        }
1155

    
1156
        /**
1157
         * Returns the number of files in this raster layer
1158
         */
1159
        public int getFileCount() {
1160
                return getDataStore().getProviderCount();
1161
        }
1162

    
1163
        /*
1164
         * (non-Javadoc)
1165
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileFormat()
1166
         */
1167
        public String getFileFormat() {
1168
                if(getDataStore().getSourceType() == RasterDataStore.FILE) {
1169
                        String fName = getDataStore().getName();
1170
                        int index = fName.lastIndexOf(".") + 1;
1171
                        String ext = null;
1172
                        if (index > 0)
1173
                                ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1174
                        return ext;
1175
                }
1176
                if(getDataStore().getSourceType() == RasterDataStore.POSTGIS) {
1177
                        return "POSTGIS";
1178
                }
1179
                return null;
1180
        }
1181

    
1182
        /*
1183
         * (non-Javadoc)
1184
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1185
         */
1186
        public int[] getDataType() {
1187
                return getDataStore().getDataType();
1188
        }
1189

    
1190
        /**
1191
         * Sets the filter list
1192
         */
1193
        public void setRenderFilterList(RasterFilterList filterList) {
1194
                getRender().setFilterList(filterList);
1195
        }
1196
        
1197
        /*
1198
         * (non-Javadoc)
1199
         * @see org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint#getInfo(java.awt.Point, double, org.gvsig.tools.task.Cancellable, boolean)
1200
         */
1201
        public DynObjectSet getInfo(org.gvsig.fmap.geom.primitive.Point p, double tolerance) throws LoadLayerException, DataException {
1202
                DynObjectSetRasterInfo info = new DynObjectSetRasterInfo();
1203
                
1204
                if (!isOpen()) {
1205
                        info.addField("Layer not open", normalizeAsXMLTag(getName()), 0);
1206
                        return info;
1207
                }
1208
                
1209
                Point2D pReal = new Point2D.Double(p.getX(), p.getY());
1210
                Point2D px = new Point2D.Double();
1211
                if(        pReal.getX() > this.getMinX() &&
1212
                        pReal.getX() < this.getMaxX() &&
1213
                        pReal.getY() > this.getMinY() &&
1214
                        pReal.getY() < this.getMaxY()) {
1215
                        px = transformPoint(pReal);
1216
                }
1217
                //int[] rgb = getPixel((int) p.getX(), (int) p.getY());
1218
                //ColorConversion conv = rManager.getColorConversion();
1219
                
1220
                info.addField("File", normalizeAsXMLTag(getName()), 0);
1221
                info.addField("View Point", "[" + p.getX() + " , " + p.getY() + "]", 1);
1222
                info.addField("World Point", "[" + mathUtil.format(pReal.getX(), 3) + " , " + mathUtil.format(pReal.getY(), 3) + "]", 2);
1223
                if (px == null)
1224
                        info.addField("Pixel Point", "Out", 3);
1225
                else
1226
                        info.addField("Pixel Point", "[" + (int) px.getX() + ",  " + (int) px.getY() + "]", 3);
1227
        
1228
                //La informaci?n RGB no puede obtener de la capa
1229
                
1230
                /*info.addField("RGB", "[" + rgb[1] + ",  " + rgb[2] + ",  " + rgb[3] + "]", 4);
1231
                double[] cmyk = conv.RGBtoCMYK(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff, 1D);
1232
                info.addField("CMYK", "[" + mathUtil.format(cmyk[0], 4) + ",  " + mathUtil.format(cmyk[1], 4) + ",  " + mathUtil.format(cmyk[2], 4) + ",  " + mathUtil.format(cmyk[3], 4) + "]", 5);
1233
                double[] hsl = conv.RGBtoHSL(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff);
1234
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
1235
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
1236
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
1237
                info.addField("HSL", "[" + mathUtil.format(hsl[0], 4) + ",  " + mathUtil.format(hsl[1], 4) + ",  " + mathUtil.format(hsl[2], 4) + "]", 6);*/
1238
                
1239
                String data = "[";
1240
                try {
1241
                        if (px != null) {
1242
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3) {
1243
                                        for(int i = 0; i < getDataStore().getBandCount(); i++) {
1244
                                                if(getDataStore().isInside(pReal)) {
1245
                                                        Point2D pxAux = transformPoint(pReal);
1246
                                                        int val = ((Integer)getDataStore().getData((int)pxAux.getX(), 
1247
                                                                        (int)pxAux.getY(), i)).intValue();
1248
                                                        if(getDataType()[0] == Buffer.TYPE_BYTE)
1249
                                                                data += (val & 0x000000ff) + ",  ";
1250
                                                        else
1251
                                                                data += val + ",  ";
1252
                                                }
1253
                                        }
1254
                                }
1255
                                if(getDataType()[0] == 4) {
1256
                                        for(int i = 0; i < getDataStore().getBandCount(); i++) {
1257
                                                if(getDataStore().isInside(pReal)) {
1258
                                                        Point2D pxAux = transformPoint(pReal);
1259
                                                        data += ((Float)getDataStore().getData((int)pxAux.getX(), 
1260
                                                                        (int)pxAux.getY(), i)).floatValue() + ",  ";
1261
                                                }
1262
                                        }
1263
                                }
1264
                                if(getDataType()[0] == 5) {
1265
                                        for(int i = 0; i < getDataStore().getBandCount(); i++) {
1266
                                                if(getDataStore().isInside(pReal)) {
1267
                                                        Point2D pxAux = transformPoint(pReal);
1268
                                                        data += ((Double)getDataStore().getData((int)pxAux.getX(), 
1269
                                                                        (int)pxAux.getY(), i)).doubleValue() + ",  ";
1270
                                                }
1271
                                        }
1272
                                }
1273
                        }
1274
                        data +=  "]";
1275
                        info.addField("Band Value", data, 7);
1276
                } catch (RasterDriverException ex) {
1277
                        throw new LoadLayerException("Error en el acceso al dataset", ex);
1278
                } catch (InvalidSetViewException ex) {
1279
                        throw new LoadLayerException("Error en la asignaci?n de la vista en getData", ex);
1280
                } catch (FileNotOpenException ex) {
1281
                        throw new LoadLayerException("Fichero no abierto en el dataset", ex);
1282
                }
1283
                return info;
1284
        }
1285
        
1286
        /**
1287
         * Transforma un punto real a coordenadas pixel
1288
         * 
1289
         * @param numberBand
1290
         * @param pReal
1291
         * @return
1292
         * @throws LoadLayerException 
1293
         * @throws ReadDriverException
1294
         */
1295
        private Point2D transformPoint(Point2D pReal) throws LoadLayerException {
1296
                AffineTransform at = getDataStore().getAffineTransform();
1297
                Point2D px = new Point2D.Double();
1298
                //px = new Point2D.Double(pReal.getX(), pReal.getY());
1299
                try {
1300
                        at.inverseTransform(pReal, px);
1301
                        return px;
1302
                } catch (NoninvertibleTransformException e) {
1303
                        throw new LoadLayerException("Error en la transformaci?n del punto", e);
1304
                }
1305
        }
1306
        
1307
        /*
1308
         * (non-Javadoc)
1309
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1310
         */
1311
        public Object getInfo(String key) {
1312
                if (key.equals("DriverName"))
1313
                        return "gvSIG Raster Driver";
1314
                return null;
1315
        }
1316

    
1317
        /*
1318
         * (non-Javadoc)
1319
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getBandCountFromDataset()
1320
         */
1321
        public int[] getBandCountFromDataset() {
1322
                return getDataStore().getBandCountByProvider();
1323
        }
1324

    
1325
        /*
1326
         * (non-Javadoc)
1327
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1328
         */
1329
        public String getColorInterpretation(int band, int dataset) {
1330
                if (this.getDataStore().getColorInterpretation().get(band) == null)
1331
                        return "Undefined";
1332
                return this.getDataStore().getColorInterpretation().get(band);
1333
        }
1334

    
1335
        /*
1336
         * (non-Javadoc)
1337
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getWktProjection()
1338
         */
1339
        public String getWktProjection() throws RasterDriverException {
1340
                return getDataStore().getWktProjection();
1341
        }
1342

    
1343
        /*
1344
         * (non-Javadoc)
1345
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRGB()
1346
         */
1347
        public boolean isRGB() {
1348
                if ((getDataStore() == null) || (render == null))
1349
                        return false;
1350

    
1351
                if (getDataStore().getDataType()[0] != Buffer.TYPE_BYTE)
1352
                        return false;
1353

    
1354
                boolean R = false;
1355
                boolean G = false;
1356
                boolean B = false;
1357

    
1358
                int[] renderBands = render.getRenderBands();
1359
                for (int i = 0; i < renderBands.length; i++)
1360
                        if (renderBands[i] >= 0)
1361
                                switch (i) {
1362
                                        case 0:
1363
                                                R = true;
1364
                                                break;
1365
                                        case 1:
1366
                                                G = true;
1367
                                                break;
1368
                                        case 2:
1369
                                                B = true;
1370
                                                break;
1371
                                }
1372

    
1373
                if (R && G && B)
1374
                        return true;
1375

    
1376
                return false;
1377
        }
1378

    
1379
        /**
1380
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1381
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1382
         * cacheado o no dependiendo del tama?o de esta.
1383
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1384
         * @return Grid.
1385
         * @throws InterruptedException
1386
         */
1387
        public Grid getFullGrid(boolean interpolated) throws GridException, InterruptedException {
1388
                RasterQuery query = rManager.createQuery();
1389
                query.setAllDrawableBands();
1390
                Buffer bf = null;
1391
                try {
1392
                        query.setAreaOfInterest();
1393
                        bf = getDataStore().query(query);
1394
                } catch (RasterDriverException e) {
1395
                        throw new GridException("Error reading buffer");
1396
                } catch (ProcessInterruptedException e) {
1397
                        throw new InterruptedException("Carga interrumpida");
1398
                } catch (InvalidSetViewException e) {
1399
                        throw new GridException("Error reading buffer");
1400
                }
1401
                return rManager.createGrid(bf, getDataStore(), interpolated);
1402
        }
1403

    
1404
        /*
1405
         * (non-Javadoc)
1406
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getReadOnlyFullGrid(boolean)
1407
         */
1408
        public Grid getReadOnlyFullGrid(boolean interpolated) throws GridException, InterruptedException {
1409
                RasterQuery query = rManager.createQuery();
1410
                query.setReadOnly(true);
1411
                query.setAllDrawableBands();
1412
                Buffer bf = null;
1413
                try {
1414
                        query.setAreaOfInterest();
1415
                        bf = getDataStore().query(query);
1416
                } catch (RasterDriverException e) {
1417
                        throw new GridException("Error reading buffer");
1418
                } catch (ProcessInterruptedException e) {
1419
                        throw new InterruptedException("Carga interrumpida");
1420
                } catch (InvalidSetViewException e) {
1421
                        throw new GridException("Error reading buffer");
1422
                }
1423
                return rManager.createGrid(bf, getDataStore(), interpolated);
1424
        }
1425

    
1426
        /**
1427
         * Obtiene el tama?o de celda de la fuente de datos
1428
         * @return double con el tama?o de celda
1429
         */
1430
        public double getCellSize() {
1431
                return (getDataStore() != null) ? getDataStore().getCellSize() : 1;
1432
        }
1433

    
1434
        /*
1435
         * (non-Javadoc)
1436
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFullRasterExtent()
1437
         */
1438
        public Extent getFullRasterExtent() {
1439
                return this.getDataStore().getExtent();
1440
        }
1441

    
1442

    
1443
        /**
1444
         * Devuelve el fichero asociado a la capa o null si no tiene.
1445
         * @return Fichero.
1446
         */
1447
        public File getFile() {
1448
                if(getDataStore().getParameters() instanceof RasterFileStoreParameters)
1449
                        return ((RasterFileStoreParameters)getDataStore().getParameters()).getFile();
1450
                return new File("");
1451
        }
1452

    
1453
        /**
1454
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1455
         * @param file Fichero a consultar
1456
         * @return true si es aceptado y false si no lo es.
1457
         */
1458
        public boolean isFileAccepted(File file) {
1459
                return getDataStore().isFileSupported(file.getName());
1460
        }
1461
        
1462
        /**
1463
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1464
         * @param file Fichero a consultar
1465
         * @return true si es aceptado y false si no lo es.
1466
         */
1467
        public static boolean isFileSupported(File file) {
1468
                return RasterLocator.getManager().isExtensionSupported(file.getName());
1469
        }
1470

    
1471
        /*
1472
         * (non-Javadoc)
1473
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#existColorTable()
1474
         */
1475
        public boolean existColorTable() {
1476
                return getRender().existColorTable();
1477
        }
1478

    
1479
        /**
1480
         * Returns true if the data store has an alpha band
1481
         */
1482
        public boolean existsAlphaBand() {
1483
                if(getDataStore().getColorInterpretation() != null)
1484
                        return getDataStore().getColorInterpretation().hasAlphaBand();
1485
                else
1486
                        return false;
1487
        }
1488

    
1489
        /*
1490
         * (non-Javadoc)
1491
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAlphaBandNumber()
1492
         */
1493
        public int getAlphaBandNumber() {
1494
                if(getDataStore().getColorInterpretation() != null)
1495
                        return getDataStore().getColorInterpretation().getBand(ColorInterpretation.ALPHA_BAND);
1496
                return -1;
1497
        }
1498

    
1499
        /**
1500
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1501
         * capa busque una leyenda valida.
1502
         * @param ct
1503
         */
1504
        public void setLastLegend(ColorTable ct) {
1505
                lastLegend = ColorTableLegend.createLegend(ct);
1506
        }
1507

    
1508
        /**
1509
         * Devuelve la Leyenda de la capa.
1510
         * @return Leyenda.
1511
         */
1512
        public ILegend getLegend() {
1513
                if (lastLegend != null)
1514
                        return lastLegend;
1515

    
1516
                return null;
1517
        }
1518

    
1519
        /*
1520
         * (non-Javadoc)
1521
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1522
         */
1523
        public void addLegendListener(LegendListener listener) {
1524
                layerChangeSupport.addLayerListener(listener);
1525
        }
1526

    
1527
        /*
1528
         *  (non-Javadoc)
1529
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1530
         */
1531
        public int getShapeType() {
1532
                return TYPES.SURFACE;
1533
        }
1534

    
1535
        /*
1536
         * (non-Javadoc)
1537
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1538
         */
1539
        public void removeLegendListener(LegendListener listener) {
1540
                if(layerChangeSupport != null)
1541
                        layerChangeSupport.removeLayerListener(listener);
1542
        }
1543

    
1544
        /*
1545
         * (non-Javadoc)
1546
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isInside(java.awt.geom.Point2D)
1547
         */
1548
        public boolean isInside(Point2D p) {
1549
                 return getDataStore().isInside(p);
1550
        }
1551

    
1552
        /*
1553
         * (non-Javadoc)
1554
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAffineTransform()
1555
         */
1556
        public AffineTransform getAffineTransform() {
1557
                return getDataStore().getAffineTransform();
1558
        }
1559

    
1560
        /*
1561
         * (non-Javadoc)
1562
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setAffineTransform(java.awt.geom.AffineTransform)
1563
         */
1564
        public void setAffineTransform(AffineTransform transf) {
1565
                if(transf == null)
1566
                        return;
1567
                affineTransformList.add(transf);
1568
                getDataStore().setAffineTransform(transf);
1569
                updateDrawVersion();
1570
        }
1571

    
1572
        /*
1573
         * (non-Javadoc)
1574
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setAffineTransformWithoutHistorical(java.awt.geom.AffineTransform)
1575
         */
1576
        public void setAffineTransformWithoutHistorical(AffineTransform transf) {
1577
                getDataStore().setAffineTransform(transf);
1578
                updateDrawVersion();
1579
        }
1580

    
1581
        /*
1582
         * (non-Javadoc)
1583
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAffineTransformHistorical()
1584
         */
1585
        public Historical getAffineTransformHistorical() {
1586
                return this.affineTransformList;
1587
        }
1588

    
1589
        /*
1590
         * (non-Javadoc)
1591
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#saveGeoToRmf()
1592
         */
1593
        public void saveGeoToRmf() throws RmfSerializerException {
1594
                if (!isOpen())
1595
                        return;
1596

    
1597
                getDataStore().saveGeoreferencingToRmf();
1598
                
1599
                affineTransformList.clear();
1600
                affineTransformList.add(this.getAffineTransform());
1601
        }
1602

    
1603
        /*
1604
         * (non-Javadoc)
1605
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1606
         */
1607
        public boolean isActionEnabled(int action) {
1608
                switch (action) {
1609
                        case IRasterLayerActions.BANDS_FILE_LIST:
1610
                                if (existColorTable() || getDataStore().isMosaic() || getDataStore().isTiled())
1611
                                        return false;
1612
                                break;
1613
                        case IRasterLayerActions.BANDS_RGB:
1614
                                if (existColorTable())
1615
                                        return false;
1616
                                break;
1617
                        case IRasterLayerActions.REPROJECT:
1618
                                if (!isReproyectable())
1619
                                        return false;
1620
                                break;
1621
                        case IRasterLayerActions.CREATEOVERVIEWS:
1622
                                return overviewsSupport();
1623
                        case IRasterLayerActions.OPACITY:
1624
                        case IRasterLayerActions.TRANSPARENCY:
1625
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1626
                        case IRasterLayerActions.ENHANCED:
1627
                        case IRasterLayerActions.PANSHARPENING:
1628
                        case IRasterLayerActions.SELECT_LAYER:
1629
                        case IRasterLayerActions.SAVE_COLORINTERP:
1630
                                return true;
1631
                        case IRasterLayerActions.REMOTE_ACTIONS:
1632
                                return false;
1633
                        case IRasterLayerActions.TAILTRIM:
1634
                        case IRasterLayerActions.GEOLOCATION:
1635
                                return !(getDataStore().isTiled());
1636
                }
1637
                return true;
1638
        }
1639

    
1640
        /*
1641
         * (non-Javadoc)
1642
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1643
         */
1644
        public void setVisible(boolean visibility) {
1645
                if(visibility)
1646
                        state.disableStopped();
1647
                else
1648
                        enableStopped();
1649

    
1650
                if(isAwake() || isClosed())
1651
                        try {
1652
                                this.load();
1653
                        } catch (LoadLayerException e) {
1654
                                e.printStackTrace();
1655
                        }
1656

    
1657
                /*
1658
                 * Cuando se modifica la visibilidad de una capa raster se hace un updateDrawVersion de todas las
1659
                 * capas raster de ese MapContext. Esto es porque la estrategia utilizada por RasterDrawStrategy hace
1660
                 * que se cacheen en blanco las capas raster que est?n ocultas debajo de otras. Al hacer invisibles las
1661
                 * de arriba la cache que estaba en blanco hace que no se pinte nada. Para evitar esto las marcamos todas
1662
                 * como que han sido modificadas para que se vuelvan a leer.
1663
                 */
1664
                if(getMapContext() != null) {
1665
                        ArrayList<FLayer> listLayers = new ArrayList<FLayer>();
1666
                        listLayers = RasterDrawStrategy.getLayerList(getMapContext().getLayers(), listLayers);
1667
                        for (int i = 0; i < listLayers.size(); i++)
1668
                                if(listLayers.get(i) instanceof DefaultFLyrRaster)
1669
                                        ((DefaultFLyrRaster)listLayers.get(i)).updateDrawVersion();
1670
                }
1671

    
1672
                super.setVisible(visibility);
1673
        }
1674

    
1675
        /**
1676
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1677
         * @return valor de transparencia
1678
         */
1679
        public int getTransparency() {
1680
                try {
1681
                        return getRender().getLastTransparency().getOpacity();
1682
                } catch (NullPointerException e) {
1683
                        return super.getTransparency();
1684
                }
1685
        }
1686

    
1687
        /**
1688
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1689
         * o no.
1690
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1691
         */
1692
        public boolean isTransparent() {
1693
                return getRender().getLastTransparency().isTransparencyActive();
1694
        }
1695

    
1696
        /**
1697
         * Asigna la transparencia de la siguiente renderizaci?n
1698
         * @param valor de transparencia
1699
         */
1700
        public void setTransparency(int trans) {
1701
                super.setTransparency(trans);
1702
                try {
1703
                        getRender().getLastTransparency().setOpacity(trans);
1704
                } catch (NullPointerException e) {
1705
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1706
                }
1707
        }
1708

    
1709
        /**
1710
         *
1711
         * @return ROIs asociadas a la capa raster.
1712
         */
1713
        public ArrayList<ROI> getRois() {
1714
                return rois;
1715
        }
1716

    
1717
        /**
1718
         * Establece las ROI asociadas a la capa raster.
1719
         *
1720
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1721
         */
1722
        public void setRois(ArrayList<ROI> rois) {
1723
                this.rois = rois;
1724
        }
1725

    
1726
        /**
1727
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1728
         * devolver? null.
1729
         * @return TreeMap con la lista de capas a dibujar
1730
         */
1731
        public HashMap<DefaultFLyrRaster, Boolean> getRasterStrategy() {
1732
                if(strategy != null)
1733
                        return strategy.getStrategy();
1734
                return null;
1735
        }
1736

    
1737
        /**
1738
         * @return the configuration
1739
         */
1740
        static public IConfiguration getConfiguration() {
1741
                return configuration;
1742
        }
1743

    
1744
        /**
1745
         * @param configuration the configuration to set
1746
         */
1747
        static public void setConfiguration(IConfiguration configuration) {
1748
                DefaultFLyrRaster.configuration = configuration;
1749
        }
1750

    
1751
        /*
1752
         * (non-Javadoc)
1753
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#reload()
1754
         */
1755
        public void reload() throws ReloadLayerException {
1756
                try {
1757
                        super.reload();
1758
                        if (getMapContext() == null)
1759
                                return;
1760
                        if (isStopped())
1761
                                disableStopped();
1762
                        load();
1763
                        getMapContext().invalidate();
1764
                } catch (LoadLayerException e) {
1765
                        setAvailable(false);
1766
                        throw new ReloadLayerException(getName(), e);
1767
                }
1768
        }
1769

    
1770
        /**
1771
         * Devuelve si la capa tiene soporte para poder generar overviews
1772
         * @return
1773
         */
1774
        public boolean overviewsSupport() {
1775
                if ((getDataStore() != null) && (getDataStore().overviewsSupport()))
1776
                        return true;
1777

    
1778
                return false;
1779
        }
1780

    
1781
        /**
1782
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1783
         * en escala de grises
1784
         * @return
1785
         */
1786
        public boolean isRenderingAsGray() {
1787
                int[] renderBands = getRender().getRenderBands();
1788
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1789
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1790
                        return true;
1791
                return false;
1792
        }
1793

    
1794
        /*
1795
         * (non-Javadoc)
1796
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
1797
         */
1798
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1799
                updateDrawVersion();
1800
        }
1801

    
1802
        /*
1803
         * (non-Javadoc)
1804
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#adjustWorldRequest(java.awt.geom.Point2D)
1805
         */
1806
        public Point2D adjustWorldRequest(Point2D req) {
1807
                Envelope ext = null;
1808

    
1809
                ext = getFullEnvelope();
1810
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
1811
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
1812
                return req;
1813
        }
1814

    
1815
        /*
1816
         * (non-Javadoc)
1817
         * @see org.gvsig.fmap.mapcontext.layers.FLyrDefault#cloneLayer()
1818
         */
1819
        public FLayer cloneLayer() throws Exception {
1820
                RasterDataStore  ds = getDataStore().cloneDataStore();
1821
                DefaultFLyrRaster newLayer = new DefaultFLyrRaster();
1822
                newLayer.setName(getName());
1823
                newLayer.setOpenRasterStore(ds);
1824
                newLayer.firstLoad = firstLoad;
1825
                
1826
                List<RasterFilter> filters = getRender().getFilterList().getStatusCloned();
1827

    
1828
                //Hacemos una copia de las bandas a renderizar
1829
                if(getRender().getRenderBands() != null) {
1830
                        int[] rb = new int[getRender().getRenderBands().length];
1831
                        for (int i = 0; i < rb.length; i++)
1832
                                rb[i] = getRender().getRenderBands()[i];
1833
                        newLayer.getRender().setRenderBands(rb);
1834
                }
1835

    
1836
                //Asignamos el entorno
1837
                if(newLayer.getRender().getFilterList() == null)
1838
                        newLayer.getRender().setFilterList(RasterLocator.getManager().createEmptyFilterList(getRender().getFilterList().getInitDataType()));
1839
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
1840
                newLayer.getRender().getFilterList().setStatus(filters);
1841

    
1842
                // Asignamos los valores noData del original
1843
                newLayer.setNoDataValue(getNoDataValue());
1844
                if(getDataStore().getNoDataValue().isDefined())
1845
                        newLayer.setNoDataTransparent(true);
1846
                newLayer.enableOpen();
1847
                
1848
                return newLayer;
1849
        }
1850
        
1851
        /*
1852
         * (non-Javadoc)
1853
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileLayer()
1854
         */
1855
        public FLayer getFileLayer() throws RasterDriverException {
1856
                try {
1857
                        return cloneLayer();
1858
                } catch (Exception e) {
1859
                }
1860
                return null;
1861
        }
1862
        
1863
        /*
1864
         * (non-Javadoc)
1865
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#addFile(java.lang.String)
1866
         */
1867
        public void addFile(String file) throws InvalidSourceException {
1868
                getDataStore().addFile(file);
1869
        }
1870
        
1871
        /*
1872
         * (non-Javadoc)
1873
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#removeFile(java.lang.String)
1874
         */
1875
        public void removeFile(String file) {
1876
                getDataStore().removeFile(file);
1877
        }
1878

    
1879
        /*****************************************************/
1880

    
1881
        public void disableStopped() {
1882
                if(state != null)
1883
                        state.disableStopped();
1884
        }
1885

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

    
1888
        public void enableClosed() throws NotAvailableStateException {
1889
                if(state != null)
1890
                        state.enableClosed();
1891
        }
1892

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

    
1895
        public void enableStopped() {state.enableStopped();}
1896

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

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

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

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

    
1905

    
1906
        @SuppressWarnings("unchecked")
1907
        public Set getMetadataChildren() {
1908
                return null;
1909
        }
1910

    
1911
        public Object getMetadataID() {
1912
                return getName();
1913
        }
1914

    
1915
        public String getMetadataName() {
1916
                return null;
1917
        }
1918

    
1919
        /*
1920
         * (non-Javadoc)
1921
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getDataStore()
1922
         */
1923
        public RasterDataStore getDataStore() {
1924
                if(dataStore != null) {
1925
                        RasterDataParameters params = (RasterDataParameters)dataStore.getParameters();
1926
                        if (getCoordTrans() != null && params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
1927
                                this.dataStore.setCoordTrans(getCoordTrans());
1928
                        }
1929
                }
1930
                return this.dataStore;
1931
        }
1932
        
1933
        /*
1934
         * (non-Javadoc)
1935
         * @see org.cresques.geo.Projected#getProjection()
1936
         */
1937
        public IProjection getProjection() {
1938
                RasterDataParameters p = (RasterDataParameters)getDataStore().getParameters();
1939
                if(p.getReprojectionOption() == RasterDataParameters.DONT_CHANGE_PROJECTION)
1940
                        return null;
1941
                return getDataStore().getProjection();
1942
        }
1943

    
1944
        public void setOpenRasterStore(DataStore dataStore) throws LoadLayerException {
1945
                if(dataStore instanceof CoverageStoreProviderServices) {
1946
                        try {
1947
                                this.dataStore = rManager.open(((CoverageStoreProviderServices) dataStore).getProvider(), dataStore.getParameters());
1948
                        } catch (NotSupportedExtensionException e) {
1949
                                throw new LoadLayerException("Extension not supported", e);
1950
                        } catch (RasterDriverException e) {
1951
                                throw new LoadLayerException("Error opening the DataStore", e);
1952
                        }
1953
                } else
1954
                        this.dataStore = (RasterDataStore) dataStore;
1955
                try {
1956
                        enableAwake();
1957
                } catch (NotAvailableStateException e) {
1958
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
1959
                }
1960
                setProjection(getDataStore().getProjection());
1961
        }
1962
        
1963
        /*
1964
         * (non-Javadoc)
1965
         * @see org.gvsig.fmap.mapcontext.layers.operations.SingleLayer#setDataStore(org.gvsig.fmap.dal.DataStore)
1966
         */
1967
        public void setDataStore(DataStore dataStore) throws LoadLayerException {
1968
                setOpenRasterStore(dataStore);
1969
                load();
1970
        }
1971
        
1972
        /*
1973
         * (non-Javadoc)
1974
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRemote()
1975
         */
1976
        public boolean isRemote() {
1977
                return false;
1978
        }
1979
        
1980
        /**
1981
         * Returns true if exists a process reading data from this layer
1982
         * @return
1983
         */
1984
        public boolean isReadingData() {
1985
                return readingData != null;
1986
        }
1987

    
1988
        /**
1989
         * When a process is using information of this layer this variable will contain
1990
         * the thread ID.
1991
         * @param readingData
1992
         */
1993
        public synchronized void setReadingData(String readingData) {
1994
                this.readingData = readingData;
1995
        }
1996
        
1997
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel,
1998
                        boolean fast)
1999
                        throws LoadLayerException, DataException {
2000
                return null;
2001
        }
2002

    
2003
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel)
2004
                        throws LoadLayerException, DataException {
2005
                return null;
2006
        }
2007

    
2008
        @Override
2009
        protected void doDispose() throws BaseException {
2010
                if(render != null)
2011
                        render.dispose();
2012
                if(getDataStore() != null)
2013
                        getDataStore().dispose();
2014
                finalize();
2015
        }
2016

    
2017
        /*
2018
         * (non-Javadoc)
2019
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#getZoomLevel()
2020
         */
2021
        public int getZoomLevel() {
2022
                return zoomLevel;
2023
        }
2024

    
2025
        /*
2026
         * (non-Javadoc)
2027
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#setZoomLevel(int)
2028
         */
2029
        public void setZoomLevel(int zoomLevel) {
2030
                this.zoomLevel = zoomLevel;
2031
        }
2032
        
2033
        /*
2034
         * (non-Javadoc)
2035
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#increaseZoomLevel()
2036
         */
2037
        public boolean increaseZoomLevel() {
2038
                if(zoomLevel < (this.getDataStore().getZoomLevels() - 1)) { 
2039
                        zoomLevel ++;
2040
                        recalcLevel = false;
2041
                        return true;
2042
                }
2043
                return false;
2044
        }
2045
        
2046
        /*
2047
         * (non-Javadoc)
2048
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#decreaseZoomLevel()
2049
         */
2050
        public boolean decreaseZoomLevel() {
2051
                if(zoomLevel > 0) { 
2052
                        zoomLevel --;
2053
                        recalcLevel = false;
2054
                        return true;
2055
                }
2056
                return false;
2057
        }
2058
        
2059
        /*
2060
         * (non-Javadoc)
2061
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#getCoordsInLevel(java.awt.geom.Point2D, int, int, int)
2062
         */
2063
        public Envelope getCoordsInLevel(Point2D center, int level, int w, int h) throws CreateEnvelopeException {
2064
                Extent ex = getDataStore().getCoordsInLevel(center, level, w, h);
2065
                return geomManager.createEnvelope(ex.getULX(), ex.getULY(), ex.getLRX(), ex.getLRY(), SUBTYPES.GEOM2D);
2066
        }
2067
        
2068
        /*
2069
         * (non-Javadoc)
2070
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#isEnabledMultiresolution()
2071
         */
2072
        public boolean isEnabledMultiresolution() {
2073
                return getDataStore().isTiled();
2074
        }
2075
        
2076
        /*
2077
         * (non-Javadoc)
2078
         * @see org.gvsig.raster.fmap.layers.Multiresolution#setTileServer(java.lang.Class)
2079
         */
2080
        public void setTileServer(Class<?> tileServer) throws InitializeException {
2081
                getDataStore().setTileServer(tileServer);
2082
        }
2083
        
2084
        @SuppressWarnings("unchecked")
2085
        @Override
2086
        public void loadFromState(PersistentState state)
2087
                        throws PersistenceException {
2088
                super.loadFromState(state);
2089
                
2090
                //this.status = (IStatusRaster)state.get("status");
2091
                List<ROI> rois = state.getList("rois");
2092
                if(rois != null) {
2093
                        this.rois = new ArrayList<ROI>();
2094
                        this.rois.addAll(rois);
2095
                }
2096
                this.zoomLevel = state.getInt("zoomLevel");
2097
                this.recalcLevel = state.getBoolean("recalcLevel");
2098
                if(getDataStore() == null)
2099
                        this.dataStore = (RasterDataStore)state.get("rasterdatastore");
2100
                this.lastLegend = (ILegend)state.get("legend");
2101
                this.colorTableLoadedFromProject = (ColorTable)state.get("colortable");
2102
                this.zoomLevel = state.getInt("zoomLevel");
2103
                this.recalcLevel = state.getBoolean("recalcLevel");
2104
                loadedFromProject = true;
2105
        }
2106

    
2107
        @Override
2108
        public void saveToState(PersistentState state) throws PersistenceException {
2109
                super.saveToState(state);
2110
                
2111
                //state.set("status", status);
2112
                state.set("rasterdatastore", getDataStore());        
2113
                state.set("legend", lastLegend);        
2114
                state.set("rois", rois);        
2115
                state.set("colortable", getRender().getColorTable());        
2116
                state.set("zoomLevel", zoomLevel);        
2117
                state.set("recalcLevel", recalcLevel);        
2118
        }        
2119
        
2120
        public static void registerPersistence() {
2121
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
2122
                DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
2123
                if( definition == null ) {
2124
                        if (manager.getDefinition(FLyrDefault.class) == null) {
2125
                                FLyrDefault.registerPersistent();
2126
                        }
2127
                        definition = manager.addDefinition(
2128
                                        DefaultFLyrRaster.class,
2129
                                        PERSISTENT_NAME,
2130
                                        PERSISTENT_DESCRIPTION,
2131
                                        null, 
2132
                                        null
2133
                        );
2134
                        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE, "FLyrDefault");
2135
                        
2136
                        registerPersistence(definition);
2137
                }
2138
        }
2139
        
2140
        public static void registerPersistence(DynStruct definition) {
2141
                //definition.addDynFieldObject("status").setClassOfValue(StatusLayerRaster.class).setMandatory(false);
2142
                definition.addDynFieldObject("rasterdatastore").setClassOfValue(RasterDataStore.class).setMandatory(true);
2143
                definition.addDynFieldObject("legend").setClassOfValue(ILegend.class).setMandatory(false);
2144
                definition.addDynFieldList("rois").setClassOfItems(ROI.class).setMandatory(false);
2145
                definition.addDynFieldObject("colortable").setClassOfValue(ColorTable.class).setMandatory(false);
2146
                definition.addDynFieldInt("zoomlevel").setMandatory(false);
2147
                definition.addDynFieldBoolean("recalcLevel").setMandatory(false);
2148
        }
2149

    
2150
        /*
2151
         * (non-Javadoc)
2152
         * @see org.gvsig.fmap.mapcontext.layers.operations.Classifiable#getGeometryType()
2153
         */
2154
        public GeometryType getGeometryType() throws ReadException {
2155
                try {
2156
                        return GeometryLocator.getGeometryManager().getGeometryType(TYPES.SURFACE, SUBTYPES.GEOM2D);
2157
                } catch (GeometryTypeNotSupportedException e) {
2158
                        throw new ReadException(getDataStore().getName(), e);
2159
                } catch (GeometryTypeNotValidException e) {
2160
                        throw new ReadException(getDataStore().getName(), e);
2161
                } 
2162
        }
2163
        
2164
        public void setDataStore(DataStore dataStore, String domain) throws LoadLayerException {
2165
                setDataStore(dataStore);
2166
        }
2167
        
2168
        /*
2169
         * (non-Javadoc)
2170
         * @see java.lang.Object#finalize()
2171
         */
2172
        protected void finalize() {
2173
                layerChangeSupport             = null;
2174
                state                          = null;
2175
                lastLegend                     = null;
2176
                colorTableLoadedFromProject    = null;
2177
                if(rois != null) {
2178
                        rois.clear();
2179
                        rois = null;
2180
                }
2181
                strategy                       = null;
2182
                configuration                  = null;
2183
                fileUtil                       = null;
2184
                rasterUtil                     = null;
2185
                crsUtil                        = null;
2186
                mathUtil                       = null;
2187
                uri                            = null;
2188
                affineTransformList            = null;
2189
                readingData                    = null;
2190
                dataStore                      = null;
2191
                render                         = null;
2192
        }
2193

    
2194
}