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

History | View | Annotate | Download (69.1 KB)

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

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

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

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

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

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

    
248
                return lyr;
249
        }
250

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
508
                                                        setLastLegend(colorTable);
509

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

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

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

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

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

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

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

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

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

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

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

    
699
        /*
700
         * (non-Javadoc)
701
         * @see org.gvsig.fmap.mapcontext.layers.FLayer#getFullEnvelope()
702
         */
703
        public Envelope getFullEnvelope() {
704
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
705
                //un extent aunque la capa no est? abierta
706
                if(/*!isOpen() || */getDataStore() == null || getDataStore().getExtent() == null)
707
                        return null;
708

    
709
                Rectangle2D e = getDataStore().getExtent().toRectangle2D();
710
                try {
711
                        return geomManager.createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
712
                                        .getMaxY(), SUBTYPES.GEOM2D);
713

    
714
                        /*
715
                        No es necesario 
716
                        ICoordTrans ct = getCoordTrans();
717
                        RasterDataParameters params = (RasterDataParameters)getDataStore().getParameters();
718
                        if (ct != null && params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
719
                                env = env.convert(ct);
720
                        }
721
                        return env;*/
722

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

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

    
759
        /*
760
         * (non-Javadoc)
761
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
762
         */
763
        public double getMaxY() {
764
                if(getFullEnvelope() != null)
765
                        return this.getFullEnvelope().getMaximum(1);
766
                return -1;
767
        }
768

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

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

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

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

    
800
                ArrayList<Object> attr = getAttributes();
801
                data += "  <raster\n";
802
                data += "    File=\"" + getFile() + "\"\n";
803
                for (int i = 0; i < attr.size(); i++) {
804
                        Object[] a = (Object[]) attr.get(i);
805

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

    
824
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
825
                return data;
826
        }
827

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

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

    
858

    
859
        /* (non-Javadoc)
860
         * @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)
861
         */
862
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
863
                        double scale, PrintAttributes propeties) throws ReadException {
864

    
865
                if (/*!isOpen() ||*/ !isVisible() || !isWithinScale(scale))
866
                        return;
867
                
868
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
869
                SimpleTaskStatus taskStatus = new RasterTaskStatus("Printing raster " + getName() + "...", cancel);
870
                manager.add(taskStatus);
871
                taskStatus.setAutoremove(true);
872

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

    
896
        /*public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
897
                        double scale) throws ReadException {
898
                if(!isOpen())
899
                        return;
900

901
                // Para no pedir imagenes demasiado grandes, vamos
902
                // a hacer lo mismo que hace EcwFile: chunkear.
903
                // Llamamos a drawView con cuadraditos m?s peque?os
904
                // del BufferedImage ni caso, cuando se imprime viene con null
905

906
                int numW, numH;
907
                int stepX, stepY;
908
                int xProv, yProv;
909
                int A = 1500;
910
                int H = 1500;
911
                int altoAux, anchoAux;
912

913
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
914

915
                // Vamos a hacerlo en trozos de AxH
916
                Rectangle r = g.getClipBounds();
917
                numW = (r.width) / A;
918
                numH = (r.height) / H;
919

920
                double[] srcPts = new double[8];
921
                double[] dstPts = new double[8];
922

923
                yProv = r.y;
924
                for (stepY = 0; stepY < numH + 1; stepY++) {
925
                        if ((yProv + H) > r.getMaxY())
926
                                altoAux = (int) r.getMaxY() - yProv;
927
                        else
928
                                altoAux = H;
929

930
                        xProv = r.x;
931
                        for (stepX = 0; stepX < numW + 1; stepX++) {
932
                                if ((xProv + A) > r.getMaxX())
933
                                        anchoAux = (int) r.getMaxX() - xProv;
934
                                else
935
                                        anchoAux = A;
936

937
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
938

939
                                // Parte que dibuja
940
                                srcPts[0] = xProv;
941
                                srcPts[1] = yProv;
942
                                srcPts[2] = xProv + anchoAux + 1;
943
                                srcPts[3] = yProv;
944
                                srcPts[4] = xProv + anchoAux + 1;
945
                                srcPts[5] = yProv + altoAux + 1;
946
                                srcPts[6] = xProv;
947
                                srcPts[7] = yProv + altoAux + 1;
948

949
                                try {
950
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
951
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
952
                                        // Extent extent = new Extent(rectCuadricula);
953

954
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
955
                                        ViewPort vp = (ViewPort)viewPort.clone();
956
                                        vp.setImageSize(tam);
957
                                        Envelope env = geomManager.createEnvelope(rectCuadricula
958
                                                        .getMinX(), rectCuadricula.getMinY(),
959
                                                        rectCuadricula.getMaxX(), rectCuadricula.getMaxY(),
960
                                                        SUBTYPES.GEOM2D);
961
                                        vp.setEnvelope(env);
962
                                        vp.setAffineTransform(mat);
963
                                        draw(null, g, vp, cancel, scale);
964

965
                                } catch (NoninvertibleTransformException e) {
966
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
967
                                } catch (ReadException e) {
968
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
969
                                } catch (CreateEnvelopeException e) {
970
                                        logger.error("Error creating the envelope", e);
971
                                } catch (CloneNotSupportedException e) {
972
                                        logger.error("Error cloning the viewport", e);
973
                                }
974
                                // Fin parte que dibuja
975
                                xProv = xProv + A;
976
                        }
977
                        yProv = yProv + H;
978
                }
979
        }*/
980

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

    
997
                // Salva a RMF
998
                if (getDataStore() != null)
999
                        // Guardamos la GeoReferenciacion de cada dataset
1000
                        try {
1001
                                getDataStore().saveGeoreferencingToRmf();
1002
                        } catch (Exception e) {
1003
                                logger.info("error_salvando_rmf", e);
1004
                        }
1005

    
1006
                        if (this.isRemoveRasterFlag()) {
1007
                                if (getDataStore() != null) {
1008
                                        String[] files = getFileName().clone();
1009

    
1010
                                        try {
1011
                                                getDataStore().close();
1012
                                        } catch (CloseException e) {
1013
                                        }
1014

    
1015
                                        dataStore = null;
1016
                                        if(render != null)
1017
                                                render.dispose();
1018
                                        render = null;
1019
                                        // System.gc();
1020
                                        this.setRemoveRasterFlag(true);
1021

    
1022
                                        for (int i = 0; i < files.length; i++) {
1023
                                                File file = new File(files[i]);
1024
                                                File dirTemp = fileUtil.getTemporalFile();
1025
                                                if(!file.exists())
1026
                                                        continue;
1027
                                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
1028
                                                        file.delete();
1029

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

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

    
1056
        /*
1057
         * (non-Javadoc)
1058
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setRemoveRasterFlag(boolean)
1059
         */
1060
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1061
                this.removeRasterFlag = removeRasterFlag;
1062
        }
1063

    
1064
        /*
1065
         * (non-Javadoc)
1066
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1067
         */
1068
        public String getTocImageIcon() {
1069
                return "map-ok-ico";
1070
        }
1071

    
1072
        /*
1073
         * (non-Javadoc)
1074
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getTileSize()
1075
         */
1076
        public int[] getTileSize() {
1077
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1078
                return size;
1079
        }
1080

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

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

    
1097
        /*
1098
         * (non-Javadoc)
1099
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getNoDataValue()
1100
         */
1101
        public NoData getNoDataValue() {
1102
                return getDataStore().getNoDataValue();
1103
        }
1104

    
1105
        /**
1106
         * Sets the nodata value for this layer
1107
         * @param nd
1108
         */
1109
        public void setNoDataValue(NoData nd) {
1110
                if (getDataStore() != null)
1111
                        getDataStore().setNoDataValue(nd);
1112
        }
1113

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

    
1122
        /*
1123
         * (non-Javadoc)
1124
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getPxWidth()
1125
         */
1126
        public double getPxWidth() {
1127
                return getDataStore().getWidth();
1128
        }
1129

    
1130
        /**
1131
         * Gets the height in world coordinates of this raster layer
1132
         */
1133
        public double getWCHeight() {
1134
                return getFullEnvelope().getMaximum(1);
1135
        }
1136

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

    
1144
        /**
1145
         * Gets the size of all files of this raster layer
1146
         */
1147
        public long[] getFileSize() {
1148
                if (getDataStore() == null)
1149
                        return null;
1150

    
1151
                return getDataStore().getFileSizeByProvider();
1152
        }
1153

    
1154
        /**
1155
         * Gets the list of file names
1156
         */
1157
        public String[] getFileName() {
1158
                if (getDataStore() == null)
1159
                        return null;
1160

    
1161
                return getDataStore().getURIByProvider();
1162
        }
1163

    
1164
        /**
1165
         * Returns the number of files in this raster layer
1166
         */
1167
        public int getFileCount() {
1168
                return getDataStore().getProviderCount();
1169
        }
1170

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

    
1190
        /*
1191
         * (non-Javadoc)
1192
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1193
         */
1194
        public int[] getDataType() {
1195
                return getDataStore().getDataType();
1196
        }
1197

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

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

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

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

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

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

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

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

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

    
1384
                return false;
1385
        }
1386

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

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

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

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

    
1450

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

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

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

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

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

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

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

    
1524
                return null;
1525
        }
1526

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1680
                super.setVisible(visibility);
1681
        }
