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 @ 1087

History | View | Annotate | Download (66.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.ReadException;
93
import org.gvsig.fmap.dal.raster.spi.CoverageStoreProviderServices;
94
import org.gvsig.fmap.geom.GeometryLocator;
95
import org.gvsig.fmap.geom.GeometryManager;
96
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
97
import org.gvsig.fmap.geom.Geometry.TYPES;
98
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
99
import org.gvsig.fmap.geom.primitive.Envelope;
100
import org.gvsig.fmap.geom.type.GeometryType;
101
import org.gvsig.fmap.geom.type.GeometryTypeNotSupportedException;
102
import org.gvsig.fmap.geom.type.GeometryTypeNotValidException;
103
import org.gvsig.fmap.mapcontext.MapContextLocator;
104
import org.gvsig.fmap.mapcontext.MapContextManager;
105
import org.gvsig.fmap.mapcontext.ViewPort;
106
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
107
import org.gvsig.fmap.mapcontext.exceptions.ReloadLayerException;
108
import org.gvsig.fmap.mapcontext.layers.FLayer;
109
import org.gvsig.fmap.mapcontext.layers.FLyrDefault;
110
import org.gvsig.fmap.mapcontext.layers.LayerChangeSupport;
111
import org.gvsig.fmap.mapcontext.layers.LayerListener;
112
import org.gvsig.fmap.mapcontext.layers.Tiling;
113
import org.gvsig.fmap.mapcontext.layers.operations.Classifiable;
114
import org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint;
115
import org.gvsig.fmap.mapcontext.layers.operations.SingleLayer;
116
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
117
import org.gvsig.fmap.mapcontext.rendering.legend.events.listeners.LegendListener;
118
import org.gvsig.raster.fmap.legend.ColorTableLegend;
119
import org.gvsig.raster.util.RasterNotLoadException;
120
import org.gvsig.tools.ToolsLocator;
121
import org.gvsig.tools.dynobject.DynClass;
122
import org.gvsig.tools.dynobject.DynObjectManager;
123
import org.gvsig.tools.dynobject.DynObjectSet;
124
import org.gvsig.tools.dynobject.DynStruct;
125
import org.gvsig.tools.exception.BaseException;
126
import org.gvsig.tools.persistence.PersistenceManager;
127
import org.gvsig.tools.persistence.PersistentState;
128
import org.gvsig.tools.persistence.exception.PersistenceException;
129
import org.gvsig.tools.task.Cancellable;
130
import org.gvsig.tools.task.SimpleTaskStatus;
131
import org.gvsig.tools.task.TaskStatusManager;
132
import org.slf4j.Logger;
133
import org.slf4j.LoggerFactory;
134

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

    
184
        /**
185
         * Lista de transformaciones afines que son aplicadas. Esta lista es
186
         * simplemente un historico que no se utiliza. Es posible utilizarlo para
187
         * recuperar transformaciones anteriores.
188
         */
189
        private Historical              affineTransformList    = null;
190
        protected String                readingData            = null;
191
        //It is set to true if the method init has been called at least once
192
        protected boolean               layerInitialize        = false;
193
        
194
        public DefaultFLyrRaster() {
195
                affineTransformList = rManager.createHistoricalService();
196
        }
197
        
198
        public static void registerDynClass() {
199
                DynObjectManager manager = ToolsLocator.getDynObjectManager();
200
            DynClass dynClass = manager.add("RasterInfo", "Raster layer Info by point");
201
            dynClass.setNamespace("InfoByPoint");
202
            dynClass.addDynFieldString("File");
203
            dynClass.addDynFieldString("View Point");
204
            dynClass.addDynFieldString("Pixel Point");
205
            dynClass.addDynFieldString("RGB");
206
            dynClass.addDynFieldString("CMYK");
207
            dynClass.addDynFieldString("HSL");
208
            dynClass.addDynFieldString("Band Value");
209
            dynClass.addDynFieldString("World Point");
210
        }
211
        
212
        /**
213
         * Builds a new raster layer
214
         * @param fileName
215
         * @return
216
         * @throws RasterNotLoadException 
217
         * @throws LoadLayerException 
218
         */
219
        public static DefaultFLyrRaster createLayer(String layerName, File file) throws LoadLayerException {
220
                ProviderServices provServ = RasterLocator.getManager().getProviderServices();
221
                RasterDataParameters storeParameters = provServ.createParameters(file.getName());
222
                storeParameters.setURI(file.getPath());
223
                
224
                MapContextManager mcm = MapContextLocator.getMapContextManager();
225
                DefaultFLyrRaster lyr = (DefaultFLyrRaster) mcm.createLayer(layerName, storeParameters);
226

    
227
                return lyr;
228
        }
229

    
230
        /*
231
         * (non-Javadoc)
232
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setName(java.lang.String)
233
         */
234
        public void setName(String name) {
235
                super.setName(name);
236

    
237
                //Si la capa tiene nombre acivamos el estado awake
238
                if(name != null)
239
                        try {
240
                                if(isClosed())
241
                                        enableAwake();
242
                        } catch (NotAvailableStateException e) {
243
                                logger.error("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
244
                        }
245
        }
246

    
247
        /*
248
         * (non-Javadoc)
249
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#wakeUp()
250
         */
251
        public void wakeUp(){
252
                try {
253
                        reload();
254
                } catch (ReloadLayerException e) {
255
                        // No se ha podido recuperar la capa con exito
256
                }
257
        }
258

    
259
        /*
260
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
261
         */
262
        public void load() throws LoadLayerException {
263
                if (isStopped() || getDataStore() == null)
264
                        return;
265

    
266
                enableStopped(); // Paramos la capa mientras se hace un load
267

    
268
                int test = -1;
269
                DataStoreParameters params = getDataStore().getParameters();
270
                DataStoreParameters p = params;
271
                if (params != null) {
272
                        if(params instanceof TileDataParameters) {
273
                                uri = ((RasterDataParameters)params).getURI();
274
                                if(uri == null)
275
                                        p = (DataStoreParameters)((TileDataParameters)params).getDataParameters();
276
                        }
277
                        if(uri == null) {
278
                                if(params instanceof RasterDataParameters)
279
                                        uri = ((RasterDataParameters)p).getURI();
280
                        }
281
                        test = uri.indexOf("ecwp:");
282
                }
283

    
284
                if (test != -1) {
285
                        String urlECW = uri.substring(test + 6);
286
                        uri = "ecwp://" + urlECW;
287
                        System.err.println(test + " " + uri);
288
                }
289

    
290
                try {
291
                        if(!dataStore.isOpen())
292
                                dataStore = rManager.open(params);
293
                } catch (NotSupportedExtensionException e) {
294
                        throw new LoadLayerException(this.getName());
295
                } catch (RasterDriverException e) {
296
                        throw new LoadLayerException(this.getName());
297
                }
298
        }
299

    
300
        /**
301
         * Acciones de inicializaci?n despu?s de que la fuente de datos
302
         * de la capa est? asignada. El tipo de fuente de datos es variable
303
         * puede ser MultiRasterDataset, CompositeDataset u otras que existan e
304
         * implementen IRasterDatasource.
305
         * @throws FilePaletteException 
306
         */
307
        public void init() throws LoadLayerException, FilePaletteException {
308
                layerInitialize = true;
309
                
310
                if (dataStore == null)
311
                        throw new LoadLayerException("Formato no valido", new IOException());
312

    
313
                render = dataStore.getRender();
314
                render.addVisualPropertyListener(this);
315
                initFilters();
316

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

    
321
                try {
322
                        if(!isOpen())
323
                                enableOpen();
324
                } catch (NotAvailableStateException e) {
325
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Awake=" + isAwake(), e);
326
                }
327
        }
328

    
329
        /*
330
         * (non-Javadoc)
331
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#readProjection()
332
         */
333
        public IProjection readProjection() throws RasterDriverException {
334
                try {
335
                        crsUtil.setCRSFactory(CRSFactory.cp);
336
                        if( dataStore == null )
337
                                return null;
338
                        return crsUtil.convertWktToIProjection(dataStore.getWktProjection());
339
                } catch (Exception e) {
340
                        throw new RasterDriverException("Problems converting from WKT to IProjection", e);
341
                } catch (Error e) {
342
                        e.printStackTrace();
343
                        return null;
344
                }
345
        }
346

    
347
        /**
348
         * Crea el objeto renderizador de raster
349
         * @return Rendering
350
         */
351
        public Render getRender() {
352
                if (render == null) {
353
                        if(dataStore != null) {
354
                                render = dataStore.getRender();
355
                                render.addVisualPropertyListener(this);
356
                        }
357
                }
358
                return render;
359
        }
360
        
361
        /*
362
         * (non-Javadoc)
363
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getURI()
364
         */
365
        public String getURI() {
366
                return uri;
367
        }
368

    
369
        /*
370
         * (non-Javadoc)
371
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setNoDataTransparent(boolean)
372
         */
373
        public void setNoDataTransparent(boolean t) {
374
                getNoDataValue().setNoDataTransparent(t);
375
                if(getRender().getLastTransparency() != null) {
376
                        getRender().getLastTransparency().setNoData(dataStore.getNoDataValue());
377
                        getRender().getLastTransparency().activeTransparency();
378
                }
379
        }
380

    
381
        /**
382
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
383
         * @throws FilePaletteException 
384
         */
385
        protected void initFilters() throws FilePaletteException {
386
                if(getDataType() == null)
387
                        return;
388
                        
389
                RasterFilterList filterList = rManager.createEmptyFilterList(getDataType()[0]);
390
                if(loadedFromProject) {
391
                        filterList = getDataStore().getRender().getFilterList();
392
                }
393
                filterList.addEnvParam("IStatistics", dataStore.getStatistics());
394
                filterList.addEnvParam("MultiRasterDataset", dataStore);
395

    
396
                if(dataStore == null)
397
                        return;
398
                
399
                if(dataStore.getNoDataValue() != null) {
400
                        dataStore.getNoDataValue().load();
401
                        if(dataStore.getNoDataValue().isDefined())
402
                                setNoDataTransparent(true);
403
                }
404

    
405
                filterList.setInitDataType(getDataType()[0]);
406

    
407
                // Quitamos la leyenda
408
                lastLegend = null;
409

    
410
                try {
411
                        //Si en la carga del proyecto se carg? una tabla de color asignamos esta
412
                        if(colorTableLoadedFromProject != null) {
413
                                setLastLegend(colorTableLoadedFromProject);
414
                                RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
415
                                Params params = filterList.createEmptyFilterParams();
416
                                params.setParam("colorTable", colorTableLoadedFromProject);
417
                                colorTableManager.addFilter(params);
418
                        } else
419
                                //sino ponemos la tabla asociada al raster
420
                                if (dataStore.getColorTable() != null) {
421
                                        ColorTable table = dataStore.getColorTable();
422
                                        setLastLegend(table);
423
                                        RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
424
                                        Params params = filterList.createEmptyFilterParams();
425
                                        params.setParam("colorTable", table);
426
                                        colorTableManager.addFilter(params);
427
                                } else //sino hace lo que dice en las preferencias
428
                                        if(dataStore.needEnhanced() || 
429
                                                        (loadedFromProject && filterList.get("enhanced_stretch") != null)) 
430
                                                loadEnhancedOrColorTable(filterList);
431
                        colorTableLoadedFromProject = null;
432

    
433
                        getRender().setFilterList(filterList);
434
                        // Inicializo la transparencia para el render
435
                        if(!loadedFromProject) {
436
                                getRender().setLastTransparency(dataStore.getTransparency().cloneTransparency());
437
                        }
438
                        loadedFromProject = false;
439
                } catch (FilterTypeException e) {
440
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
441
                        logger.error("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
442
                } catch (FilterManagerException e) {
443
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
444
                        logger.error("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
445
                }
446
        }
447

    
448
        /**
449
         * Mira la configuracion para saber si debe cargar un realce o una tabla
450
         * de color por defecto
451
         * @param filterManager
452
         * @throws FilterTypeException
453
         * @throws FilePaletteException 
454
         */
455
        private void loadEnhancedOrColorTable(RasterFilterList filterList) throws FilterTypeException, FilterManagerException, FilePaletteException {
456
                String colorTableName = null;
457
                if(configuration != null)
458
                        colorTableName = configuration.getValueString("loadlayer_usecolortable", (String) null);
459

    
460
                String palettesPath = System.getProperty("user.home") +
461
                File.separator +
462
                "gvSIG" + // PluginServices.getArguments()[0] +
463
                File.separator + "colortable";
464

    
465
                Statistics stats = dataStore.getStatistics();
466
                ColorTableLibrary colorTableLibrary = rManager.getDataStructFactory().getColorTableLibrary();
467

    
468
                if (colorTableName != null)
469
                        try {
470
                                stats.calculate(RasterLibrary.statisticsScale);
471
                                if (getDataStore().getBandCount() == 1) {
472
                                        ArrayList<String> fileList = colorTableLibrary.getPaletteFileList(palettesPath);
473
                                        for (int i = 0; i < fileList.size(); i++) {
474
                                                ArrayList<ColorItem> paletteItems = new ArrayList<ColorItem>();
475
                                                String paletteName = colorTableLibrary.loadPalette(palettesPath, (String) fileList.get(i), paletteItems);
476
                                                if (paletteName.equals(colorTableName)) {
477
                                                        if (paletteItems.size() <= 0)
478
                                                                continue;
479

    
480
                                                        ColorTable colorTable = colorTableLibrary.createColorTable();
481
                                                        colorTable.setName(paletteName);
482
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
483
                                                        colorTable.setInterpolated(true);
484

    
485
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
486

    
487
                                                        setLastLegend(colorTable);
488

    
489
                                                        RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
490
                                                        Params params = filterList.createEmptyFilterParams();
491
                                                        params.setParam("colorTable", colorTable);
492
                                                        colorTableManager.addFilter(params);
493
                                                        return;
494
                                                }
495
                                        }
496
                                }
497
                        } catch (FileNotOpenException e) {
498
                                // No podemos aplicar el filtro
499
                        } catch (RasterDriverException e) {
500
                                // No podemos aplicar el filtro
501
                        } catch (ProcessInterruptedException e) {
502
                                // El usuario ha cancelado el proceso
503
                        }
504

    
505
                        RasterFilterListManager enhancementManager = filterList.getManagerByID("EnhancementStretch");
506
                        Params params = filterList.createEmptyFilterParams();
507
                        params.setParam("stats", stats);
508
                        params.setParam("remove", new Boolean(false));
509
                        params.setParam("renderBands", getRender().getRenderBands());
510
                        params.setParam("stretchs", null);//coge el LinearStretchParams por defecto
511
                        params.setParam("rgb", new Boolean(true));
512
                        enhancementManager.addFilter(params);
513
        }
514

    
515
        /*
516
         * (non-Javadoc)
517
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isReproyectable()
518
         */
519
        public boolean isReproyectable() {
520
                if (dataStore == null)
521
                        return false;
522
                return dataStore.isReproyectable();
523
        }
524

    
525
        /**
526
         * @throws ReadException
527
         * @throws ReadDriverException
528
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
529
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
530
         *                 com.iver.utiles.swing.threads.Cancellable)
531
         */
532
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadException {
533
                this.image = image;
534
                TaskEventManager task = rManager.getRasterTask();
535
                task.setEvent(null);
536
                
537
                if(!layerInitialize) {
538
                        if (dataStore != null)
539
                                try {
540
                                        this.init();
541
                                } catch (FilePaletteException e) {
542
                                        throw new ReadException("Error in raster legend", e);
543
                                } catch (LoadLayerException e) {
544
                                        throw new ReadException("Error initializing the layer", e);
545
                                }
546
                }
547

    
548
                try {
549
                        if (!isOpen())
550
                                return;
551

    
552
                        enableStopped();
553
                        // callLegendChanged(null);
554
                        
555
                        //Solo el zoom normal recalcula el nivel dependiendo de la escala. El zoom por niveles asigna
556
                        //?l el nivel de zoom por lo que no habr? que recalcularlo.
557
                        if(recalcLevel) {
558
                                double pixelSize = vp.getEnvelope().getLength(0) / (double)vp.getImageWidth();
559
                                zoomLevel = dataStore.getNearestLevel(pixelSize);
560
                        }
561
                        recalcLevel = true;
562

    
563
                        strategy = new RasterDrawStrategy(getMapContext(), this);
564
                        strategy.stackStrategy();
565
                        HashMap<DefaultFLyrRaster, Boolean> tStr = strategy.getStrategy();
566
                        if (tStr != null &&
567
                                tStr.get(this) != null &&
568
                                ((Boolean) (tStr.get(this))).booleanValue() == false) {
569
                                disableStopped();
570
                                return;
571
                        }
572

    
573
                        if (isWithinScale(scale)) {
574
                                
575
                                if (mustTileDraw) {
576
                                        Point2D p = vp.getOffset();
577
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
578
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
579
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
580
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
581
                                                // drawing part
582
                                                try {
583
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
584
                                                        draw(image, g, vport, cancel);
585
                                                } catch (InterruptedException e) {
586
                                                        System.out.println("Se ha cancelado el pintado");
587
                                                } catch (InvalidSetViewException e) {
588
                                                        throw new ReadException("Error reading file.", e);
589
                                                } catch (RasterDriverException e) {
590
                                                        throw new ReadException("Error reading file.", e);
591
                                                }  catch (NoninvertibleTransformException e) {
592
                                                        throw new ReadException("Error in the transformation.", e);
593
                                                }
594
                                } else
595
                                        try {
596
                                                draw(image, g, vp, cancel);
597
                                        } catch (InterruptedException e) {
598
                                                System.out.println("Se ha cancelado el pintado");
599
                                        } catch (InvalidSetViewException e) {
600
                                                throw new ReadException("Error reading file.", e);
601
                                        } catch (RasterDriverException e) {
602
                                                throw new ReadException("Error reading file.", e);
603
                                        }
604

    
605
                        }
606
                        
607
                        //callLegendChanged(null);
608
                } finally {
609
                        disableStopped();
610
                        task.setEvent(null);
611
                }
612
        }
613

    
614
        protected void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws RasterDriverException, InvalidSetViewException, InterruptedException {
615
                Envelope adjustedExtent = vp.getAdjustedExtent();
616
                if (adjustedExtent == null)
617
                        return;
618
                Extent e = rManager.getDataStructFactory().createExtent(adjustedExtent.getLowerCorner().getX(),
619
                                adjustedExtent.getUpperCorner().getY(), adjustedExtent
620
                                                .getUpperCorner().getX(),
621
                                adjustedExtent
622
                                                .getLowerCorner().getY());
623
                Dimension imgSz = vp.getImageSize();
624
                ViewPortData vp2 = rManager.createViewPortData(vp.getProjection(), e, imgSz );
625
                vp2.setMat(vp.getAffineTransform());
626
                //vp2.setTime(vp.getTime()); 
627
                
628
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
629
                SimpleTaskStatus taskStatus = manager.createDefaultSimpleTaskStatus("Drawing " + getName() + "...");
630
                manager.add(taskStatus);
631
                
632
                try {
633
                        //Cancelaci?n temporal para tiles
634
                        getRender().setCancel(cancel);
635
                        if(getDataStore().isTiled()) {
636
                                getRender().drawTiledService(g, vp2, vp.getImageSize(), taskStatus);
637
                        } else {
638
                                getRender().draw(g, vp2, taskStatus);
639
                                taskStatus.terminate();
640
                        }
641
                } catch (ProcessInterruptedException e1) {
642
                }
643
        }
644

    
645
        /**
646
         * Inserta la proyecci?n.
647
         *
648
         * @param proj Proyecci?n.
649
         */
650
        public void setProjection(IProjection proj) {
651
                super.setProjection(proj);
652
        }
653

    
654
        /*
655
         * (non-Javadoc)
656
         * @see org.gvsig.fmap.mapcontext.layers.FLayer#getFullEnvelope()
657
         */
658
        public Envelope getFullEnvelope() {
659
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
660
                //un extent aunque la capa no est? abierta
661
                if(/*!isOpen() || */dataStore == null || dataStore.getExtent() == null)
662
                        return null;
663

    
664
                Rectangle2D e = dataStore.getExtent().toRectangle2D();
665
                try {
666
                        return geomManager.createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
667
                                        .getMaxY(), SUBTYPES.GEOM2D);
668
                } catch (CreateEnvelopeException e1) {
669
                        logger.error("Error creating the envelope", e);
670
                        return null;
671
                }
672
        }
673

    
674
        /**
675
         * Obtiene el valor del pixel del Image en la posici?n x,y
676
         * @param x Posici?n x
677
         * @param y Posici?n y
678
         * @return valor de pixel
679
         */
680
        public int[] getPixel(int pxx, int pxy) {
681
                int[] argb = { -1, -1, -1, -1 };
682
                if (!isOpen() || (image == null))
683
                        return argb;
684
                if (pxx >= 0 && pxx < image.getWidth() && pxy >= 0 && pxy < image.getHeight()) {
685
                        int value = image.getRGB(pxx, pxy);
686
                        argb[0] = ((value & 0xff000000) >> 24);
687
                        argb[1] = ((value & 0x00ff0000) >> 16);
688
                        argb[2] = ((value & 0x0000ff00) >> 8);
689
                        argb[3] = (value & 0x000000ff);
690
                }
691
                return argb;
692
        }
693

    
694
        /*
695
         * (non-Javadoc)
696
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
697
         */
698
        public double getMaxX() {
699
                if(getFullEnvelope() != null)
700
                        return getFullEnvelope().getMaximum(0);
701
                return -1;
702
        }
703

    
704
        /*
705
         * (non-Javadoc)
706
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
707
         */
708
        public double getMaxY() {
709
                if(getFullEnvelope() != null)
710
                        return this.getFullEnvelope().getMaximum(1);
711
                return -1;
712
        }
713

    
714
        /*
715
         * (non-Javadoc)
716
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinX()
717
         */
718
        public double getMinX() {
719
                if(getFullEnvelope() != null)
720
                        return getFullEnvelope().getMinimum(0);
721
                return -1;
722
        }
723

    
724
        /*
725
         * (non-Javadoc)
726
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinY()
727
         */
728
        public double getMinY() {
729
                if(getFullEnvelope() != null)
730
                        return getFullEnvelope().getMinimum(1);
731
                return -1;
732
        }
733

    
734
        /* (non-Javadoc)
735
         * @deprecated. See String getInfo(Point p) throws DriverException
736
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
737
         */
738
        public String queryByPoint(Point p) {
739
                if (!isOpen())
740
                        return null;
741
                ColorConversion conv = rManager.getColorConversion();
742

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

    
745
                ArrayList<Object> attr = getAttributes();
746
                data += "  <raster\n";
747
                data += "    File=\"" + getFile() + "\"\n";
748
                for (int i = 0; i < attr.size(); i++) {
749
                        Object[] a = (Object[]) attr.get(i);
750

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

    
769
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
770
                return data;
771
        }
772

    
773
        /**
774
         * Filters a string for being suitable as XML Tag, erasing
775
         * all not alphabetic or numeric characters.
776
         * @param s
777
         * @return string normalized
778
         */
779
        private String normalizeAsXMLTag(String s) {
780
                return s.replaceAll("[^a-zA-Z0-9]", "");
781
        }
782

    
783
        /*
784
         * (non-Javadoc)
785
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAttributes()
786
         */
787
        public ArrayList<Object> getAttributes() {
788
                ArrayList<Object> attr = new ArrayList<Object>();
789
                if(!isOpen())
790
                        return attr;
791
                Object [][] a = {
792
                        {"Filename", dataStore.getName()},
793
                        {"Filesize", new Long(dataStore.getFileSize())},
794
                        {"Width", new Integer((int)dataStore.getWidth())},
795
                        {"Height", new Integer((int)dataStore.getHeight())},
796
                        {"Bands", new Integer(dataStore.getBandCount())}
797
                };
798
                for (int i = 0; i < a.length; i++)
799
                        attr.add(a[i]);
800
                return attr;
801
        }
802

    
803

    
804
        /* (non-Javadoc)
805
         * @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)
806
         */
807
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
808
                        double scale, PrintAttributes propeties) throws ReadException {
809

    
810
                if (/*!isOpen() ||*/ !isVisible() || !isWithinScale(scale))
811
                        return;
812

    
813
                if (!mustTilePrint)
814
                        draw(null, g, viewPort, cancel,scale);
815
                else {
816
                        // Para no pedir imagenes demasiado grandes, vamos
817
                        // a hacer lo mismo que hace EcwFile: chunkear.
818
                        // Llamamos a drawView con cuadraditos m?s peque?os
819
                        // del BufferedImage ni caso, cuando se imprime viene con null
820
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
821
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
822

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

    
826
                        //RasterStats stats = getSource().getFilterStack().getStats();
827
                        //if(stats != null)
828
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
829

    
830

    
831
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
832
                                // Parte que dibuja
833
                                try {
834
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
835
                                        draw(null, g, vp, cancel, scale);
836
                                } catch (NoninvertibleTransformException e) {
837
                                        throw new ReadException("Error en la transformaci?n.", e);
838
                                }
839
                }
840
        }
841

    
842
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
843
                        double scale) throws ReadException {
844
                if(!isOpen())
845
                        return;
846

    
847
                // Para no pedir imagenes demasiado grandes, vamos
848
                // a hacer lo mismo que hace EcwFile: chunkear.
849
                // Llamamos a drawView con cuadraditos m?s peque?os
850
                // del BufferedImage ni caso, cuando se imprime viene con null
851

    
852
                int numW, numH;
853
                int stepX, stepY;
854
                int xProv, yProv;
855
                int A = 1500;
856
                int H = 1500;
857
                int altoAux, anchoAux;
858

    
859
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
860

    
861
                // Vamos a hacerlo en trozos de AxH
862
                Rectangle r = g.getClipBounds();
863
                numW = (r.width) / A;
864
                numH = (r.height) / H;
865

    
866
                double[] srcPts = new double[8];
867
                double[] dstPts = new double[8];
868

    
869
                yProv = r.y;
870
                for (stepY = 0; stepY < numH + 1; stepY++) {
871
                        if ((yProv + H) > r.getMaxY())
872
                                altoAux = (int) r.getMaxY() - yProv;
873
                        else
874
                                altoAux = H;
875

    
876
                        xProv = r.x;
877
                        for (stepX = 0; stepX < numW + 1; stepX++) {
878
                                if ((xProv + A) > r.getMaxX())
879
                                        anchoAux = (int) r.getMaxX() - xProv;
880
                                else
881
                                        anchoAux = A;
882

    
883
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
884

    
885
                                // Parte que dibuja
886
                                srcPts[0] = xProv;
887
                                srcPts[1] = yProv;
888
                                srcPts[2] = xProv + anchoAux + 1;
889
                                srcPts[3] = yProv;
890
                                srcPts[4] = xProv + anchoAux + 1;
891
                                srcPts[5] = yProv + altoAux + 1;
892
                                srcPts[6] = xProv;
893
                                srcPts[7] = yProv + altoAux + 1;
894

    
895
                                try {
896
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
897
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
898
                                        // Extent extent = new Extent(rectCuadricula);
899

    
900
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
901
                                        ViewPort vp = (ViewPort)viewPort.clone();
902
                                        vp.setImageSize(tam);
903
                                        Envelope env = geomManager.createEnvelope(rectCuadricula
904
                                                        .getMinX(), rectCuadricula.getMinY(),
905
                                                        rectCuadricula.getMaxX(), rectCuadricula.getMaxY(),
906
                                                        SUBTYPES.GEOM2D);
907
                                        vp.setEnvelope(env);
908
                                        vp.setAffineTransform(mat);
909
                                        draw(null, g, vp, cancel, scale);
910

    
911
                                } catch (NoninvertibleTransformException e) {
912
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
913
                                } catch (ReadException e) {
914
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
915
                                } catch (CreateEnvelopeException e) {
916
                                        logger.error("Error creating the envelope", e);
917
                                } catch (CloneNotSupportedException e) {
918
                                        logger.error("Error cloning the viewport", e);
919
                                }
920
                                // Fin parte que dibuja
921
                                xProv = xProv + A;
922
                        }
923
                        yProv = yProv + H;
924
                }
925
        }
926

    
927
        /**
928
         * Borra de la lista de listeners el que se pasa como par?metro.
929
         *
930
         * @param o LayerListener a borrar.
931
         *
932
         * @return True si ha sido correcto el borrado del Listener.
933
         */
934
        public boolean removeLayerListener(LayerListener o) {
935
                if (this.isRemoveRasterFlag()) {
936
                        try {
937
                                enableClosed();
938
                        } catch (NotAvailableStateException e1) {
939
                                // No se ha podido cambiar el estado de la capa a cerrado
940
                        }
941
                }
942

    
943
                // Salva a RMF
944
                if (dataStore != null)
945
                        // Guardamos la GeoReferenciacion de cada dataset
946
                        try {
947
                                dataStore.saveGeoreferencingToRmf();
948
                        } catch (Exception e) {
949
                                logger.info("error_salvando_rmf", e);
950
                        }
951

    
952
                        if (this.isRemoveRasterFlag()) {
953
                                image = null;
954
                                if (dataStore != null) {
955
                                        String[] files = getFileName().clone();
956

    
957
                                        try {
958
                                                dataStore.close();
959
                                        } catch (CloseException e) {
960
                                        }
961

    
962
                                        dataStore = null;
963
                                        if(render != null)
964
                                                render.dispose();
965
                                        render = null;
966
                                        // System.gc();
967
                                        this.setRemoveRasterFlag(true);
968

    
969
                                        for (int i = 0; i < files.length; i++) {
970
                                                File file = new File(files[i]);
971
                                                File dirTemp = fileUtil.getTemporalFile();
972
                                                if(!file.exists())
973
                                                        continue;
974
                                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
975
                                                        file.delete();
976

    
977
                                                        // Borramos todos los ficheros que puedan tener relacion con el fichero actual
978
                                                        String basefile = file.getName();
979
                                                        File basepath = file.getParentFile();
980
                                                        int last = basefile.lastIndexOf(".");
981
                                                        if (last != -1)
982
                                                                basefile = basefile.substring(0, last + 1);
983
                                                        File[] list = basepath.listFiles();
984
                                                        for (int j = 0; j < list.length; j++)
985
                                                                if (list[j].getName().startsWith(basefile))
986
                                                                        list[j].delete();
987
                                                }
988
                                        }
989
                                }
990
                        }
991
                        updateDrawVersion();
992
                        return super.layerListeners.remove(o);
993
        }
994

    
995
        /*
996
         * (non-Javadoc)
997
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRemoveRasterFlag()
998
         */
999
        public boolean isRemoveRasterFlag() {
1000
                return removeRasterFlag;
1001
        }
1002

    
1003
        /*
1004
         * (non-Javadoc)
1005
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setRemoveRasterFlag(boolean)
1006
         */
1007
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1008
                this.removeRasterFlag = removeRasterFlag;
1009
        }
