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

History | View | Annotate | Download (66.5 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 = configuration.getValueString("loadlayer_usecolortable", (String) null);
457

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

    
463
                Statistics stats = dataStore.getStatistics();
464
                ColorTableLibrary colorTableLibrary = rManager.getDataStructFactory().getColorTableLibrary();
465

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

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

    
483
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
484

    
485
                                                        setLastLegend(colorTable);
486

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

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

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

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

    
546
                try {
547
                        if (!isOpen())
548
                                return;
549

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
801

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

    
808
                if (/*!isOpen() ||*/ !isVisible() || !isWithinScale(scale))
809
                        return;
810

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

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

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

    
828

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

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

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

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

    
857
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
858

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

    
864
                double[] srcPts = new double[8];
865
                double[] dstPts = new double[8];
866

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

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

    
881
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
882

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

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

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

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

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

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

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

    
955
                                        try {
956
                                                dataStore.close();
957
                                        } catch (CloseException e) {
958
                                        }
959

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1096
                return dataStore.getFileSizeByProvider();
1097
        }
1098

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

    
1106
                return dataStore.getURIByProvider();
1107
        }
1108

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

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

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

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

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

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

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

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

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

    
1302
                boolean R = false;
1303
                boolean G = false;
1304
                boolean B = false;
1305

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

    
1321
                if (R && G && B)
1322
                        return true;
1323

    
1324
                return false;
1325
        }
1326

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

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

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

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

    
1390

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

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

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

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

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

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

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

    
1464
                return null;
1465
        }
1466

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1620
                super.setVisible(visibility);
1621
        }
1622

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

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

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

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

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

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

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

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

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

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

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

    
1733
                return false;
1734
        }
1735

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

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

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

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

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

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

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

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

    
1834
        /*****************************************************/
1835

    
1836
        public void disableStopped() {state.disableStopped();}
1837

    
1838
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1839

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

    
1845
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1846

    
1847
        public void enableStopped() {state.enableStopped();}
1848

    
1849
        public boolean isAwake() {return state.isAwake();}
1850

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

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

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

    
1857

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

    
1863
        public Object getMetadataID() {
1864
                return getName();
1865
        }
1866

    
1867
        public String getMetadataName() {
1868
                return null;
1869
        }
1870

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

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

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

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

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

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

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

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

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

    
2126
}