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

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

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

    
185
        /**
186
         * Lista de transformaciones afines que son aplicadas. Esta lista es
187
         * simplemente un historico que no se utiliza. Es posible utilizarlo para
188
         * recuperar transformaciones anteriores.
189
         */
190
        private Historical              affineTransformList    = null;
191
        protected String                readingData            = null;
192
        //It is set to true if the method init has been called at least once
193
        protected boolean               layerInitialize        = false;
194

    
195
        public DefaultFLyrRaster() {
196
                affineTransformList = rManager.createHistoricalService();
197
        }
198
        
199
        public static void registerDynClass() {
200
                DynObjectManager manager = ToolsLocator.getDynObjectManager();
201
            DynClass dynClass = manager.add("RasterInfo", "Raster layer Info by point");
202
            dynClass.setNamespace("InfoByPoint");
203
            dynClass.addDynFieldString("File");
204
            dynClass.addDynFieldString("View Point");
205
            dynClass.addDynFieldString("Pixel Point");
206
            dynClass.addDynFieldString("RGB");
207
            dynClass.addDynFieldString("CMYK");
208
            dynClass.addDynFieldString("HSL");
209
            dynClass.addDynFieldString("Band Value");
210
            dynClass.addDynFieldString("World Point");
211
        }
212
        
213
        /**
214
         * Builds a new raster layer
215
         * @param fileName
216
         * @return
217
         * @throws RasterNotLoadException 
218
         * @throws LoadLayerException 
219
         */
220
        public static DefaultFLyrRaster createLayer(String layerName, File file) throws LoadLayerException {
221
                ProviderServices provServ = RasterLocator.getManager().getProviderServices();
222
                RasterDataParameters storeParameters = provServ.createParameters(file.getName());
223
                storeParameters.setURI(file.getPath());
224
                
225
                DataManager dataManager = DALLocator.getDataManager();
226
                DataStore dataStore = null;
227
                try {
228
                        dataStore = dataManager.createStore(storeParameters);
229
                } catch (ValidateDataParametersException e) {
230
                        throw new LoadLayerException("Error al cargar la capa.");
231
                } catch (InitializeException e) {
232
                        throw new LoadLayerException("Error al cargar la capa.");
233
                } catch (ProviderNotRegisteredException e) {
234
                        throw new LoadLayerException("Error al cargar la capa.");
235
                }
236
                
237
                DefaultFLyrRaster lyr = new DefaultFLyrRaster();
238
                lyr.setName(layerName);
239
                lyr.setDataStore(dataStore);
240
                return lyr;
241
        }
242

    
243
        /*
244
         * (non-Javadoc)
245
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setName(java.lang.String)
246
         */