1010

    
1011
        /*
1012
         * (non-Javadoc)
1013
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1014
         */
1015
        public String getTocImageIcon() {
1016
                return "map-ok-ico";
1017
        }
1018

    
1019
        /*
1020
         * (non-Javadoc)
1021
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getTileSize()
1022
         */
1023
        public int[] getTileSize() {
1024
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1025
                return size;
1026
        }
1027

    
1028
        /*
1029
         * (non-Javadoc)
1030
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isTiled()
1031
         */
1032
        public boolean isTiled() {
1033
                return mustTileDraw;
1034
        }
1035

    
1036
        /*
1037
         * (non-Javadoc)
1038
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isGeoreferenced()
1039
         */
1040
        public boolean isGeoreferenced() {
1041
                return dataStore.isGeoreferenced();
1042
        }
1043

    
1044
        /*
1045
         * (non-Javadoc)
1046
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getNoDataValue()
1047
         */
1048
        public NoData getNoDataValue() {
1049
                return dataStore.getNoDataValue();
1050
        }
1051

    
1052
        /**
1053
         * Sets the nodata value for this layer
1054
         * @param nd
1055
         */
1056
        public void setNoDataValue(NoData nd) {
1057
                if (dataStore != null)
1058
                        dataStore.setNoDataValue(nd);
1059
        }
