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

History | View | Annotate | Download (68.2 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.gvsig.utils.XMLEntity;
134
import org.gvsig.utils.XMLException;
135
import org.slf4j.Logger;
136
import org.slf4j.LoggerFactory;
137

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

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

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

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

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

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

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

    
281
                enableStopped(); // Paramos la capa mientras se hace un load
282

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

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

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

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

    
335
                render = dataStore.getRender();
336
                render.addVisualPropertyListener(this);
337
                initFilters();
338

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

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

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

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

    
391
        /*
392
         * (non-Javadoc)
393
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setNoDataTransparent(boolean)
394
         */
395
        public void setNoDataTransparent(boolean t) {
396
                if(dataStore.getNoDataValue().isDefined()) {
397
                        dataStore.getTransparency().setNoData(dataStore.getNoDataValue());
398
                }
399
                dataStore.getTransparency().activeNoData(t);
400
                dataStore.getTransparency().activeTransparency();
401
        }
402

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

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

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

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

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

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

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

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

    
485
                Statistics stats = dataStore.getStatistics();
486
                ColorTableLibrary colorTableLibrary = rManager.getDataStructFactory().getColorTableLibrary();
487

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

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

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

    
507
                                                        setLastLegend(colorTable);
508

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

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

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

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

    
568
                try {
569
                        if (!isOpen())
570
                                return;
571

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
865

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

    
872
                if (/*!isOpen() ||*/ !isVisible() || !isWithinScale(scale))
873
                        return;
874

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

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

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

    
892

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

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

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

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

    
921
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
922

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

    
928
                double[] srcPts = new double[8];
929
                double[] dstPts = new double[8];
930

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

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

    
945
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
946

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

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

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

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

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

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

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

    
1019
                                        try {
1020
                                                dataStore.close();
1021
                                        } catch (CloseException e) {
1022
                                        }
1023

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1158
                return dataStore.getFileSizeByProvider();
1159
        }
1160

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

    
1168
                return dataStore.getURIByProvider();
1169
        }
1170

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

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

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

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

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

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

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

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

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

    
1364
                boolean R = false;
1365
                boolean G = false;
1366
                boolean B = false;
1367

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

    
1383
                if (R && G && B)
1384
                        return true;
1385

    
1386
                return false;
1387
        }
1388

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

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

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

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

    
1452

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

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

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

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

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

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

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

    
1526
                return null;
1527
        }
1528

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1681
                super.setVisible(visibility);
1682
        }
1683

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

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

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

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

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

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

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

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

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

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

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

    
1794
                return false;
1795
        }
1796

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

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

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

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

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

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

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

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

    
1895
        /*****************************************************/
1896

    
1897
        public void disableStopped() {state.disableStopped();}
1898

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

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

    
1903
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1904

    
1905
        public void enableStopped() {state.enableStopped();}
1906

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

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

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

    
1913
        public boolean isStopped() {return state.isStopped();}
1914

    
1915

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

    
1921
        public Object getMetadataID() {
1922
                return getName();
1923
        }
1924

    
1925
        public String getMetadataName() {
1926
                return null;
1927
        }
1928

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

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

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

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

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

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

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

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

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

    
2153
}