247
        public void setName(String name) {
248
                super.setName(name);
249

    
250
                //Si la capa tiene nombre acivamos el estado awake
251
                if(name != null)
252
                        try {
253
                                if(isClosed())
254
                                        enableAwake();
255
                        } catch (NotAvailableStateException e) {
256
                                logger.error("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
257
                        }
258
        }
259

    
260
        /*
261
         * (non-Javadoc)
262
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#wakeUp()
263
         */
264
        public void wakeUp(){
265
                try {
266
                        reload();
267
                } catch (ReloadLayerException e) {
268
                        // No se ha podido recuperar la capa con exito
269
                }
270
        }
271

    
272
        /*
273
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
274
         */
275
        public void load() throws LoadLayerException {
276
                if (isStopped() || getDataStore() == null)
277
                        return;
278

    
279
                enableStopped(); // Paramos la capa mientras se hace un load
280

    
281
                int test = -1;
282
                DataStoreParameters params = getDataStore().getParameters();
283
                DataStoreParameters p = params;
284
                if (params != null) {
285
                        if(params instanceof TileDataParameters) {
286
                                uri = ((RasterDataParameters)params).getURI();
287
                                if(uri == null)
288
                                        p = (DataStoreParameters)((TileDataParameters)params).getDataParameters();
289
                        }
290
                        if(uri == null) {
291
                                if(params instanceof RasterDataParameters)
292
                                        uri = ((RasterDataParameters)p).getURI();
293
                        }
294
                        test = uri.indexOf("ecwp:");
295
                }
296

    
297
                if (test != -1) {
298
                        String urlECW = uri.substring(test + 6);
299
                        uri = "ecwp://" + urlECW;
300
                        System.err.println(test + " " + uri);
301
                }
302

    
303
                try {
304
                        if(!dataStore.isOpen())
305
                                dataStore = rManager.open(params);
306
                } catch (NotSupportedExtensionException e) {
307
                        throw new LoadLayerException(this.getName());
308
                } catch (RasterDriverException e) {
309
                        throw new LoadLayerException(this.getName());
310
                }
311
                
312
                /*if (dataStore != null)
313
                        try {
314
                                this.init();
315
                        } catch (FilePaletteException e) {
316
                                throw new LoadLayerException("", e);
317
                        }*/
318
        }
319

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

    
333
                render = dataStore.getRender();
334
                render.addVisualPropertyListener(this);
335
                initFilters();
336

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

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

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

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

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

    
401
        /**
402
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
403
         * @throws FilePaletteException 
404
         */
405
        protected void initFilters() throws FilePaletteException {
406
                if(getDataType() == null)
407
                        return;
408
                        
409
                RasterFilterList filterList = rManager.createEmptyFilterList(getDataType()[0]);
410
                if(loadedFromProject) {
411
                        filterList = getDataStore().getRender().getFilterList();
412
                }
413
                filterList.addEnvParam("IStatistics", dataStore.getStatistics());
414
                filterList.addEnvParam("MultiRasterDataset", dataStore);
415

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

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

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

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

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

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

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

    
483
                Statistics stats = dataStore.getStatistics();
484
                ColorTableLibrary colorTableLibrary = rManager.getDataStructFactory().getColorTableLibrary();
485

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

    
498
                                                        ColorTable colorTable = colorTableLibrary.createColorTable();
499
                                                        colorTable.setName(paletteName);
500
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
501
                                                        colorTable.setInterpolated(true);
502

    
503
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
504

    
505
                                                        setLastLegend(colorTable);
506

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

    
523
                        RasterFilterListManager enhancementManager = filterList.getManagerByID("EnhancementStretch");
524
                        Params params = filterList.createEmptyFilterParams();
525
                        params.setParam("stats", stats);
526
                        params.setParam("remove", new Boolean(false));
527
                        params.setParam("renderBands", getRender().getRenderBands());
528
                        params.setParam("stretchs", null);//coge el LinearStretchParams por defecto
529
                        params.setParam("rgb", new Boolean(true));
530
                        enhancementManager.addFilter(params);
531
        }
532

    
533
        /*
534
         * (non-Javadoc)
535
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isReproyectable()
536
         */
537
        public boolean isReproyectable() {
538
                if (dataStore == null)
539
                        return false;
540
                return dataStore.isReproyectable();
541
        }
542

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

    
566
                try {
567
                        if (!isOpen())
568
                                return;
569

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

    
581
                        strategy = new RasterDrawStrategy(getMapContext(), this);
582
                        strategy.stackStrategy();
583
                        HashMap<DefaultFLyrRaster, Boolean> tStr = strategy.getStrategy();
584
                        if (tStr != null &&
585
                                tStr.get(this) != null &&
586
                                ((Boolean) (tStr.get(this))).booleanValue() == false) {
587
                                disableStopped();
588
                                return;
589
                        }
590

    
591
                        if (isWithinScale(scale)) {
592
                                /*if (status != null && firstLoad) {
593
                                        if (mustTileDraw) {
594
                                                Point2D p = vp.getOffset();
595
                                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
596
                                                Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
597
                                                tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
598
                                                for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
599
                                                        // drawing part
600
                                                        try {
601
                                                                ViewPort vport = tiles.getTileViewPort(vp, tileNr);
602
//                                                                g.setClip(tiles.getClip(tileNr).x, tiles.getClip(tileNr).y, tiles.getClip(tileNr).width - 5, tiles.getClip(tileNr).height);
603
                                                                draw(image, g, vport, cancel);
604
                                                        } catch (InterruptedException e) {
605
                                                                System.out.println("Se ha cancelado el pintado");
606
                                                        } catch (InvalidSetViewException e) {
607
                                                                throw new ReadException("Error reading file.", e);
608
                                                        } catch (RasterDriverException e) {
609
                                                                throw new ReadException("Error reading file.", e);
610
                                                        }  catch (NoninvertibleTransformException e) {
611
                                                                throw new ReadException("Error in the transformation.", e);
612
                                                        }
613
                                        } else
614
                                                try {
615
                                                        draw(image, g, vp, cancel);
616
                                                } catch (InterruptedException e) {
617
                                                        System.out.println("Se ha cancelado el pintado");
618
                                                } catch (InvalidSetViewException e) {
619
                                                        throw new ReadException("Error reading file.", e);
620
                                                } catch (RasterDriverException e) {
621
                                                        throw new ReadException("Error reading file.", e);
622
                                                }
623
                                        try {
624
                                                status.applyStatus(this);
625
                                        } catch (NotSupportedExtensionException e) {
626
                                                throw new ReadException("Error in input file", e);
627
                                        } catch (FilterTypeException e) {
628
                                                throw new ReadException("Error setting filters from a project.", e);
629
                                        } catch (RasterDriverException e) {
630
                                                throw new ReadException("Error reading file.", e);
631
                                        } catch (FileNotFoundInListException e) {
632
                                                throw new ReadException("Error reading file.", e);
633
                                        } catch (OperationNotSupportedException e) {
634
                                                throw new ReadException("Error reading file.", e);
635
                                        } catch (FilterManagerException e) {
636
                                                throw new ReadException("Error reading file.", e);
637
                                        } catch (InvalidSourceException e) {
638
                                                throw new ReadException("Invalid file.", e);
639
                                        }
640
                                        firstLoad = false;
641
                                }*/
642

    
643
                                if (mustTileDraw) {
644
                                        Point2D p = vp.getOffset();
645
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
646
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
647
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
648
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
649
                                                // drawing part
650
                                                try {
651
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
652
                                                        draw(image, g, vport, cancel);
653
                                                } catch (InterruptedException e) {
654
                                                        System.out.println("Se ha cancelado el pintado");
655
                                                } catch (InvalidSetViewException e) {
656
                                                        throw new ReadException("Error reading file.", e);
657
                                                } catch (RasterDriverException e) {
658
                                                        throw new ReadException("Error reading file.", e);
659
                                                }  catch (NoninvertibleTransformException e) {
660
                                                        throw new ReadException("Error in the transformation.", e);
661
                                                }
662
                                } else
663
                                        try {
664
                                                draw(image, g, vp, cancel);
665
                                        } catch (InterruptedException e) {
666
                                                System.out.println("Se ha cancelado el pintado");
667
                                        } catch (InvalidSetViewException e) {
668
                                                throw new ReadException("Error reading file.", e);
669
                                        } catch (RasterDriverException e) {
670
                                                throw new ReadException("Error reading file.", e);
671
                                        }
672

    
673
                        }
674
                        
675
                        //callLegendChanged(null);
676
                } finally {
677
                        disableStopped();
678
                        task.setEvent(null);
679
                }
680
        }
681

    
682
        protected void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws RasterDriverException, InvalidSetViewException, InterruptedException {
683
                Envelope adjustedExtent = vp.getAdjustedExtent();
684
                if (adjustedExtent == null)
685
                        return;
686
                Extent e = rManager.getDataStructFactory().createExtent(adjustedExtent.getLowerCorner().getX(),
687
                                adjustedExtent.getUpperCorner().getY(), adjustedExtent
688
                                                .getUpperCorner().getX(),
689
                                adjustedExtent
690
                                                .getLowerCorner().getY());
691
                Dimension imgSz = vp.getImageSize();
692
                ViewPortData vp2 = rManager.createViewPortData(vp.getProjection(), e, imgSz );
693
                vp2.setMat(vp.getAffineTransform());
694
                //vp2.setTime(vp.getTime()); 
695
                
696
                try {
697
                        if(getDataStore().isTiled()) 
698
                                getRender().drawTiledService(g, vp2, vp.getImageSize());
699
                        else
700
                                getRender().draw(g, vp2);
701
                } catch (ProcessInterruptedException e1) {
702
                }
703
        }