1060

    
1061
        /*
1062
         * (non-Javadoc)
1063
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getPxHeight()
1064
         */
1065
        public double getPxHeight() {
1066
                return dataStore.getHeight();
1067
        }
1068

    
1069
        /*
1070
         * (non-Javadoc)
1071
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getPxWidth()
1072
         */
1073
        public double getPxWidth() {
1074
                return dataStore.getWidth();
1075
        }
1076

    
1077
        /**
1078
         * Gets the height in world coordinates of this raster layer
1079
         */
1080
        public double getWCHeight() {
1081
                return getFullEnvelope().getMaximum(1);
1082
        }
1083

    
1084
        /**
1085
         * Gets the width in world coordinates of this raster layer
1086
         */
1087
        public double getWCWidth() {
1088
                return getFullEnvelope().getMaximum(0);
1089
        }
1090

    
1091
        /**
1092
         * Gets the size of all files of this raster layer
1093
         */
1094
        public long[] getFileSize() {
1095
                if (dataStore == null)
1096
                        return null;
1097

    
1098
                return dataStore.getFileSizeByProvider();
1099
        }
1100

    
1101
        /**
1102
         * Gets the list of file names
1103
         */
1104
        public String[] getFileName() {
1105
                if (dataStore == null)
1106
                        return null;
1107

    
1108
                return dataStore.getURIByProvider();
1109
        }