1682

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

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

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

    
1717
        /**
1718
         *
1719
         * @return ROIs asociadas a la capa raster.
1720
         */
1721
        public ArrayList<ROI> getRois() {
1722
                return rois;
1723
        }
1724

    
1725
        /**
1726
         * Establece las ROI asociadas a la capa raster.
1727
         *
1728
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1729
         */
1730
        public void setRois(ArrayList<ROI> rois) {
1731
                this.rois = rois;
1732
        }
1733

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

    
1745
        /**
1746
         * @return the configuration
1747
         */
1748
        static public IConfiguration getConfiguration() {
1749
                return configuration;
1750
        }
1751

    
1752
        /**
1753
         * @param configuration the configuration to set
1754
         */
1755
        static public void setConfiguration(IConfiguration configuration) {
1756
                DefaultFLyrRaster.configuration = configuration;
1757
        }
1758

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

    
1778
        /**
1779
         * Devuelve si la capa tiene soporte para poder generar overviews
1780
         * @return
1781
         */
1782
        public boolean overviewsSupport() {
1783
                if ((getDataStore() != null) && (getDataStore().overviewsSupport()))
1784
                        return true;
1785

    
1786
                return false;
1787
        }
1788

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

    
1802
        /*
1803
         * (non-Javadoc)
1804
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
1805
         */