704

    
705
        /**
706
         * Inserta la proyecci?n.
707
         *
708
         * @param proj Proyecci?n.
709
         */
710
        public void setProjection(IProjection proj) {
711
                super.setProjection(proj);
712
        }
713

    
714
        /*
715
         * (non-Javadoc)
716
         * @see org.gvsig.fmap.mapcontext.layers.FLayer#getFullEnvelope()
717
         */
718
        public Envelope getFullEnvelope() {
719
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
720
                //un extent aunque la capa no est? abierta
721
                if(/*!isOpen() || */dataStore == null || dataStore.getExtent() == null)
722
                        return null;
723

    
724
                Rectangle2D e = dataStore.getExtent().toRectangle2D();
725
                try {
726
                        return geomManager.createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
727
                                        .getMaxY(), SUBTYPES.GEOM2D);
728
                } catch (CreateEnvelopeException e1) {
729
                        logger.error("Error creating the envelope", e);
730
                        return null;
731
                }
732
        }
733

    
734
        /**
735
         * Obtiene el valor del pixel del Image en la posici?n x,y
736
         * @param x Posici?n x
737
         * @param y Posici?n y
738
         * @return valor de pixel
739
         */
740
        public int[] getPixel(int pxx, int pxy) {
741
                int[] argb = { -1, -1, -1, -1 };
742
                if (!isOpen() || (image == null))
743
                        return argb;
744
                if (pxx >= 0 && pxx < image.getWidth() && pxy >= 0 && pxy < image.getHeight()) {
745
                        int value = image.getRGB(pxx, pxy);
746
                        argb[0] = ((value & 0xff000000) >> 24);
747
                        argb[1] = ((value & 0x00ff0000) >> 16);
748
                        argb[2] = ((value & 0x0000ff00) >> 8);
749
                        argb[3] = (value & 0x000000ff);
750
                }
751
                return argb;
752
        }
753

    
754
        /*
755
         * (non-Javadoc)
756
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
757
         */
758
        public double getMaxX() {
759
                if(getFullEnvelope() != null)
760
                        return getFullEnvelope().getMaximum(0);
761
                return -1;
762
        }
763

    
764
        /*
765
         * (non-Javadoc)
766
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
767
         */
768
        public double getMaxY() {
769
                if(getFullEnvelope() != null)
770
                        return this.getFullEnvelope().getMaximum(1);
771
                return -1;
772
        }
773

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

    
784
        /*
785
         * (non-Javadoc)
786
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinY()
787
         */
788
        public double getMinY() {
789
                if(getFullEnvelope() != null)
790
                        return getFullEnvelope().getMinimum(1);
791
                return -1;
792
        }
793

    
794
        /* (non-Javadoc)
795
         * @deprecated. See String getInfo(Point p) throws DriverException
796
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
797
         */
798
        public String queryByPoint(Point p) {
799
                if (!isOpen())
800
                        return null;
801
                ColorConversion conv = rManager.getColorConversion();
802

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

    
805
                ArrayList<Object> attr = getAttributes();
806
                data += "  <raster\n";
807
                data += "    File=\"" + getFile() + "\"\n";
808
                for (int i = 0; i < attr.size(); i++) {
809
                        Object[] a = (Object[]) attr.get(i);
810

    
811
                        data += "    " + a[0].toString() + "=";
812
                        if (a[1].toString() instanceof String)
813
                                data += "\"" + a[1].toString() + "\"\n";
814
                        else
815
                                data += a[1].toString() + "\n";
816
                }
817
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
818
                data += "    Point_WC=\"" + mathUtil.format(posXWC, 3) + " , " + mathUtil.format(posYWC, 3) + "\"\n";
819
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
820
                double[] cmyk = conv.RGBtoCMYK(r & 0xff, g & 0xff, b & 0xff, 1D);
821
                data += "    CMYK=\"" + mathUtil.format(cmyk[0], 4) + ", " + mathUtil.format(cmyk[1], 4) + ", " + mathUtil.format(cmyk[2], 4) + "," + mathUtil.format(cmyk[3], 4) + "\"\n";
822
                double[] hsl = conv.RGBtoHSL(r & 0xff, g & 0xff, b & 0xff);
823
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
824
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
825
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
826
                data += "    HSL=\"" + mathUtil.format(hsl[0], 4) + ", " + mathUtil.format(hsl[1], 4) + ", " + mathUtil.format(hsl[2], 4) + "\"\n";
827
                data += "  />\n";
828

    
829
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
830
                return data;
831
        }
832

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

    
843
        /*
844
         * (non-Javadoc)
845
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAttributes()
846
         */
847
        public ArrayList<Object> getAttributes() {
848
                ArrayList<Object> attr = new ArrayList<Object>();
849
                if(!isOpen())
850
                        return attr;
851
                Object [][] a = {
852
                        {"Filename", dataStore.getName()},
853
                        {"Filesize", new Long(dataStore.getFileSize())},
854
                        {"Width", new Integer((int)dataStore.getWidth())},
855
                        {"Height", new Integer((int)dataStore.getHeight())},
856
                        {"Bands", new Integer(dataStore.getBandCount())}
857
                };
858
                for (int i = 0; i < a.length; i++)
859
                        attr.add(a[i]);
860
                return attr;
861
        }
862

    
863

    
864
        /* (non-Javadoc)
865
         * @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)
866
         */