1110

    
1111
        /**
1112
         * Returns the number of files in this raster layer
1113
         */
1114
        public int getFileCount() {
1115
                return dataStore.getProviderCount();
1116
        }
1117

    
1118
        /*
1119
         * (non-Javadoc)
1120
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileFormat()
1121
         */
1122
        public String getFileFormat() {
1123
                if(dataStore.getSourceType() == RasterDataStore.FILE) {
1124
                        String fName = dataStore.getName();
1125
                        int index = fName.lastIndexOf(".") + 1;
1126
                        String ext = null;
1127
                        if (index > 0)
1128
                                ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1129
                        return ext;
1130
                }
1131
                if(dataStore.getSourceType() == RasterDataStore.POSTGIS) {
1132
                        return "POSTGIS";
1133
                }
1134
                return null;
1135
        }
1136

    
1137
        /*
1138
         * (non-Javadoc)
1139
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1140
         */
1141
        public int[] getDataType() {
1142
                return dataStore.getDataType();
1143
        }
1144

    
1145
        /**
1146
         * Sets the filter list
1147
         */
1148
        public void setRenderFilterList(RasterFilterList filterList) {
1149
                getRender().setFilterList(filterList);
1150
        }
1151
        
1152
        /*
1153
         * (non-Javadoc)
1154
         * @see org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint#getInfo(java.awt.Point, double, org.gvsig.tools.task.Cancellable, boolean)
1155
         */