1806
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1807
                updateDrawVersion();
1808
        }
1809

    
1810
        /*
1811
         * (non-Javadoc)
1812
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#adjustWorldRequest(java.awt.geom.Point2D)
1813
         */
1814
        public Point2D adjustWorldRequest(Point2D req) {
1815
                Envelope ext = null;
1816

    
1817
                ext = getFullEnvelope();
1818
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
1819
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
1820
                return req;
1821
        }
1822

    
1823
        /*
1824
         * (non-Javadoc)
1825
         * @see org.gvsig.fmap.mapcontext.layers.FLyrDefault#cloneLayer()
1826
         */
1827
        public FLayer cloneLayer() throws Exception {
1828
                RasterDataStore  ds = getDataStore().cloneDataStore();
1829
                DefaultFLyrRaster newLayer = new DefaultFLyrRaster();
1830
                newLayer.setName(getName());
1831
                newLayer.setOpenRasterStore(ds);
1832
                newLayer.firstLoad = firstLoad;
1833
                
1834
                List<RasterFilter> filters = getRender().getFilterList().getStatusCloned();
1835

    
1836
                //Hacemos una copia de las bandas a renderizar
1837
                if(getRender().getRenderBands() != null) {
1838
                        int[] rb = new int[getRender().getRenderBands().length];
1839
                        for (int i = 0; i < rb.length; i++)
1840
                                rb[i] = getRender().getRenderBands()[i];
1841
                        newLayer.getRender().setRenderBands(rb);
1842
                }
1843

    
1844
                //Asignamos el entorno
1845
                if(newLayer.getRender().getFilterList() == null)
1846
                        newLayer.getRender().setFilterList(RasterLocator.getManager().createEmptyFilterList(getRender().getFilterList().getInitDataType()));
1847
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
1848
                newLayer.getRender().getFilterList().setStatus(filters);
1849

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

    
1887
        /*****************************************************/
1888

    
1889
        public void disableStopped() {
1890
                if(state != null)
1891
                        state.disableStopped();
1892
        }
1893

    
1894
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1895

    
1896
        public void enableClosed() throws NotAvailableStateException {
1897
                if(state != null)
1898
                        state.enableClosed();
1899
        }
1900

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

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

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

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

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

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

    
1913

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

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

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

    
1927
        /*
1928
         * (non-Javadoc)
1929
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getDataStore()
1930
         */
1931
        public RasterDataStore getDataStore() {
1932
                if(dataStore != null) {
1933
                        RasterDataParameters params = (RasterDataParameters)dataStore.getParameters();
1934
                        if (getCoordTrans() != null && params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
1935
                                this.dataStore.setCoordTrans(getCoordTrans());
1936
                        }
1937
                }
1938
                return this.dataStore;
1939
        }
1940
        
1941
        /*
1942
         * (non-Javadoc)
1943
         * @see org.cresques.geo.Projected#getProjection()
1944
         */
1945
        public IProjection getProjection() {
1946
                RasterDataParameters p = (RasterDataParameters)getDataStore().getParameters();
1947
                if(p.getReprojectionOption() == RasterDataParameters.DONT_CHANGE_PROJECTION)
1948
                        return null;
1949
                return getDataStore().getProjection();
1950
        }
1951

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

    
2003
        /**
2004
         * When a process is using information of this layer this variable will contain
2005
         * the thread ID.
2006
         * @param readingData
2007
         */
2008
        public synchronized void setReadingData(String readingData) {
2009
                this.readingData = readingData;
2010
        }
2011
        
2012
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel,
2013
                        boolean fast)