867
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
868
                        double scale, PrintAttributes propeties) throws ReadException {
869

    
870
                if (/*!isOpen() ||*/ !isVisible() || !isWithinScale(scale))
871
                        return;
872

    
873
                if (!mustTilePrint)
874
                        draw(null, g, viewPort, cancel,scale);
875
                else {
876
                        // Para no pedir imagenes demasiado grandes, vamos
877
                        // a hacer lo mismo que hace EcwFile: chunkear.
878
                        // Llamamos a drawView con cuadraditos m?s peque?os
879
                        // del BufferedImage ni caso, cuando se imprime viene con null
880
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
881
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
882

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

    
886
                        //RasterStats stats = getSource().getFilterStack().getStats();
887
                        //if(stats != null)
888
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
889

    
890

    
891
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
892
                                // Parte que dibuja
893
                                try {
894
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
895
                                        draw(null, g, vp, cancel, scale);
896
                                } catch (NoninvertibleTransformException e) {
897
                                        throw new ReadException("Error en la transformaci?n.", e);
898
                                }
899
                }
900
        }
901

    
902
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
903
                        double scale) throws ReadException {
904
                if(!isOpen())
905
                        return;
906

    
907
                // Para no pedir imagenes demasiado grandes, vamos
908
                // a hacer lo mismo que hace EcwFile: chunkear.
909
                // Llamamos a drawView con cuadraditos m?s peque?os
910
                // del BufferedImage ni caso, cuando se imprime viene con null
911

    
912
                int numW, numH;
913
                int stepX, stepY;
914
                int xProv, yProv;
915
                int A = 1500;
916
                int H = 1500;
917
                int altoAux, anchoAux;
918

    
919
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
920

    
921
                // Vamos a hacerlo en trozos de AxH
922
                Rectangle r = g.getClipBounds();
923
                numW = (r.width) / A;
924
                numH = (r.height) / H;
925

    
926
                double[] srcPts = new double[8];
927
                double[] dstPts = new double[8];
928

    
929
                yProv = r.y;
930
                for (stepY = 0; stepY < numH + 1; stepY++) {
931
                        if ((yProv + H) > r.getMaxY())
932
                                altoAux = (int) r.getMaxY() - yProv;
933
                        else
934
                                altoAux = H;
935

    
936
                        xProv = r.x;
937
                        for (stepX = 0; stepX < numW + 1; stepX++) {
938
                                if ((xProv + A) > r.getMaxX())
939
                                        anchoAux = (int) r.getMaxX() - xProv;
940
                                else
941
                                        anchoAux = A;
942

    
943
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
944

    
945
                                // Parte que dibuja
946
                                srcPts[0] = xProv;
947
                                srcPts[1] = yProv;
948
                                srcPts[2] = xProv + anchoAux + 1;
949
                                srcPts[3] = yProv;
950
                                srcPts[4] = xProv + anchoAux + 1;
951
                                srcPts[5] = yProv + altoAux + 1;
952
                                srcPts[6] = xProv;
953
                                srcPts[7] = yProv + altoAux + 1;
954

    
955
                                try {
956
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
957
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
958
                                        // Extent extent = new Extent(rectCuadricula);
959

    
960
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
961
                                        ViewPort vp = (ViewPort)viewPort.clone();
962
                                        vp.setImageSize(tam);
963
                                        Envelope env = geomManager.createEnvelope(rectCuadricula
964
                                                        .getMinX(), rectCuadricula.getMinY(),
965
                                                        rectCuadricula.getMaxX(), rectCuadricula.getMaxY(),
966
                                                        SUBTYPES.GEOM2D);
967
                                        vp.setEnvelope(env);
968
                                        vp.setAffineTransform(mat);
969
                                        draw(null, g, vp, cancel, scale);
970

    
971
                                } catch (NoninvertibleTransformException e) {
972
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
973
                                } catch (ReadException e) {
974
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
975
                                } catch (CreateEnvelopeException e) {
976
                                        logger.error("Error creating the envelope", e);
977
                                } catch (CloneNotSupportedException e) {
978
                                        logger.error("Error cloning the viewport", e);
979
                                }
980
                                // Fin parte que dibuja
981
                                xProv = xProv + A;
982
                        }
983
                        yProv = yProv + H;
984
                }
985
        }
986

    
987
        /**
988
         * Borra de la lista de listeners el que se pasa como par?metro.
989
         *
990
         * @param o LayerListener a borrar.
991
         *
992
         * @return True si ha sido correcto el borrado del Listener.
993
         */
994
        public boolean removeLayerListener(LayerListener o) {
995
                if (this.isRemoveRasterFlag()) {
996
                        try {
997
                                enableClosed();
998
                        } catch (NotAvailableStateException e1) {
999
                                // No se ha podido cambiar el estado de la capa a cerrado
1000
                        }
1001
                }
1002

    
1003
                // Salva a RMF
1004
                if (dataStore != null)
1005
                        // Guardamos la GeoReferenciacion de cada dataset
1006
                        try {
1007
                                dataStore.saveGeoreferencingToRmf();
1008
                        } catch (RmfSerializerException e) {
1009
                                logger.error("error_salvando_rmf", this, e);
1010
                        }
1011

    
1012
                        if (this.isRemoveRasterFlag()) {
1013
                                image = null;
1014
                                if (dataStore != null) {
1015
                                        String[] files = getFileName().clone();
1016

    
1017
                                        try {
1018
                                                dataStore.close();
1019
                                        } catch (CloseException e) {
1020
                                        }
1021

    
1022
                                        dataStore = null;
1023
                                        render = null;
1024
                                        // System.gc();
1025
                                        this.setRemoveRasterFlag(true);
1026

    
1027
                                        for (int i = 0; i < files.length; i++) {
1028
                                                File file = new File(files[i]);
1029
                                                File dirTemp = fileUtil.getTemporalFile();
1030
                                                if(!file.exists())
1031
                                                        continue;
1032
                                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
1033
                                                        file.delete();
1034

    
1035
                                                        // Borramos todos los ficheros que puedan tener relacion con el fichero actual
1036
                                                        String basefile = file.getName();
1037
                                                        File basepath = file.getParentFile();
1038
                                                        int last = basefile.lastIndexOf(".");
1039
                                                        if (last != -1)
1040
                                                                basefile = basefile.substring(0, last + 1);
1041
                                                        File[] list = basepath.listFiles();
1042
                                                        for (int j = 0; j < list.length; j++)
1043
                                                                if (list[j].getName().startsWith(basefile))
1044
                                                                        list[j].delete();
1045
                                                }
1046
                                        }
1047
                                }
1048
                        }