1156
        public DynObjectSet getInfo(org.gvsig.fmap.geom.primitive.Point p, double tolerance) throws LoadLayerException, DataException {
1157
                DynObjectSetRasterInfo info = new DynObjectSetRasterInfo();
1158
                
1159
                if (!isOpen()) {
1160
                        info.addField("Layer not open", normalizeAsXMLTag(getName()), 0);
1161
                        return info;
1162
                }
1163
                
1164
                Point2D pReal = new Point2D.Double(p.getX(), p.getY());
1165
                Point2D px = new Point2D.Double();
1166
                if(        pReal.getX() > this.getMinX() &&
1167
                        pReal.getX() < this.getMaxX() &&
1168
                        pReal.getY() > this.getMinY() &&
1169
                        pReal.getY() < this.getMaxY()) {
1170
                        px = transformPoint(pReal);
1171
                }
1172
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
1173
                ColorConversion conv = rManager.getColorConversion();
1174
                info.addField("File", normalizeAsXMLTag(getName()), 0);
1175
                info.addField("View Point", "[" + p.getX() + " , " + p.getY() + "]", 1);
1176
                info.addField("World Point", "[" + mathUtil.format(pReal.getX(), 3) + " , " + mathUtil.format(pReal.getY(), 3) + "]", 2);
1177
                if (px == null)
1178
                        info.addField("Pixel Point", "Out", 3);
1179
                else
1180
                        info.addField("Pixel Point", "[" + (int) px.getX() + ",  " + (int) px.getY() + "]", 3);
1181
                info.addField("RGB", "[" + rgb[1] + ",  " + rgb[2] + ",  " + rgb[3] + "]", 4);
1182
                double[] cmyk = conv.RGBtoCMYK(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff, 1D);
1183
                info.addField("CMYK", "[" + mathUtil.format(cmyk[0], 4) + ",  " + mathUtil.format(cmyk[1], 4) + ",  " + mathUtil.format(cmyk[2], 4) + ",  " + mathUtil.format(cmyk[3], 4) + "]", 5);
1184
                double[] hsl = conv.RGBtoHSL(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff);
1185
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
1186
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
1187
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
1188
                info.addField("HSL", "[" + mathUtil.format(hsl[0], 4) + ",  " + mathUtil.format(hsl[1], 4) + ",  " + mathUtil.format(hsl[2], 4) + "]", 6);
1189
                String data = "[";
1190
                try {
1191
                        if (px != null) {
1192
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3) {
1193
                                        for(int i = 0; i < dataStore.getBandCount(); i++) {
1194
                                                if(dataStore.isInside(pReal)) {
1195
                                                        Point2D pxAux = transformPoint(pReal);
1196
                                                        int val = ((Integer)dataStore.getData((int)pxAux.getX(), 
1197
                                                                        (int)pxAux.getY(), i)).intValue();
1198
                                                        if(getDataType()[0] == Buffer.TYPE_BYTE)
1199
                                                                data += (val & 0x000000ff) + ",  ";
1200
                                                        else
1201
                                                                data += val + ",  ";
1202
                                                }
1203
                                        }
1204
                                }
1205
                                if(getDataType()[0] == 4) {
1206
                                        for(int i = 0; i < dataStore.getBandCount(); i++) {
1207
                                                if(dataStore.isInside(pReal)) {
1208
                                                        Point2D pxAux = transformPoint(pReal);
1209
                                                        data += ((Float)dataStore.getData((int)pxAux.getX(), 
1210
                                                                        (int)pxAux.getY(), i)).floatValue() + ",  ";
1211
                                                }
1212
                                        }
1213
                                }
1214
                                if(getDataType()[0] == 5) {
1215
                                        for(int i = 0; i < dataStore.getBandCount(); i++) {
1216
                                                if(dataStore.isInside(pReal)) {
1217
                                                        Point2D pxAux = transformPoint(pReal);
1218
                                                        data += ((Double)dataStore.getData((int)pxAux.getX(), 
1219
                                                                        (int)pxAux.getY(), i)).doubleValue() + ",  ";
1220
                                                }
1221
                                        }
1222
                                }
1223
                        }
1224
                        data +=  "]";
1225
                        info.addField("Band Value", data, 7);
1226
                } catch (RasterDriverException ex) {
1227
                        throw new LoadLayerException("Error en el acceso al dataset", ex);
1228
                } catch (InvalidSetViewException ex) {
1229
                        throw new LoadLayerException("Error en la asignaci?n de la vista en getData", ex);
1230
                } catch (FileNotOpenException ex) {
1231
                        throw new LoadLayerException("Fichero no abierto en el dataset", ex);
1232
                }
1233
                return info;
1234
        }
1235
        
1236
        /**
1237
         * Transforma un punto real a coordenadas pixel
1238
         * 
1239
         * @param numberBand
1240
         * @param pReal
1241
         * @return
1242
         * @throws LoadLayerException 
1243
         * @throws ReadDriverException
1244
         */
1245
        private Point2D transformPoint(Point2D pReal) throws LoadLayerException {
1246
                AffineTransform at = dataStore.getAffineTransform();
1247
                Point2D px = new Point2D.Double();
1248
                //px = new Point2D.Double(pReal.getX(), pReal.getY());
1249
                try {
1250
                        at.inverseTransform(pReal, px);
1251
                        return px;
1252
                } catch (NoninvertibleTransformException e) {
1253
                        throw new LoadLayerException("Error en la transformaci?n del punto", e);
1254
                }
1255
        }
1256
        
1257
        /*
1258
         * (non-Javadoc)
1259
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1260
         */
1261
        public Object getInfo(String key) {
1262
                if (key.equals("DriverName"))
1263
                        return "gvSIG Raster Driver";
1264
                return null;
1265
        }
1266

    
1267
        /*
1268
         * (non-Javadoc)
1269
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getBandCountFromDataset()
1270
         */
1271
        public int[] getBandCountFromDataset() {
1272
                return dataStore.getBandCountByProvider();
1273
        }
1274

    
1275
        /*
1276
         * (non-Javadoc)
1277
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1278
         */
1279
        public String getColorInterpretation(int band, int dataset) {
1280
                if (this.dataStore.getColorInterpretation().get(band) == null)
1281
                        return "Undefined";
1282
                return this.dataStore.getColorInterpretation().get(band);
1283
        }
1284

    
1285
        /*
1286
         * (non-Javadoc)
1287
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getWktProjection()
1288
         */
1289
        public String getWktProjection() throws RasterDriverException {
1290
                return dataStore.getWktProjection();
1291
        }
1292

    
1293
        /*
1294
         * (non-Javadoc)
1295
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRGB()
1296
         */
1297
        public boolean isRGB() {
1298
                if ((dataStore == null) || (render == null))
1299
                        return false;
1300

    
1301
                if (dataStore.getDataType()[0] != Buffer.TYPE_BYTE)
1302
                        return false;
1303

    
1304
                boolean R = false;
1305
                boolean G = false;
1306
                boolean B = false;
1307

    
1308
                int[] renderBands = render.getRenderBands();
1309
                for (int i = 0; i < renderBands.length; i++)
1310
                        if (renderBands[i] >= 0)
1311
                                switch (i) {
1312
                                        case 0:
1313
                                                R = true;
1314
                                                break;
1315
                                        case 1:
1316
                                                G = true;
1317
                                                break;
1318
                                        case 2:
1319
                                                B = true;
1320
                                                break;
1321
                                }
1322

    
1323
                if (R && G && B)
1324
                        return true;
1325

    
1326
                return false;
1327
        }
1328

    
1329
        /**
1330
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1331
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1332
         * cacheado o no dependiendo del tama?o de esta.
1333
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1334
         * @return Grid.
1335
         * @throws InterruptedException
1336
         */
1337
        public Grid getFullGrid(boolean interpolated) throws GridException, InterruptedException {
1338
                RasterQuery query = rManager.createQuery();
1339
                query.setAllDrawableBands();
1340
                Buffer bf = null;
1341
                try {
1342
                        query.setAreaOfInterest();
1343
                        bf = dataStore.query(query);
1344
                } catch (RasterDriverException e) {
1345
                        throw new GridException("Error reading buffer");
1346
                } catch (ProcessInterruptedException e) {
1347
                        throw new InterruptedException("Carga interrumpida");
1348
                } catch (InvalidSetViewException e) {
1349
                        throw new GridException("Error reading buffer");
1350
                }
1351
                return rManager.createGrid(bf, dataStore, interpolated);
1352
        }
1353

    
1354
        /*
1355
         * (non-Javadoc)
1356
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getReadOnlyFullGrid(boolean)
1357
         */