2014
                        throws LoadLayerException, DataException {
2015
                return null;
2016
        }
2017

    
2018
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel)
2019
                        throws LoadLayerException, DataException {
2020
                return null;
2021
        }
2022

    
2023
        @Override
2024
        protected void doDispose() throws BaseException {
2025
                if(render != null)
2026
                        render.dispose();
2027
                if(getDataStore() != null)
2028
                        getDataStore().dispose();
2029
                finalize();
2030
        }
2031

    
2032
        /*
2033
         * (non-Javadoc)
2034
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#getZoomLevel()
2035
         */
2036
        public int getZoomLevel() {
2037
                return zoomLevel;
2038
        }
2039

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

    
2122
        @Override
2123
        public void saveToState(PersistentState state) throws PersistenceException {
2124
                super.saveToState(state);
2125
                
2126
                //state.set("status", status);
2127
                state.set("rasterdatastore", getDataStore());        
2128
                state.set("legend", lastLegend);        
2129
                state.set("rois", rois);        
2130
                state.set("colortable", getRender().getColorTable());        
2131
                state.set("zoomLevel", zoomLevel);        
2132
                state.set("recalcLevel", recalcLevel);        
2133
        }        
2134
        
2135
        public static void registerPersistence() {
2136
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
2137
                DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
2138
                if( definition == null ) {
2139
                        if (manager.getDefinition(FLyrDefault.class) == null) {
2140
                                FLyrDefault.registerPersistent();
2141
                        }
2142
                        definition = manager.addDefinition(
2143
                                        DefaultFLyrRaster.class,
2144
                                        PERSISTENT_NAME,
2145
                                        PERSISTENT_DESCRIPTION,
2146
                                        null, 
2147
                                        null
2148
                        );
2149
                        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE, "FLyrDefault");
2150
                        
2151
                        registerPersistence(definition);
2152
                }
2153
        }
2154
        
2155
        public static void registerPersistence(DynStruct definition) {
2156
                //definition.addDynFieldObject("status").setClassOfValue(StatusLayerRaster.class).setMandatory(false);
2157
                definition.addDynFieldObject("rasterdatastore").setClassOfValue(RasterDataStore.class).setMandatory(true);
2158
                definition.addDynFieldObject("legend").setClassOfValue(ILegend.class).setMandatory(false);
2159
                definition.addDynFieldList("rois").setClassOfItems(ROI.class).setMandatory(false);
2160
                definition.addDynFieldObject("colortable").setClassOfValue(ColorTable.class).setMandatory(false);
2161
                definition.addDynFieldInt("zoomlevel").setMandatory(false);
2162
                definition.addDynFieldBoolean("recalcLevel").setMandatory(false);
2163
        }
2164

    
2165
        /*
2166
         * (non-Javadoc)
2167
         * @see org.gvsig.fmap.mapcontext.layers.operations.Classifiable#getGeometryType()
2168
         */
2169
        public GeometryType getGeometryType() throws ReadException {
2170
                try {
2171
                        return GeometryLocator.getGeometryManager().getGeometryType(TYPES.SURFACE, SUBTYPES.GEOM2D);
2172
                } catch (GeometryTypeNotSupportedException e) {
2173
                        throw new ReadException(getDataStore().getName(), e);
2174
                } catch (GeometryTypeNotValidException e) {
2175
                        throw new ReadException(getDataStore().getName(), e);
2176
                } 
2177
        }
2178
        
2179
        public void setDataStore(DataStore dataStore, String domain) throws LoadLayerException {
2180
                setDataStore(dataStore);
2181
        }
2182
        
2183
        /*
2184
         * (non-Javadoc)
2185
         * @see java.lang.Object#finalize()
2186
         */
2187
        protected void finalize() {
2188
                layerChangeSupport             = null;
2189
                state                          = null;
2190
                lastLegend                     = null;
2191
                colorTableLoadedFromProject    = null;
2192
                if(rois != null) {
2193
                        rois.clear();
2194
                        rois = null;
2195
                }
2196
                strategy                       = null;
2197
                configuration                  = null;
2198
                fileUtil                       = null;
2199
                rasterUtil                     = null;
2200
                crsUtil                        = null;
2201
                mathUtil                       = null;
2202
                uri                            = null;
2203
                affineTransformList            = null;
2204
                readingData                    = null;
2205
                dataStore                      = null;
2206
                render                         = null;
2207
        }
2208

    
2209
}