1049
                        updateDrawVersion();
1050
                        return super.layerListeners.remove(o);
1051
        }
1052

    
1053
        /*
1054
         * (non-Javadoc)
1055
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRemoveRasterFlag()
1056
         */
1057
        public boolean isRemoveRasterFlag() {
1058
                return removeRasterFlag;
1059
        }
1060

    
1061
        /*
1062
         * (non-Javadoc)
1063
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setRemoveRasterFlag(boolean)
1064
         */
1065
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1066
                this.removeRasterFlag = removeRasterFlag;
1067
        }
1068

    
1069
        /*
1070
         * (non-Javadoc)
1071
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1072
         */
1073
        public String getTocImageIcon() {
1074
                return "map-ok-ico";
1075
        }
1076

    
1077
        /*
1078
         * (non-Javadoc)
1079
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getTileSize()
1080
         */
1081
        public int[] getTileSize() {
1082
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1083
                return size;
1084
        }
1085

    
1086
        /*
1087
         * (non-Javadoc)
1088
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isTiled()
1089
         */
1090
        public boolean isTiled() {
1091
                return mustTileDraw;
1092
        }
1093

    
1094
        /*
1095
         * (non-Javadoc)
1096
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isGeoreferenced()
1097
         */
1098
        public boolean isGeoreferenced() {
1099
                return dataStore.isGeoreferenced();
1100
        }
1101

    
1102
        /*
1103
         * (non-Javadoc)
1104
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getNoDataValue()
1105
         */
1106
        public NoData getNoDataValue() {
1107
                return dataStore.getNoDataValue();
1108
        }
1109

    
1110
        /**
1111
         * Sets the nodata value for this layer
1112
         * @param nd
1113
         */
1114
        public void setNoDataValue(NoData nd) {
1115
                if (dataStore != null)
1116
                        dataStore.setNoDataValue(nd);
1117
        }
1118

    
1119
        /*
1120
         * (non-Javadoc)
1121
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getPxHeight()
1122
         */
1123
        public double getPxHeight() {
1124
                return dataStore.getHeight();
1125
        }
1126

    
1127
        /*
1128
         * (non-Javadoc)
1129
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getPxWidth()
1130
         */
1131
        public double getPxWidth() {
1132
                return dataStore.getWidth();
1133
        }
1134

    
1135
        /**
1136
         * Gets the height in world coordinates of this raster layer
1137
         */
1138
        public double getWCHeight() {
1139
                return getFullEnvelope().getMaximum(1);
1140
        }
1141

    
1142
        /**
1143
         * Gets the width in world coordinates of this raster layer
1144
         */
1145
        public double getWCWidth() {
1146
                return getFullEnvelope().getMaximum(0);
1147
        }
1148

    
1149
        /**
1150
         * Gets the size of all files of this raster layer
1151
         */
1152
        public long[] getFileSize() {
1153
                if (dataStore == null)
1154
                        return null;
1155

    
1156
                return dataStore.getFileSizeByProvider();
1157
        }
1158

    
1159
        /**
1160
         * Gets the list of file names
1161
         */
1162
        public String[] getFileName() {
1163
                if (dataStore == null)
1164
                        return null;
1165

    
1166
                return dataStore.getURIByProvider();
1167
        }
1168

    
1169
        /**
1170
         * Returns the number of files in this raster layer
1171
         */
1172
        public int getFileCount() {
1173
                return dataStore.getProviderCount();
1174
        }
1175

    
1176
        /*
1177
         * (non-Javadoc)
1178
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileFormat()
1179
         */
1180
        public String getFileFormat() {
1181
                if(dataStore.getSourceType() == RasterDataStore.FILE) {
1182
                        String fName = dataStore.getName();
1183
                        int index = fName.lastIndexOf(".") + 1;
1184
                        String ext = null;
1185
                        if (index > 0)
1186
                                ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1187
                        return ext;
1188
                }
1189
                if(dataStore.getSourceType() == RasterDataStore.POSTGIS) {
1190
                        return "POSTGIS";
1191
                }
1192
                return null;
1193
        }
1194

    
1195
        /*
1196
         * (non-Javadoc)
1197
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1198
         */
1199
        public int[] getDataType() {
1200
                return dataStore.getDataType();
1201
        }
1202

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

    
1325
        /*
1326
         * (non-Javadoc)
1327
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getBandCountFromDataset()
1328
         */
1329
        public int[] getBandCountFromDataset() {
1330
                return dataStore.getBandCountByProvider();
1331
        }
1332

    
1333
        /*
1334
         * (non-Javadoc)
1335
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1336
         */
1337
        public String getColorInterpretation(int band, int dataset) {
1338
                if (this.dataStore.getColorInterpretation().get(band) == null)
1339
                        return "Undefined";
1340
                return this.dataStore.getColorInterpretation().get(band);
1341
        }
1342

    
1343
        /*
1344
         * (non-Javadoc)
1345
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getWktProjection()
1346
         */
1347
        public String getWktProjection() throws RasterDriverException {
1348
                return dataStore.getWktProjection();
1349
        }
1350

    
1351
        /*
1352
         * (non-Javadoc)
1353
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRGB()
1354
         */
1355
        public boolean isRGB() {
1356
                if ((dataStore == null) || (render == null))
1357
                        return false;
1358

    
1359
                if (dataStore.getDataType()[0] != Buffer.TYPE_BYTE)
1360
                        return false;
1361

    
1362
                boolean R = false;
1363
                boolean G = false;
1364
                boolean B = false;
1365

    
1366
                int[] renderBands = render.getRenderBands();
1367
                for (int i = 0; i < renderBands.length; i++)
1368
                        if (renderBands[i] >= 0)
1369
                                switch (i) {
1370
                                        case 0:
1371
                                                R = true;
1372
                                                break;
1373
                                        case 1:
1374
                                                G = true;
1375
                                                break;
1376
                                        case 2:
1377
                                                B = true;
1378
                                                break;
1379
                                }
1380

    
1381
                if (R && G && B)
1382
                        return true;
1383

    
1384
                return false;
1385
        }