1358
        public Grid getReadOnlyFullGrid(boolean interpolated) throws GridException, InterruptedException {
1359
                RasterQuery query = rManager.createQuery();
1360
                query.setReadOnly(true);
1361
                query.setAllDrawableBands();
1362
                Buffer bf = null;
1363
                try {
1364
                        query.setAreaOfInterest();
1365
                        bf = dataStore.query(query);
1366
                } catch (RasterDriverException e) {
1367
                        throw new GridException("Error reading buffer");
1368
                } catch (ProcessInterruptedException e) {
1369
                        throw new InterruptedException("Carga interrumpida");
1370
                } catch (InvalidSetViewException e) {
1371
                        throw new GridException("Error reading buffer");
1372
                }
1373
                return rManager.createGrid(bf, dataStore, interpolated);
1374
        }
1375

    
1376
        /**
1377
         * Obtiene el tama?o de celda de la fuente de datos
1378
         * @return double con el tama?o de celda
1379
         */
1380
        public double getCellSize() {
1381
                return (dataStore != null) ? dataStore.getCellSize() : 1;
1382
        }
1383

    
1384
        /*
1385
         * (non-Javadoc)
1386
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFullRasterExtent()
1387
         */
1388
        public Extent getFullRasterExtent() {
1389
                return this.dataStore.getExtent();
1390
        }
1391

    
1392

    
1393
        /**
1394
         * Devuelve el fichero asociado a la capa o null si no tiene.
1395
         * @return Fichero.
1396
         */
1397
        public File getFile() {
1398
                if(getDataStore().getParameters() instanceof RasterFileStoreParameters)
1399
                        return ((RasterFileStoreParameters)getDataStore().getParameters()).getFile();
1400
                return new File("");
1401
        }
1402

    
1403
        /**
1404
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1405
         * @param file Fichero a consultar
1406
         * @return true si es aceptado y false si no lo es.
1407
         */
1408
        public boolean isFileAccepted(File file) {
1409
                return dataStore.isFileSupported(file.getName());
1410
        }
1411
        
1412
        /**
1413
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1414
         * @param file Fichero a consultar
1415
         * @return true si es aceptado y false si no lo es.
1416
         */
1417
        public static boolean isFileSupported(File file) {
1418
                return RasterLocator.getManager().isExtensionSupported(file.getName());
1419
        }
1420

    
1421
        /*
1422
         * (non-Javadoc)
1423
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#existColorTable()
1424
         */
1425
        public boolean existColorTable() {
1426
                return getRender().existColorTable();
1427
        }
1428

    
1429
        /**
1430
         * Returns true if the data store has an alpha band
1431
         */
1432
        public boolean existsAlphaBand() {
1433
                if(dataStore.getColorInterpretation() != null)
1434
                        return dataStore.getColorInterpretation().hasAlphaBand();
1435
                else
1436
                        return false;
1437
        }
1438

    
1439
        /*
1440
         * (non-Javadoc)
1441
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAlphaBandNumber()
1442
         */
1443
        public int getAlphaBandNumber() {
1444
                if(dataStore.getColorInterpretation() != null)
1445
                        return dataStore.getColorInterpretation().getBand(ColorInterpretation.ALPHA_BAND);
1446
                return -1;
1447
        }
1448

    
1449
        /**
1450
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1451
         * capa busque una leyenda valida.
1452
         * @param ct
1453
         */
1454
        public void setLastLegend(ColorTable ct) {
1455
                lastLegend = ColorTableLegend.createLegend(ct);
1456
        }
1457

    
1458
        /**
1459
         * Devuelve la Leyenda de la capa.
1460
         * @return Leyenda.
1461
         */
1462
        public ILegend getLegend() {
1463
                if (lastLegend != null)
1464
                        return lastLegend;
1465

    
1466
                return null;
1467
        }
1468

    
1469
        /*
1470
         * (non-Javadoc)
1471
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1472
         */
1473
        public void addLegendListener(LegendListener listener) {
1474
                layerChangeSupport.addLayerListener(listener);
1475
        }
1476

    
1477
        /*
1478
         *  (non-Javadoc)
1479
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1480
         */
1481
        public int getShapeType() {
1482
                return TYPES.SURFACE;
1483
        }
1484

    
1485
        /*
1486
         * (non-Javadoc)
1487
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1488
         */
1489
        public void removeLegendListener(LegendListener listener) {
1490
                if(layerChangeSupport != null)
1491
                        layerChangeSupport.removeLayerListener(listener);
1492
        }
1493

    
1494
        /*
1495
         * (non-Javadoc)
1496
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isInside(java.awt.geom.Point2D)
1497
         */
1498
        public boolean isInside(Point2D p) {
1499
                 return dataStore.isInside(p);
1500
        }
1501

    
1502
        /*
1503
         * (non-Javadoc)
1504
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAffineTransform()
1505
         */
1506
        public AffineTransform getAffineTransform() {
1507
                return dataStore.getAffineTransform();
1508
        }
1509

    
1510
        /*
1511
         * (non-Javadoc)
1512
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setAffineTransform(java.awt.geom.AffineTransform)
1513
         */
1514
        public void setAffineTransform(AffineTransform transf) {
1515
                if(transf == null)
1516
                        return;
1517
                affineTransformList.add(transf);
1518
                dataStore.setAffineTransform(transf);
1519
                updateDrawVersion();
1520
        }
1521

    
1522
        /*
1523
         * (non-Javadoc)
1524
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setAffineTransformWithoutHistorical(java.awt.geom.AffineTransform)
1525
         */
1526
        public void setAffineTransformWithoutHistorical(AffineTransform transf) {
1527
                dataStore.setAffineTransform(transf);
1528
                updateDrawVersion();
1529
        }
1530

    
1531
        /*
1532
         * (non-Javadoc)
1533
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAffineTransformHistorical()
1534
         */
1535
        public Historical getAffineTransformHistorical() {
1536
                return this.affineTransformList;
1537
        }
1538

    
1539
        /*
1540
         * (non-Javadoc)
1541
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#saveGeoToRmf()
1542
         */
1543
        public void saveGeoToRmf() throws RmfSerializerException {
1544
                if (!isOpen())
1545
                        return;
1546

    
1547
                dataStore.saveGeoreferencingToRmf();
1548
                
1549
                affineTransformList.clear();
1550
                affineTransformList.add(this.getAffineTransform());
1551
        }
1552

    
1553
        /*
1554
         * (non-Javadoc)
1555
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1556
         */
1557
        public boolean isActionEnabled(int action) {
1558
                switch (action) {
1559
                        case IRasterLayerActions.BANDS_FILE_LIST:
1560
                                if (existColorTable() || getDataStore().isMosaic() || getDataStore().isTiled())
1561
                                        return false;
1562
                                break;
1563
                        case IRasterLayerActions.BANDS_RGB:
1564
                                if (existColorTable())
1565
                                        return false;
1566
                                break;
1567
                        case IRasterLayerActions.REPROJECT:
1568
                                if (!isReproyectable())
1569
                                        return false;
1570
                                break;
1571
                        case IRasterLayerActions.CREATEOVERVIEWS:
1572
                                return overviewsSupport();
1573
                        case IRasterLayerActions.OPACITY:
1574
                        case IRasterLayerActions.TRANSPARENCY:
1575
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1576
                        case IRasterLayerActions.ENHANCED:
1577
                        case IRasterLayerActions.PANSHARPENING:
1578
                        case IRasterLayerActions.SELECT_LAYER:
1579
                        case IRasterLayerActions.SAVE_COLORINTERP:
1580
                                return true;
1581
                        case IRasterLayerActions.REMOTE_ACTIONS:
1582
                                return false;
1583
                        case IRasterLayerActions.TAILTRIM:
1584
                        case IRasterLayerActions.GEOLOCATION:
1585
                                return !(dataStore.isTiled());
1586
                }
1587
                return true;
1588
        }
1589

    
1590
        /*
1591
         * (non-Javadoc)
1592
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1593
         */
1594
        public void setVisible(boolean visibility) {
1595
                if(visibility)
1596
                        state.disableStopped();
1597
                else
1598
                        enableStopped();
1599

    
1600
                if(isAwake() || isClosed())
1601
                        try {
1602
                                this.load();
1603
                        } catch (LoadLayerException e) {
1604
                                e.printStackTrace();
1605
                        }
1606

    
1607
                /*
1608
                 * Cuando se modifica la visibilidad de una capa raster se hace un updateDrawVersion de todas las
1609
                 * capas raster de ese MapContext. Esto es porque la estrategia utilizada por RasterDrawStrategy hace
1610
                 * que se cacheen en blanco las capas raster que est?n ocultas debajo de otras. Al hacer invisibles las
1611
                 * de arriba la cache que estaba en blanco hace que no se pinte nada. Para evitar esto las marcamos todas
1612
                 * como que han sido modificadas para que se vuelvan a leer.
1613
                 */
1614
                if(getMapContext() != null) {
1615
                        ArrayList<FLayer> listLayers = new ArrayList<FLayer>();
1616
                        listLayers = RasterDrawStrategy.getLayerList(getMapContext().getLayers(), listLayers);
1617
                        for (int i = 0; i < listLayers.size(); i++)
1618
                                if(listLayers.get(i) instanceof DefaultFLyrRaster)
1619
                                        ((DefaultFLyrRaster)listLayers.get(i)).updateDrawVersion();
1620
                }
1621

    
1622
                super.setVisible(visibility);
1623
        }