1386

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

    
1412
        /*
1413
         * (non-Javadoc)
1414
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getReadOnlyFullGrid(boolean)
1415
         */
1416
        public Grid getReadOnlyFullGrid(boolean interpolated) throws GridException, InterruptedException {
1417
                RasterQuery query = rManager.createQuery();
1418
                query.setReadOnly(true);
1419
                query.setAllDrawableBands();
1420
                Buffer bf = null;
1421
                try {
1422
                        query.setAreaOfInterest();
1423
                        bf = dataStore.query(query);
1424
                } catch (RasterDriverException e) {
1425
                        throw new GridException("Error reading buffer");
1426
                } catch (ProcessInterruptedException e) {
1427
                        throw new InterruptedException("Carga interrumpida");
1428
                } catch (InvalidSetViewException e) {
1429
                        throw new GridException("Error reading buffer");
1430
                }
1431
                return rManager.createGrid(bf, dataStore, interpolated);
1432
        }
1433

    
1434
        /**
1435
         * Obtiene el tama?o de celda de la fuente de datos
1436
         * @return double con el tama?o de celda
1437
         */
1438
        public double getCellSize() {
1439
                return (dataStore != null) ? dataStore.getCellSize() : 1;
1440
        }
1441

    
1442
        /*
1443
         * (non-Javadoc)
1444
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFullRasterExtent()
1445
         */
1446
        public Extent getFullRasterExtent() {
1447
                return this.dataStore.getExtent();
1448
        }
1449

    
1450

    
1451
        /**
1452
         * Devuelve el fichero asociado a la capa o null si no tiene.
1453
         * @return Fichero.
1454
         */
1455
        public File getFile() {
1456
                if(getDataStore().getParameters() instanceof RasterFileStoreParameters)
1457
                        return ((RasterFileStoreParameters)getDataStore().getParameters()).getFile();
1458
                return new File("");
1459
        }
1460

    
1461
        /**
1462
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1463
         * @param file Fichero a consultar
1464
         * @return true si es aceptado y false si no lo es.
1465
         */
1466
        public boolean isFileAccepted(File file) {
1467
                return dataStore.isFileSupported(file.getName());
1468
        }
1469
        
1470
        /**
1471
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1472
         * @param file Fichero a consultar
1473
         * @return true si es aceptado y false si no lo es.
1474
         */
1475
        public static boolean isFileSupported(File file) {
1476
                return RasterLocator.getManager().isExtensionSupported(file.getName());
1477
        }
1478

    
1479
        /*
1480
         * (non-Javadoc)
1481
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#existColorTable()
1482
         */
1483
        public boolean existColorTable() {
1484
                return getRender().existColorTable();
1485
        }
1486

    
1487
        /**
1488
         * Returns true if the data store has an alpha band
1489
         */
1490
        public boolean existsAlphaBand() {
1491
                if(dataStore.getColorInterpretation() != null)
1492
                        return dataStore.getColorInterpretation().hasAlphaBand();
1493
                else
1494
                        return false;
1495
        }
1496

    
1497
        /*
1498
         * (non-Javadoc)
1499
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAlphaBandNumber()
1500
         */
1501
        public int getAlphaBandNumber() {
1502
                if(dataStore.getColorInterpretation() != null)
1503
                        return dataStore.getColorInterpretation().getBand(ColorInterpretation.ALPHA_BAND);
1504
                return -1;
1505
        }
1506

    
1507
        /**
1508
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1509
         * capa busque una leyenda valida.
1510
         * @param ct
1511
         */
1512
        public void setLastLegend(ColorTable ct) {
1513
                lastLegend = ColorTableLegend.createLegend(ct);
1514
        }
1515

    
1516
        /**
1517
         * Devuelve la Leyenda de la capa.
1518
         * @return Leyenda.
1519
         */
1520
        public ILegend getLegend() {
1521
                if (lastLegend != null)
1522
                        return lastLegend;
1523

    
1524
                return null;
1525
        }
1526

    
1527
        /*
1528
         * (non-Javadoc)
1529
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1530
         */
1531
        public void addLegendListener(LegendListener listener) {
1532
                layerChangeSupport.addLayerListener(listener);
1533
        }
1534

    
1535
        /*
1536
         *  (non-Javadoc)
1537
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1538
         */
1539
        public int getShapeType() {
1540
                return TYPES.SURFACE;
1541
        }
1542

    
1543
        /*
1544
         * (non-Javadoc)
1545
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1546
         */
1547
        public void removeLegendListener(LegendListener listener) {
1548
                layerChangeSupport.removeLayerListener(listener);
1549
        }
1550

    
1551
        /*
1552
         * (non-Javadoc)
1553
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isInside(java.awt.geom.Point2D)
1554
         */
1555
        public boolean isInside(Point2D p) {
1556
                 return dataStore.isInside(p);
1557
        }
1558

    
1559
        /*
1560
         * (non-Javadoc)
1561
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAffineTransform()
1562
         */
1563
        public AffineTransform getAffineTransform() {
1564
                return dataStore.getAffineTransform();
1565
        }
1566

    
1567
        /*
1568
         * (non-Javadoc)
1569
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setAffineTransform(java.awt.geom.AffineTransform)
1570
         */
1571
        public void setAffineTransform(AffineTransform transf) {
1572
                if(transf == null)
1573
                        return;
1574
                affineTransformList.add(transf);
1575
                dataStore.setAffineTransform(transf);
1576
                updateDrawVersion();
1577
        }
1578

    
1579
        /*
1580
         * (non-Javadoc)
1581
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setAffineTransformWithoutHistorical(java.awt.geom.AffineTransform)
1582
         */
1583
        public void setAffineTransformWithoutHistorical(AffineTransform transf) {
1584
                dataStore.setAffineTransform(transf);
1585
                updateDrawVersion();
1586
        }
1587

    
1588
        /*
1589
         * (non-Javadoc)
1590
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAffineTransformHistorical()
1591
         */
1592
        public Historical getAffineTransformHistorical() {
1593
                return this.affineTransformList;
1594
        }
1595

    
1596
        /*
1597
         * (non-Javadoc)
1598
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#saveGeoToRmf()
1599
         */
1600
        public void saveGeoToRmf() throws RmfSerializerException {
1601
                if (!isOpen())
1602
                        return;
1603

    
1604
                dataStore.saveGeoreferencingToRmf();
1605
                
1606
                affineTransformList.clear();
1607
                affineTransformList.add(this.getAffineTransform());
1608
        }
1609

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

    
1647
        /*
1648
         * (non-Javadoc)
1649
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1650
         */
1651
        public void setVisible(boolean visibility) {
1652
                if(visibility)
1653
                        state.disableStopped();
1654
                else
1655
                        enableStopped();
1656

    
1657
                if(isAwake() || isClosed())
1658
                        try {
1659
                                this.load();
1660
                        } catch (LoadLayerException e) {
1661
                                e.printStackTrace();
1662
                        }
1663

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

    
1679
                super.setVisible(visibility);
1680
        }
1681

    
1682
        /**
1683
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1684
         * @return valor de transparencia
1685
         */
1686
        public int getTransparency() {
1687
                try {
1688
                        return getRender().getLastTransparency().getOpacity();
1689
                } catch (NullPointerException e) {
1690
                        return super.getTransparency();
1691
                }
1692
        }
1693

    
1694
        /**
1695
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1696
         * o no.
1697
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1698
         */
1699
        public boolean isTransparent() {
1700
                return getRender().getLastTransparency().isTransparencyActive();
1701
        }
1702

    
1703
        /**
1704
         * Asigna la transparencia de la siguiente renderizaci?n
1705
         * @param valor de transparencia
1706
         */
1707
        public void setTransparency(int trans) {
1708
                super.setTransparency(trans);
1709
                try {
1710
                        getRender().getLastTransparency().setOpacity(trans);
1711
                } catch (NullPointerException e) {
1712
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1713
                }
1714
        }
1715

    
1716
        /**
1717
         * Gets the last buffer which was rendered
1718
         */
1719
        public Buffer getLastRenderBuffer() {
1720
                return getRender().getLastRenderBuffer();
1721
        }
1722

    
1723
        /**
1724
         *
1725
         * @return ROIs asociadas a la capa raster.
1726
         */
1727
        public ArrayList<ROI> getRois() {
1728
                return rois;
1729
        }
1730

    
1731
        /**
1732
         * Establece las ROI asociadas a la capa raster.
1733
         *
1734
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1735
         */
1736
        public void setRois(ArrayList<ROI> rois) {
1737
                this.rois = rois;
1738
        }
1739

    
1740
        /**
1741
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1742
         * devolver? null.
1743
         * @return TreeMap con la lista de capas a dibujar
1744
         */
1745
        public HashMap<DefaultFLyrRaster, Boolean> getRasterStrategy() {
1746
                if(strategy != null)
1747
                        return strategy.getStrategy();
1748
                return null;
1749
        }
1750

    
1751
        /**
1752
         * @return the configuration
1753
         */
1754
        static public IConfiguration getConfiguration() {
1755
                return configuration;
1756
        }
1757

    
1758
        /**
1759
         * @param configuration the configuration to set
1760
         */
1761
        static public void setConfiguration(IConfiguration configuration) {
1762
                DefaultFLyrRaster.configuration = configuration;
1763
        }
1764

    
1765
        /*
1766
         * (non-Javadoc)
1767
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#reload()
1768
         */
1769
        public void reload() throws ReloadLayerException {
1770
                try {
1771
                        super.reload();
1772
                        if (getMapContext() == null)
1773
                                return;
1774
                        if (isStopped())
1775
                                disableStopped();
1776
                        load();
1777
                        getMapContext().invalidate();
1778
                } catch (LoadLayerException e) {
1779
                        setAvailable(false);
1780
                        throw new ReloadLayerException(getName(), e);
1781
                }
1782
        }
1783

    
1784
        /**
1785
         * Devuelve si la capa tiene soporte para poder generar overviews
1786
         * @return
1787
         */
1788
        public boolean overviewsSupport() {
1789
                if ((dataStore != null) && (dataStore.overviewsSupport()))
1790
                        return true;
1791

    
1792
                return false;
1793
        }
1794

    
1795
        /**
1796
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1797
         * en escala de grises
1798
         * @return
1799
         */
1800
        public boolean isRenderingAsGray() {
1801
                int[] renderBands = getRender().getRenderBands();
1802
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1803
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1804
                        return true;
1805
                return false;
1806
        }
1807

    
1808
        /*
1809
         * (non-Javadoc)
1810
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
1811
         */
1812
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1813
                updateDrawVersion();
1814
        }
1815

    
1816
        /*
1817
         * (non-Javadoc)
1818
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#adjustWorldRequest(java.awt.geom.Point2D)
1819
         */
1820
        public Point2D adjustWorldRequest(Point2D req) {
1821
                Envelope ext = null;
1822

    
1823
                ext = getFullEnvelope();
1824
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
1825
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
1826
                return req;
1827
        }
1828

    
1829
        /*
1830
         * (non-Javadoc)
1831
         * @see org.gvsig.fmap.mapcontext.layers.FLyrDefault#cloneLayer()
1832
         */
1833
        public FLayer cloneLayer() throws Exception {
1834
                RasterDataStore  ds = dataStore.cloneDataStore();
1835
                DefaultFLyrRaster newLayer = new DefaultFLyrRaster();
1836
                newLayer.setName(getName());
1837
                newLayer.setOpenRasterStore(ds);
1838
                newLayer.firstLoad = firstLoad;
1839
                
1840
                ArrayList<RasterFilter> filters = getRender().getFilterList().getStatusCloned();
1841

    
1842
                //Hacemos una copia de las bandas a renderizar
1843
                if(getRender().getRenderBands() != null) {
1844
                        int[] rb = new int[getRender().getRenderBands().length];
1845
                        for (int i = 0; i < rb.length; i++)
1846
                                rb[i] = getRender().getRenderBands()[i];
1847
                        newLayer.getRender().setRenderBands(rb);
1848
                }
1849

    
1850
                //Asignamos el entorno
1851
                if(newLayer.getRender().getFilterList() == null)
1852
                        newLayer.getRender().setFilterList(RasterLocator.getManager().createEmptyFilterList(getRender().getFilterList().getInitDataType()));
1853
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
1854
                newLayer.getRender().getFilterList().setStatus(filters);
1855

    
1856
                // Asignamos los valores noData del original
1857
                newLayer.setNoDataValue(getNoDataValue());
1858
                if(dataStore.getNoDataValue().isDefined())
1859
                        newLayer.setNoDataTransparent(true);
1860
                newLayer.enableOpen();
1861
                
1862
                return newLayer;
1863
        }