1624

    
1625
        /**
1626
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1627
         * @return valor de transparencia
1628
         */
1629
        public int getTransparency() {
1630
                try {
1631
                        return getRender().getLastTransparency().getOpacity();
1632
                } catch (NullPointerException e) {
1633
                        return super.getTransparency();
1634
                }
1635
        }
1636

    
1637
        /**
1638
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1639
         * o no.
1640
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1641
         */
1642
        public boolean isTransparent() {
1643
                return getRender().getLastTransparency().isTransparencyActive();
1644
        }
1645

    
1646
        /**
1647
         * Asigna la transparencia de la siguiente renderizaci?n
1648
         * @param valor de transparencia
1649
         */
1650
        public void setTransparency(int trans) {
1651
                super.setTransparency(trans);
1652
                try {
1653
                        getRender().getLastTransparency().setOpacity(trans);
1654
                } catch (NullPointerException e) {
1655
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1656
                }
1657
        }
1658

    
1659
        /**
1660
         * Gets the last buffer which was rendered
1661
         */
1662
        public Buffer getLastRenderBuffer() {
1663
                return getRender().getLastRenderBuffer();
1664
        }
1665

    
1666
        /**
1667
         *
1668
         * @return ROIs asociadas a la capa raster.
1669
         */
1670
        public ArrayList<ROI> getRois() {
1671
                return rois;
1672
        }
1673

    
1674
        /**
1675
         * Establece las ROI asociadas a la capa raster.
1676
         *
1677
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1678
         */
1679
        public void setRois(ArrayList<ROI> rois) {
1680
                this.rois = rois;
1681
        }
1682

    
1683
        /**
1684
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1685
         * devolver? null.
1686
         * @return TreeMap con la lista de capas a dibujar
1687
         */
1688
        public HashMap<DefaultFLyrRaster, Boolean> getRasterStrategy() {
1689
                if(strategy != null)
1690
                        return strategy.getStrategy();
1691
                return null;
1692
        }
1693

    
1694
        /**
1695
         * @return the configuration
1696
         */
1697
        static public IConfiguration getConfiguration() {
1698
                return configuration;
1699
        }
1700

    
1701
        /**
1702
         * @param configuration the configuration to set
1703
         */
1704
        static public void setConfiguration(IConfiguration configuration) {
1705
                DefaultFLyrRaster.configuration = configuration;
1706
        }
1707

    
1708
        /*
1709
         * (non-Javadoc)
1710
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#reload()
1711
         */
1712
        public void reload() throws ReloadLayerException {
1713
                try {
1714
                        super.reload();
1715
                        if (getMapContext() == null)
1716
                                return;
1717
                        if (isStopped())
1718
                                disableStopped();
1719
                        load();
1720
                        getMapContext().invalidate();
1721
                } catch (LoadLayerException e) {
1722
                        setAvailable(false);
1723
                        throw new ReloadLayerException(getName(), e);
1724
                }
1725
        }
1726

    
1727
        /**
1728
         * Devuelve si la capa tiene soporte para poder generar overviews
1729
         * @return
1730
         */
1731
        public boolean overviewsSupport() {
1732
                if ((dataStore != null) && (dataStore.overviewsSupport()))
1733
                        return true;
1734

    
1735
                return false;
1736
        }
1737

    
1738
        /**
1739
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1740
         * en escala de grises
1741
         * @return
1742
         */
1743
        public boolean isRenderingAsGray() {
1744
                int[] renderBands = getRender().getRenderBands();
1745
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1746
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1747
                        return true;
1748
                return false;
1749
        }
1750

    
1751
        /*
1752
         * (non-Javadoc)
1753
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
1754
         */
1755
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1756
                updateDrawVersion();
1757
        }
1758

    
1759
        /*
1760
         * (non-Javadoc)
1761
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#adjustWorldRequest(java.awt.geom.Point2D)
1762
         */
1763
        public Point2D adjustWorldRequest(Point2D req) {
1764
                Envelope ext = null;
1765

    
1766
                ext = getFullEnvelope();
1767
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
1768
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
1769
                return req;
1770
        }
1771

    
1772
        /*
1773
         * (non-Javadoc)
1774
         * @see org.gvsig.fmap.mapcontext.layers.FLyrDefault#cloneLayer()
1775
         */
1776
        public FLayer cloneLayer() throws Exception {
1777
                RasterDataStore  ds = dataStore.cloneDataStore();
1778
                DefaultFLyrRaster newLayer = new DefaultFLyrRaster();
1779
                newLayer.setName(getName());
1780
                newLayer.setOpenRasterStore(ds);
1781
                newLayer.firstLoad = firstLoad;
1782
                
1783
                ArrayList<RasterFilter> filters = getRender().getFilterList().getStatusCloned();
1784

    
1785
                //Hacemos una copia de las bandas a renderizar
1786
                if(getRender().getRenderBands() != null) {
1787
                        int[] rb = new int[getRender().getRenderBands().length];
1788
                        for (int i = 0; i < rb.length; i++)
1789
                                rb[i] = getRender().getRenderBands()[i];
1790
                        newLayer.getRender().setRenderBands(rb);
1791
                }
1792

    
1793
                //Asignamos el entorno
1794
                if(newLayer.getRender().getFilterList() == null)
1795
                        newLayer.getRender().setFilterList(RasterLocator.getManager().createEmptyFilterList(getRender().getFilterList().getInitDataType()));
1796
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
1797
                newLayer.getRender().getFilterList().setStatus(filters);
1798

    
1799
                // Asignamos los valores noData del original
1800
                newLayer.setNoDataValue(getNoDataValue());
1801
                if(dataStore.getNoDataValue().isDefined())
1802
                        newLayer.setNoDataTransparent(true);
1803
                newLayer.enableOpen();
1804
                
1805
                return newLayer;
1806
        }
1807
        
1808
        /*
1809
         * (non-Javadoc)
1810
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileLayer()
1811
         */
1812
        public FLayer getFileLayer() throws RasterDriverException {
1813
                try {
1814
                        return cloneLayer();
1815
                } catch (Exception e) {
1816
                }
1817
                return null;
1818
        }
1819
        
1820
        /*
1821
         * (non-Javadoc)
1822
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#addFile(java.lang.String)
1823
         */
1824
        public void addFile(String file) throws InvalidSourceException {
1825
                getDataStore().addFile(file);
1826
        }
1827
        
1828
        /*
1829
         * (non-Javadoc)
1830
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#removeFile(java.lang.String)
1831
         */
1832
        public void removeFile(String file) {
1833
                getDataStore().removeFile(file);
1834
        }
1835

    
1836
        /*****************************************************/
1837

    
1838
        public void disableStopped() {state.disableStopped();}
1839

    
1840
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1841

    
1842
        public void enableClosed() throws NotAvailableStateException {
1843
                if(state != null)
1844
                        state.enableClosed();
1845
        }
1846

    
1847
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1848

    
1849
        public void enableStopped() {state.enableStopped();}
1850

    
1851
        public boolean isAwake() {return state.isAwake();}
1852

    
1853
        public boolean isClosed() {return state.isClosed();}
1854

    
1855
        public boolean isOpen() {return state.isOpen();}
1856

    
1857
        public boolean isStopped() {return state.isStopped();}
1858

    
1859

    
1860
        @SuppressWarnings("unchecked")
1861
        public Set getMetadataChildren() {
1862
                return null;
1863
        }
1864

    
1865
        public Object getMetadataID() {
1866
                return getName();
1867
        }
1868

    
1869
        public String getMetadataName() {
1870
                return null;
1871
        }
1872

    
1873
        /*
1874
         * (non-Javadoc)
1875
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getDataStore()
1876
         */
1877
        public RasterDataStore getDataStore() {
1878
                return this.dataStore;
1879
        }
1880

    
1881
        public void setOpenRasterStore(DataStore dataStore) throws LoadLayerException {
1882
                if(dataStore instanceof CoverageStoreProviderServices) {
1883
                        try {
1884
                                this.dataStore = rManager.open(((CoverageStoreProviderServices) dataStore).getProvider(), dataStore.getParameters());
1885
                        } catch (NotSupportedExtensionException e) {
1886
                                throw new LoadLayerException("Extension not supported", e);
1887
                        } catch (RasterDriverException e) {
1888
                                throw new LoadLayerException("Error opening the DataStore", e);
1889
                        }
1890
                } else
1891
                        this.dataStore = (RasterDataStore) dataStore;
1892
                try {
1893
                        enableAwake();
1894
                } catch (NotAvailableStateException e) {
1895
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
1896
                }
1897
                setProjection(this.dataStore.getProjection());
1898
        }
1899
        
1900
        /*
1901
         * (non-Javadoc)
1902
         * @see org.gvsig.fmap.mapcontext.layers.operations.SingleLayer#setDataStore(org.gvsig.fmap.dal.DataStore)
1903
         */
1904
        public void setDataStore(DataStore dataStore) throws LoadLayerException {
1905
                setOpenRasterStore(dataStore);
1906
                load();
1907
        }
1908
        
1909
        /*
1910
         * (non-Javadoc)
1911
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRemote()
1912
         */
1913
        public boolean isRemote() {
1914
                return false;
1915
        }
1916
        
1917
        /**
1918
         * Returns true if exists a process reading data from this layer
1919
         * @return
1920
         */
1921
        public boolean isReadingData() {
1922
                return readingData != null;
1923
        }
1924

    
1925
        /**
1926
         * When a process is using information of this layer this variable will contain
1927
         * the thread ID.
1928
         * @param readingData
1929
         */
1930
        public synchronized void setReadingData(String readingData) {
1931
                this.readingData = readingData;
1932
        }
1933
        
1934
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel,
1935
                        boolean fast)
1936
                        throws LoadLayerException, DataException {
1937
                return null;
1938
        }
1939

    
1940
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel)
1941
                        throws LoadLayerException, DataException {
1942
                return null;
1943
        }
1944

    
1945
        @Override
1946
        protected void doDispose() throws BaseException {
1947
                if(render != null)
1948
                        render.dispose();
1949
                if(dataStore != null)
1950
                        dataStore.dispose();
1951
                finalize();
1952
        }
1953

    
1954
        /*
1955
         * (non-Javadoc)
1956
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#getZoomLevel()
1957
         */
1958
        public int getZoomLevel() {
1959
                return zoomLevel;
1960
        }
1961

    
1962
        /*
1963
         * (non-Javadoc)
1964
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#setZoomLevel(int)
1965
         */
1966
        public void setZoomLevel(int zoomLevel) {
1967
                this.zoomLevel = zoomLevel;
1968
        }
1969
        
1970
        /*
1971
         * (non-Javadoc)
1972
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#increaseZoomLevel()
1973
         */
1974
        public boolean increaseZoomLevel() {
1975
                if(zoomLevel < (this.dataStore.getZoomLevels() - 1)) { 
1976
                        zoomLevel ++;
1977
                        recalcLevel = false;
1978
                        return true;
1979
                }
1980
                return false;
1981
        }
1982
        
1983
        /*
1984
         * (non-Javadoc)
1985
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#decreaseZoomLevel()
1986
         */
1987
        public boolean decreaseZoomLevel() {
1988
                if(zoomLevel > 0) { 
1989
                        zoomLevel --;
1990
                        recalcLevel = false;
1991
                        return true;
1992
                }
1993
                return false;
1994
        }
1995
        
1996
        /*
1997
         * (non-Javadoc)
1998
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#getCoordsInLevel(java.awt.geom.Point2D, int, int, int)
1999
         */
2000
        public Envelope getCoordsInLevel(Point2D center, int level, int w, int h) throws CreateEnvelopeException {
2001
                Extent ex = getDataStore().getCoordsInLevel(center, level, w, h);
2002
                return geomManager.createEnvelope(ex.getULX(), ex.getULY(), ex.getLRX(), ex.getLRY(), SUBTYPES.GEOM2D);
2003
        }
2004
        
2005
        /*
2006
         * (non-Javadoc)
2007
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#isEnabledMultiresolution()
2008
         */
2009
        public boolean isEnabledMultiresolution() {
2010
                return dataStore.isTiled();
2011
        }
2012
        
2013
        /*
2014
         * (non-Javadoc)
2015
         * @see org.gvsig.raster.fmap.layers.Multiresolution#setTileServer(java.lang.Class)
2016
         */
2017
        public void setTileServer(Class<?> tileServer) {
2018
                dataStore.setTileServer(tileServer);
2019
        }
2020
        
2021
        @SuppressWarnings("unchecked")
2022
        @Override
2023
        public void loadFromState(PersistentState state)
2024
                        throws PersistenceException {
2025
                super.loadFromState(state);
2026
                
2027
                //this.status = (IStatusRaster)state.get("status");
2028
                List<ROI> rois = state.getList("rois");
2029
                if(rois != null) {
2030
                        this.rois = new ArrayList<ROI>();
2031
                        this.rois.addAll(rois);
2032
                }
2033
                this.zoomLevel = state.getInt("zoomLevel");
2034
                this.recalcLevel = state.getBoolean("recalcLevel");
2035
                if(this.dataStore == null)
2036
                        this.dataStore = (RasterDataStore)state.get("rasterdatastore");
2037
                this.lastLegend = (ILegend)state.get("legend");
2038
                this.colorTableLoadedFromProject = (ColorTable)state.get("colortable");
2039
                this.zoomLevel = state.getInt("zoomLevel");
2040
                this.recalcLevel = state.getBoolean("recalcLevel");
2041
                loadedFromProject = true;
2042
        }
2043

    
2044
        @Override
2045
        public void saveToState(PersistentState state) throws PersistenceException {
2046
                super.saveToState(state);
2047
                
2048
                //state.set("status", status);
2049
                state.set("rasterdatastore", dataStore);        
2050
                state.set("legend", lastLegend);        
2051
                state.set("rois", rois);        
2052
                state.set("colortable", getRender().getColorTable());        
2053
                state.set("zoomLevel", zoomLevel);        
2054
                state.set("recalcLevel", recalcLevel);        
2055
        }        
2056
        
2057
        public static void registerPersistence() {
2058
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
2059
                DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
2060
                if( definition == null ) {
2061
                        if (manager.getDefinition(FLyrDefault.class) == null) {
2062
                                FLyrDefault.registerPersistent();
2063
                        }
2064
                        definition = manager.addDefinition(
2065
                                        DefaultFLyrRaster.class,
2066
                                        PERSISTENT_NAME,
2067
                                        PERSISTENT_DESCRIPTION,
2068
                                        null, 
2069
                                        null
2070
                        );
2071
                        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE, "FLyrDefault");
2072
                        
2073
                        registerPersistence(definition);
2074
                }
2075
        }
2076
        
2077
        public static void registerPersistence(DynStruct definition) {
2078
                //definition.addDynFieldObject("status").setClassOfValue(StatusLayerRaster.class).setMandatory(false);
2079
                definition.addDynFieldObject("rasterdatastore").setClassOfValue(RasterDataStore.class).setMandatory(true);
2080
                definition.addDynFieldObject("legend").setClassOfValue(ILegend.class).setMandatory(false);
2081
                definition.addDynFieldList("rois").setClassOfItems(ROI.class).setMandatory(false);
2082
                definition.addDynFieldObject("colortable").setClassOfValue(ColorTable.class).setMandatory(false);
2083
                definition.addDynFieldInt("zoomlevel").setMandatory(false);
2084
                definition.addDynFieldBoolean("recalcLevel").setMandatory(false);
2085
        }
2086

    
2087
        /*
2088
         * (non-Javadoc)
2089
         * @see org.gvsig.fmap.mapcontext.layers.operations.Classifiable#getGeometryType()
2090
         */
2091
        public GeometryType getGeometryType() throws ReadException {
2092
                try {
2093
                        return GeometryLocator.getGeometryManager().getGeometryType(TYPES.SURFACE, SUBTYPES.GEOM2D);
2094
                } catch (GeometryTypeNotSupportedException e) {
2095
                        throw new ReadException(getDataStore().getName(), e);
2096
                } catch (GeometryTypeNotValidException e) {
2097
                        throw new ReadException(getDataStore().getName(), e);
2098
                } 
2099
        }
2100
        
2101
        /*
2102
         * (non-Javadoc)
2103
         * @see java.lang.Object#finalize()
2104
         */
2105
        protected void finalize() {
2106
                layerChangeSupport             = null;
2107
                state                          = null;
2108
                lastLegend                     = null;
2109
                colorTableLoadedFromProject    = null;
2110
                if(rois != null) {
2111
                        rois.clear();
2112
                        rois = null;
2113
                }
2114
                strategy                       = null;
2115
                configuration                  = null;
2116
                image                          = null;
2117
                fileUtil                       = null;
2118
                rasterUtil                     = null;
2119
                crsUtil                        = null;
2120
                mathUtil                       = null;
2121
                uri                            = null;
2122
                affineTransformList            = null;
2123
                readingData                    = null;
2124
                dataStore                      = null;
2125
                render                         = null;
2126
        }
2127

    
2128
        public void setDataStore(DataStore dataStore, String domain)
2129
                        throws LoadLayerException {
2130
                setDataStore(dataStore);
2131
        }
2132

    
2133
}