1864
        
1865
        /*
1866
         * (non-Javadoc)
1867
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileLayer()
1868
         */
1869
        public FLayer getFileLayer() throws RasterDriverException {
1870
                try {
1871
                        return cloneLayer();
1872
                } catch (Exception e) {
1873
                }
1874
                return null;
1875
        }
1876
        
1877
        /*
1878
         * (non-Javadoc)
1879
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#addFile(java.lang.String)
1880
         */
1881
        public void addFile(String file) throws InvalidSourceException {
1882
                getDataStore().addFile(file);
1883
        }
1884
        
1885
        /*
1886
         * (non-Javadoc)
1887
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#removeFile(java.lang.String)
1888
         */
1889
        public void removeFile(String file) {
1890
                getDataStore().removeFile(file);
1891
        }
1892

    
1893
        /*****************************************************/
1894

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

    
1897
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1898

    
1899
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
1900

    
1901
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1902

    
1903
        public void enableStopped() {state.enableStopped();}
1904

    
1905
        public boolean isAwake() {return state.isAwake();}
1906

    
1907
        public boolean isClosed() {return state.isClosed();}
1908

    
1909
        public boolean isOpen() {return state.isOpen();}
1910

    
1911
        public boolean isStopped() {return state.isStopped();}
1912

    
1913

    
1914
        @SuppressWarnings("unchecked")
1915
        public Set getMetadataChildren() {
1916
                return null;
1917
        }
1918

    
1919
        public Object getMetadataID() {
1920
                return getName();
1921
        }
1922

    
1923
        public String getMetadataName() {
1924
                return null;
1925
        }
1926

    
1927
        /*
1928
         * (non-Javadoc)
1929
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getDataStore()
1930
         */
1931
        public RasterDataStore getDataStore() {
1932
                return this.dataStore;
1933
        }
1934

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

    
1979
        /**
1980
         * When a process is using information of this layer this variable will contain
1981
         * the thread ID.
1982
         * @param readingData
1983
         */
1984
        public synchronized void setReadingData(String readingData) {
1985
                this.readingData = readingData;
1986
        }
1987
        
1988
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel,
1989
                        boolean fast)
1990
                        throws LoadLayerException, DataException {
1991
                return null;
1992
        }
1993

    
1994
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel)
1995
                        throws LoadLayerException, DataException {
1996
                return null;
1997
        }
1998

    
1999
        @Override
2000
        protected void doDispose() throws BaseException {
2001
                // Nothing to do
2002
        }
2003

    
2004
        /*
2005
         * (non-Javadoc)
2006
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#getZoomLevel()
2007
         */
2008
        public int getZoomLevel() {
2009
                return zoomLevel;
2010
        }
2011

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

    
2094
        @Override
2095
        public void saveToState(PersistentState state) throws PersistenceException {
2096
                super.saveToState(state);
2097
                
2098
                //state.set("status", status);
2099
                state.set("rasterdatastore", dataStore);        
2100
                state.set("legend", lastLegend);        
2101
                state.set("rois", rois);        
2102
                state.set("colortable", getRender().getColorTable());        
2103
                state.set("zoomLevel", zoomLevel);        
2104
                state.set("recalcLevel", recalcLevel);        
2105
        }        
2106
        
2107
        public static void registerPersistence() {
2108
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
2109
                DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
2110
                if( definition == null ) {
2111
                        if (manager.getDefinition(FLyrDefault.class) == null) {
2112
                                FLyrDefault.registerPersistent();
2113
                        }
2114
                        definition = manager.addDefinition(
2115
                                        DefaultFLyrRaster.class,
2116
                                        PERSISTENT_NAME,
2117
                                        PERSISTENT_DESCRIPTION,
2118
                                        null, 
2119
                                        null
2120
                        );
2121
                        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE, "FLyrDefault");
2122
                        
2123
                        registerPersistence(definition);
2124
                }
2125
        }
2126
        
2127
        public static void registerPersistence(DynStruct definition) {
2128
                //definition.addDynFieldObject("status").setClassOfValue(StatusLayerRaster.class).setMandatory(false);
2129
                definition.addDynFieldObject("rasterdatastore").setClassOfValue(RasterDataStore.class).setMandatory(true);
2130
                definition.addDynFieldObject("legend").setClassOfValue(ILegend.class).setMandatory(false);
2131
                definition.addDynFieldList("rois").setClassOfItems(ROI.class).setMandatory(false);
2132
                definition.addDynFieldObject("colortable").setClassOfValue(ColorTable.class).setMandatory(false);
2133
                definition.addDynFieldInt("zoomlevel").setMandatory(false);
2134
                definition.addDynFieldBoolean("recalcLevel").setMandatory(false);
2135
        }
2136

    
2137
        /*
2138
         * (non-Javadoc)
2139
         * @see org.gvsig.fmap.mapcontext.layers.operations.Classifiable#getGeometryType()
2140
         */
2141
        public GeometryType getGeometryType() throws ReadException {
2142
                try {
2143
                        return GeometryLocator.getGeometryManager().getGeometryType(TYPES.SURFACE, SUBTYPES.GEOM2D);
2144
                } catch (GeometryTypeNotSupportedException e) {
2145
                        throw new ReadException(getDataStore().getName(), e);
2146
                } catch (GeometryTypeNotValidException e) {
2147
                        throw new ReadException(getDataStore().getName(), e);
2148
                } 
2149
        }
2150

    
2151
}