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

History | View | Annotate | Download (68.6 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
                getDataStore().setProjection(proj);
683
                super.setProjection(proj);
684
        }
685

    
686
        /*
687
         * (non-Javadoc)
688
         * @see org.gvsig.fmap.mapcontext.layers.FLayer#getFullEnvelope()
689
         */
690
        public Envelope getFullEnvelope() {
691
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
692
                //un extent aunque la capa no est? abierta
693
                if(/*!isOpen() || */getDataStore() == null || getDataStore().getExtent() == null)
694
                        return null;
695

    
696
                Rectangle2D e = getDataStore().getExtent().toRectangle2D();
697
                try {
698
                        return geomManager.createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
699
                                        .getMaxY(), SUBTYPES.GEOM2D);
700

    
701
                        /*
702
                        No es necesario 
703
                        ICoordTrans ct = getCoordTrans();
704
                        RasterDataParameters params = (RasterDataParameters)getDataStore().getParameters();
705
                        if (ct != null && params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
706
                                env = env.convert(ct);
707
                        }
708
                        return env;*/
709

    
710
                } catch (CreateEnvelopeException e1) {
711
                        logger.error("Error creating the envelope", e);
712
                        return null;
713
                }
714
        }
715
        
716
        /**
717
         * Obtiene el valor del pixel del Image en la posici?n x,y
718
         * @param x Posici?n x
719
         * @param y Posici?n y
720
         * @return valor de pixel
721
         */
722
//        public int[] getPixel(int pxx, int pxy) {
723
//                int[] argb = { -1, -1, -1, -1 };
724
//                if (!isOpen() || (image == null))
725
//                        return argb;
726
//                if (pxx >= 0 && pxx < image.getWidth() && pxy >= 0 && pxy < image.getHeight()) {
727
//                        int value = image.getRGB(pxx, pxy);
728
//                        argb[0] = ((value & 0xff000000) >> 24);
729
//                        argb[1] = ((value & 0x00ff0000) >> 16);
730
//                        argb[2] = ((value & 0x0000ff00) >> 8);
731
//                        argb[3] = (value & 0x000000ff);
732
//                }
733
//                return argb;
734
//        }
735

    
736
        /*
737
         * (non-Javadoc)
738
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
739
         */
740
        public double getMaxX() {
741
                if(getFullEnvelope() != null)
742
                        return getFullEnvelope().getMaximum(0);
743
                return -1;
744
        }
745

    
746
        /*
747
         * (non-Javadoc)
748
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
749
         */
750
        public double getMaxY() {
751
                if(getFullEnvelope() != null)
752
                        return this.getFullEnvelope().getMaximum(1);
753
                return -1;
754
        }
755

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

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

    
776
        /* (non-Javadoc)
777
         * @deprecated. See String getInfo(Point p) throws DriverException
778
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
779
         */
780
        public String queryByPoint(Point p) {
781
                if (!isOpen())
782
                        return null;
783
                ColorConversion conv = rManager.getColorConversion();
784

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

    
787
                ArrayList<Object> attr = getAttributes();
788
                data += "  <raster\n";
789
                data += "    File=\"" + getFile() + "\"\n";
790
                for (int i = 0; i < attr.size(); i++) {
791
                        Object[] a = (Object[]) attr.get(i);
792

    
793
                        data += "    " + a[0].toString() + "=";
794
                        if (a[1].toString() instanceof String)
795
                                data += "\"" + a[1].toString() + "\"\n";
796
                        else
797
                                data += a[1].toString() + "\n";
798
                }
799
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
800
                data += "    Point_WC=\"" + mathUtil.format(posXWC, 3) + " , " + mathUtil.format(posYWC, 3) + "\"\n";
801
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
802
                double[] cmyk = conv.RGBtoCMYK(r & 0xff, g & 0xff, b & 0xff, 1D);
803
                data += "    CMYK=\"" + mathUtil.format(cmyk[0], 4) + ", " + mathUtil.format(cmyk[1], 4) + ", " + mathUtil.format(cmyk[2], 4) + "," + mathUtil.format(cmyk[3], 4) + "\"\n";
804
                double[] hsl = conv.RGBtoHSL(r & 0xff, g & 0xff, b & 0xff);
805
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
806
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
807
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
808
                data += "    HSL=\"" + mathUtil.format(hsl[0], 4) + ", " + mathUtil.format(hsl[1], 4) + ", " + mathUtil.format(hsl[2], 4) + "\"\n";
809
                data += "  />\n";
810

    
811
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
812
                return data;
813
        }
814

    
815
        /**
816
         * Filters a string for being suitable as XML Tag, erasing
817
         * all not alphabetic or numeric characters.
818
         * @param s
819
         * @return string normalized
820
         */
821
        private String normalizeAsXMLTag(String s) {
822
                return s.replaceAll("[^a-zA-Z0-9]", "");
823
        }
824

    
825
        /*
826
         * (non-Javadoc)
827
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAttributes()
828
         */
829
        public ArrayList<Object> getAttributes() {
830
                ArrayList<Object> attr = new ArrayList<Object>();
831
                if(!isOpen())
832
                        return attr;
833
                Object [][] a = {
834
                        {"Filename", getDataStore().getName()},
835
                        {"Filesize", new Long(getDataStore().getFileSize())},
836
                        {"Width", new Integer((int)getDataStore().getWidth())},
837
                        {"Height", new Integer((int)getDataStore().getHeight())},
838
                        {"Bands", new Integer(getDataStore().getBandCount())}
839
                };
840
                for (int i = 0; i < a.length; i++)
841
                        attr.add(a[i]);
842
                return attr;
843
        }
844

    
845

    
846
        /* (non-Javadoc)
847
         * @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)
848
         */
849
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
850
                        double scale, PrintAttributes propeties) throws ReadException {
851

    
852
                if (/*!isOpen() ||*/ !isVisible() || !isWithinScale(scale))
853
                        return;
854
                
855
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
856
                SimpleTaskStatus taskStatus = new RasterTaskStatus("Printing raster " + getName() + "...", cancel);
857
                manager.add(taskStatus);
858
                taskStatus.setAutoremove(true);
859

    
860
                if (!mustTilePrint)
861
                        draw(null, g, viewPort, cancel,scale);
862
                else {
863
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
864
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
865
                        taskStatus.setRangeOfValues(0, tiles.getNumTiles());
866
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
867
                                // Parte que dibuja
868
                                try {
869
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
870
                                        draw(null, g, vp, cancel, scale);
871
                                        taskStatus.setCurValue(tileNr);
872
                                } catch (NoninvertibleTransformException e) {
873
                                        throw new ReadException("Error en la transformaci?n.", e);
874
                                } finally {
875
                                        taskStatus.terminate();
876
                                }
877
                        }
878
                }
879
                
880
                taskStatus.terminate();
881
        }
882

    
883
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
884
                        double scale) throws ReadException {
885
                if(!isOpen())
886
                        return;
887

    
888
                // Para no pedir imagenes demasiado grandes, vamos
889
                // a hacer lo mismo que hace EcwFile: chunkear.
890
                // Llamamos a drawView con cuadraditos m?s peque?os
891
                // del BufferedImage ni caso, cuando se imprime viene con null
892

    
893
                int numW, numH;
894
                int stepX, stepY;
895
                int xProv, yProv;
896
                int A = 1500;
897
                int H = 1500;
898
                int altoAux, anchoAux;
899

    
900
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
901

    
902
                // Vamos a hacerlo en trozos de AxH
903
                Rectangle r = g.getClipBounds();
904
                numW = (r.width) / A;
905
                numH = (r.height) / H;
906

    
907
                double[] srcPts = new double[8];
908
                double[] dstPts = new double[8];
909

    
910
                yProv = r.y;
911
                for (stepY = 0; stepY < numH + 1; stepY++) {
912
                        if ((yProv + H) > r.getMaxY())
913
                                altoAux = (int) r.getMaxY() - yProv;
914
                        else
915
                                altoAux = H;
916

    
917
                        xProv = r.x;
918
                        for (stepX = 0; stepX < numW + 1; stepX++) {
919
                                if ((xProv + A) > r.getMaxX())
920
                                        anchoAux = (int) r.getMaxX() - xProv;
921
                                else
922
                                        anchoAux = A;
923

    
924
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
925

    
926
                                // Parte que dibuja
927
                                srcPts[0] = xProv;
928
                                srcPts[1] = yProv;
929
                                srcPts[2] = xProv + anchoAux + 1;
930
                                srcPts[3] = yProv;
931
                                srcPts[4] = xProv + anchoAux + 1;
932
                                srcPts[5] = yProv + altoAux + 1;
933
                                srcPts[6] = xProv;
934
                                srcPts[7] = yProv + altoAux + 1;
935

    
936
                                try {
937
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
938
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
939
                                        // Extent extent = new Extent(rectCuadricula);
940

    
941
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
942
                                        ViewPort vp = (ViewPort)viewPort.clone();
943
                                        vp.setImageSize(tam);
944
                                        Envelope env = geomManager.createEnvelope(rectCuadricula
945
                                                        .getMinX(), rectCuadricula.getMinY(),
946
                                                        rectCuadricula.getMaxX(), rectCuadricula.getMaxY(),
947
                                                        SUBTYPES.GEOM2D);
948
                                        vp.setEnvelope(env);
949
                                        vp.setAffineTransform(mat);
950
                                        draw(null, g, vp, cancel, scale);
951

    
952
                                } catch (NoninvertibleTransformException e) {
953
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
954
                                } catch (ReadException e) {
955
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
956
                                } catch (CreateEnvelopeException e) {
957
                                        logger.error("Error creating the envelope", e);
958
                                } catch (CloneNotSupportedException e) {
959
                                        logger.error("Error cloning the viewport", e);
960
                                }
961
                                // Fin parte que dibuja
962
                                xProv = xProv + A;
963
                        }
964
                        yProv = yProv + H;
965
                }
966
        }
967

    
968
        /**
969
         * Borra de la lista de listeners el que se pasa como par?metro.
970
         *
971
         * @param o LayerListener a borrar.
972
         *
973
         * @return True si ha sido correcto el borrado del Listener.
974
         */
975
        public boolean removeLayerListener(LayerListener o) {
976
                if (this.isRemoveRasterFlag()) {
977
                        try {
978
                                enableClosed();
979
                        } catch (NotAvailableStateException e1) {
980
                                // No se ha podido cambiar el estado de la capa a cerrado
981
                        }
982
                }
983

    
984
                // Salva a RMF
985
                if (getDataStore() != null)
986
                        // Guardamos la GeoReferenciacion de cada dataset
987
                        try {
988
                                getDataStore().saveGeoreferencingToRmf();
989
                        } catch (Exception e) {
990
                                logger.info("error_salvando_rmf", e);
991
                        }
992

    
993
                        if (this.isRemoveRasterFlag()) {
994
                                if (getDataStore() != null) {
995
                                        String[] files = getFileName().clone();
996

    
997
                                        try {
998
                                                getDataStore().close();
999
                                        } catch (CloseException e) {
1000
                                        }
1001

    
1002
                                        dataStore = null;
1003
                                        if(render != null)
1004
                                                render.dispose();
1005
                                        render = null;
1006
                                        // System.gc();
1007
                                        this.setRemoveRasterFlag(true);
1008

    
1009
                                        for (int i = 0; i < files.length; i++) {
1010
                                                File file = new File(files[i]);
1011
                                                File dirTemp = fileUtil.getTemporalFile();
1012
                                                if(!file.exists())
1013
                                                        continue;
1014
                                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
1015
                                                        file.delete();
1016

    
1017
                                                        // Borramos todos los ficheros que puedan tener relacion con el fichero actual
1018
                                                        String basefile = file.getName();
1019
                                                        File basepath = file.getParentFile();
1020
                                                        int last = basefile.lastIndexOf(".");
1021
                                                        if (last != -1)
1022
                                                                basefile = basefile.substring(0, last + 1);
1023
                                                        File[] list = basepath.listFiles();
1024
                                                        for (int j = 0; j < list.length; j++)
1025
                                                                if (list[j].getName().startsWith(basefile))
1026
                                                                        list[j].delete();
1027
                                                }
1028
                                        }
1029
                                }
1030
                        }
1031
                        updateDrawVersion();
1032
                        return super.layerListeners.remove(o);
1033
        }
1034

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

    
1043
        /*
1044
         * (non-Javadoc)
1045
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setRemoveRasterFlag(boolean)
1046
         */
1047
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1048
                this.removeRasterFlag = removeRasterFlag;
1049
        }
1050

    
1051
        /*
1052
         * (non-Javadoc)
1053
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1054
         */
1055
        public String getTocImageIcon() {
1056
                return "map-ok-ico";
1057
        }
1058

    
1059
        /*
1060
         * (non-Javadoc)
1061
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getTileSize()
1062
         */
1063
        public int[] getTileSize() {
1064
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1065
                return size;
1066
        }
1067

    
1068
        /*
1069
         * (non-Javadoc)
1070
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isTiled()
1071
         */
1072
        public boolean isTiled() {
1073
                return mustTileDraw;
1074
        }
1075

    
1076
        /*
1077
         * (non-Javadoc)
1078
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isGeoreferenced()
1079
         */
1080
        public boolean isGeoreferenced() {
1081
                return getDataStore().isGeoreferenced();
1082
        }
1083

    
1084
        /*
1085
         * (non-Javadoc)
1086
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getNoDataValue()
1087
         */
1088
        public NoData getNoDataValue() {
1089
                return getDataStore().getNoDataValue();
1090
        }
1091

    
1092
        /**
1093
         * Sets the nodata value for this layer
1094
         * @param nd
1095
         */
1096
        public void setNoDataValue(NoData nd) {
1097
                if (getDataStore() != null)
1098
                        getDataStore().setNoDataValue(nd);
1099
        }
1100

    
1101
        /*
1102
         * (non-Javadoc)
1103
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getPxHeight()
1104
         */
1105
        public double getPxHeight() {
1106
                return getDataStore().getHeight();
1107
        }
1108

    
1109
        /*
1110
         * (non-Javadoc)
1111
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getPxWidth()
1112
         */
1113
        public double getPxWidth() {
1114
                return getDataStore().getWidth();
1115
        }
1116

    
1117
        /**
1118
         * Gets the height in world coordinates of this raster layer
1119
         */
1120
        public double getWCHeight() {
1121
                return getFullEnvelope().getMaximum(1);
1122
        }
1123

    
1124
        /**
1125
         * Gets the width in world coordinates of this raster layer
1126
         */
1127
        public double getWCWidth() {
1128
                return getFullEnvelope().getMaximum(0);
1129
        }
1130

    
1131
        /**
1132
         * Gets the size of all files of this raster layer
1133
         */
1134
        public long[] getFileSize() {
1135
                if (getDataStore() == null)
1136
                        return null;
1137

    
1138
                return getDataStore().getFileSizeByProvider();
1139
        }
1140

    
1141
        /**
1142
         * Gets the list of file names
1143
         */
1144
        public String[] getFileName() {
1145
                if (getDataStore() == null)
1146
                        return null;
1147

    
1148
                return getDataStore().getURIByProvider();
1149
        }
1150

    
1151
        /**
1152
         * Returns the number of files in this raster layer
1153
         */
1154
        public int getFileCount() {
1155
                return getDataStore().getProviderCount();
1156
        }
1157

    
1158
        /*
1159
         * (non-Javadoc)
1160
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileFormat()
1161
         */
1162
        public String getFileFormat() {
1163
                if(getDataStore().getSourceType() == RasterDataStore.FILE) {
1164
                        String fName = getDataStore().getName();
1165
                        int index = fName.lastIndexOf(".") + 1;
1166
                        String ext = null;
1167
                        if (index > 0)
1168
                                ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1169
                        return ext;
1170
                }
1171
                if(getDataStore().getSourceType() == RasterDataStore.POSTGIS) {
1172
                        return "POSTGIS";
1173
                }
1174
                return null;
1175
        }
1176

    
1177
        /*
1178
         * (non-Javadoc)
1179
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1180
         */
1181
        public int[] getDataType() {
1182
                return getDataStore().getDataType();
1183
        }
1184

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

    
1312
        /*
1313
         * (non-Javadoc)
1314
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getBandCountFromDataset()
1315
         */
1316
        public int[] getBandCountFromDataset() {
1317
                return getDataStore().getBandCountByProvider();
1318
        }
1319

    
1320
        /*
1321
         * (non-Javadoc)
1322
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1323
         */
1324
        public String getColorInterpretation(int band, int dataset) {
1325
                if (this.getDataStore().getColorInterpretation().get(band) == null)
1326
                        return "Undefined";
1327
                return this.getDataStore().getColorInterpretation().get(band);
1328
        }
1329

    
1330
        /*
1331
         * (non-Javadoc)
1332
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getWktProjection()
1333
         */
1334
        public String getWktProjection() throws RasterDriverException {
1335
                return getDataStore().getWktProjection();
1336
        }
1337

    
1338
        /*
1339
         * (non-Javadoc)
1340
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRGB()
1341
         */
1342
        public boolean isRGB() {
1343
                if ((getDataStore() == null) || (render == null))
1344
                        return false;
1345

    
1346
                if (getDataStore().getDataType()[0] != Buffer.TYPE_BYTE)
1347
                        return false;
1348

    
1349
                boolean R = false;
1350
                boolean G = false;
1351
                boolean B = false;
1352

    
1353
                int[] renderBands = render.getRenderBands();
1354
                for (int i = 0; i < renderBands.length; i++)
1355
                        if (renderBands[i] >= 0)
1356
                                switch (i) {
1357
                                        case 0:
1358
                                                R = true;
1359
                                                break;
1360
                                        case 1:
1361
                                                G = true;
1362
                                                break;
1363
                                        case 2:
1364
                                                B = true;
1365
                                                break;
1366
                                }
1367

    
1368
                if (R && G && B)
1369
                        return true;
1370

    
1371
                return false;
1372
        }
1373

    
1374
        /**
1375
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1376
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1377
         * cacheado o no dependiendo del tama?o de esta.
1378
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1379
         * @return Grid.
1380
         * @throws InterruptedException
1381
         */
1382
        public Grid getFullGrid(boolean interpolated) throws GridException, InterruptedException {
1383
                RasterQuery query = rManager.createQuery();
1384
                query.setAllDrawableBands();
1385
                Buffer bf = null;
1386
                try {
1387
                        query.setAreaOfInterest();
1388
                        bf = getDataStore().query(query);
1389
                } catch (RasterDriverException e) {
1390
                        throw new GridException("Error reading buffer");
1391
                } catch (ProcessInterruptedException e) {
1392
                        throw new InterruptedException("Carga interrumpida");
1393
                } catch (InvalidSetViewException e) {
1394
                        throw new GridException("Error reading buffer");
1395
                }
1396
                return rManager.createGrid(bf, getDataStore(), interpolated);
1397
        }
1398

    
1399
        /*
1400
         * (non-Javadoc)
1401
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getReadOnlyFullGrid(boolean)
1402
         */
1403
        public Grid getReadOnlyFullGrid(boolean interpolated) throws GridException, InterruptedException {
1404
                RasterQuery query = rManager.createQuery();
1405
                query.setReadOnly(true);
1406
                query.setAllDrawableBands();
1407
                Buffer bf = null;
1408
                try {
1409
                        query.setAreaOfInterest();
1410
                        bf = getDataStore().query(query);
1411
                } catch (RasterDriverException e) {
1412
                        throw new GridException("Error reading buffer");
1413
                } catch (ProcessInterruptedException e) {
1414
                        throw new InterruptedException("Carga interrumpida");
1415
                } catch (InvalidSetViewException e) {
1416
                        throw new GridException("Error reading buffer");
1417
                }
1418
                return rManager.createGrid(bf, getDataStore(), interpolated);
1419
        }
1420

    
1421
        /**
1422
         * Obtiene el tama?o de celda de la fuente de datos
1423
         * @return double con el tama?o de celda
1424
         */
1425
        public double getCellSize() {
1426
                return (getDataStore() != null) ? getDataStore().getCellSize() : 1;
1427
        }
1428

    
1429
        /*
1430
         * (non-Javadoc)
1431
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFullRasterExtent()
1432
         */
1433
        public Extent getFullRasterExtent() {
1434
                return this.getDataStore().getExtent();
1435
        }
1436

    
1437

    
1438
        /**
1439
         * Devuelve el fichero asociado a la capa o null si no tiene.
1440
         * @return Fichero.
1441
         */
1442
        public File getFile() {
1443
                if(getDataStore().getParameters() instanceof RasterFileStoreParameters)
1444
                        return ((RasterFileStoreParameters)getDataStore().getParameters()).getFile();
1445
                return new File("");
1446
        }
1447

    
1448
        /**
1449
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1450
         * @param file Fichero a consultar
1451
         * @return true si es aceptado y false si no lo es.
1452
         */
1453
        public boolean isFileAccepted(File file) {
1454
                return getDataStore().isFileSupported(file.getName());
1455
        }
1456
        
1457
        /**
1458
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1459
         * @param file Fichero a consultar
1460
         * @return true si es aceptado y false si no lo es.
1461
         */
1462
        public static boolean isFileSupported(File file) {
1463
                return RasterLocator.getManager().isExtensionSupported(file.getName());
1464
        }
1465

    
1466
        /*
1467
         * (non-Javadoc)
1468
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#existColorTable()
1469
         */
1470
        public boolean existColorTable() {
1471
                return getRender().existColorTable();
1472
        }
1473

    
1474
        /**
1475
         * Returns true if the data store has an alpha band
1476
         */
1477
        public boolean existsAlphaBand() {
1478
                if(getDataStore().getColorInterpretation() != null)
1479
                        return getDataStore().getColorInterpretation().hasAlphaBand();
1480
                else
1481
                        return false;
1482
        }
1483

    
1484
        /*
1485
         * (non-Javadoc)
1486
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAlphaBandNumber()
1487
         */
1488
        public int getAlphaBandNumber() {
1489
                if(getDataStore().getColorInterpretation() != null)
1490
                        return getDataStore().getColorInterpretation().getBand(ColorInterpretation.ALPHA_BAND);
1491
                return -1;
1492
        }
1493

    
1494
        /**
1495
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1496
         * capa busque una leyenda valida.
1497
         * @param ct
1498
         */
1499
        public void setLastLegend(ColorTable ct) {
1500
                lastLegend = ColorTableLegend.createLegend(ct);
1501
        }
1502

    
1503
        /**
1504
         * Devuelve la Leyenda de la capa.
1505
         * @return Leyenda.
1506
         */
1507
        public ILegend getLegend() {
1508
                if (lastLegend != null)
1509
                        return lastLegend;
1510

    
1511
                return null;
1512
        }
1513

    
1514
        /*
1515
         * (non-Javadoc)
1516
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1517
         */
1518
        public void addLegendListener(LegendListener listener) {
1519
                layerChangeSupport.addLayerListener(listener);
1520
        }
1521

    
1522
        /*
1523
         *  (non-Javadoc)
1524
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1525
         */
1526
        public int getShapeType() {
1527
                return TYPES.SURFACE;
1528
        }
1529

    
1530
        /*
1531
         * (non-Javadoc)
1532
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1533
         */
1534
        public void removeLegendListener(LegendListener listener) {
1535
                if(layerChangeSupport != null)
1536
                        layerChangeSupport.removeLayerListener(listener);
1537
        }
1538

    
1539
        /*
1540
         * (non-Javadoc)
1541
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isInside(java.awt.geom.Point2D)
1542
         */
1543
        public boolean isInside(Point2D p) {
1544
                 return getDataStore().isInside(p);
1545
        }
1546

    
1547
        /*
1548
         * (non-Javadoc)
1549
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAffineTransform()
1550
         */
1551
        public AffineTransform getAffineTransform() {
1552
                return getDataStore().getAffineTransform();
1553
        }
1554

    
1555
        /*
1556
         * (non-Javadoc)
1557
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setAffineTransform(java.awt.geom.AffineTransform)
1558
         */
1559
        public void setAffineTransform(AffineTransform transf) {
1560
                if(transf == null)
1561
                        return;
1562
                affineTransformList.add(transf);
1563
                getDataStore().setAffineTransform(transf);
1564
                updateDrawVersion();
1565
        }
1566

    
1567
        /*
1568
         * (non-Javadoc)
1569
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setAffineTransformWithoutHistorical(java.awt.geom.AffineTransform)
1570
         */
1571
        public void setAffineTransformWithoutHistorical(AffineTransform transf) {
1572
                getDataStore().setAffineTransform(transf);
1573
                updateDrawVersion();
1574
        }
1575

    
1576
        /*
1577
         * (non-Javadoc)
1578
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAffineTransformHistorical()
1579
         */
1580
        public Historical getAffineTransformHistorical() {
1581
                return this.affineTransformList;
1582
        }
1583

    
1584
        /*
1585
         * (non-Javadoc)
1586
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#saveGeoToRmf()
1587
         */
1588
        public void saveGeoToRmf() throws RmfSerializerException {
1589
                if (!isOpen())
1590
                        return;
1591

    
1592
                getDataStore().saveGeoreferencingToRmf();
1593
                
1594
                affineTransformList.clear();
1595
                affineTransformList.add(this.getAffineTransform());
1596
        }
1597

    
1598
        /*
1599
         * (non-Javadoc)
1600
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1601
         */
1602
        public boolean isActionEnabled(int action) {
1603
                switch (action) {
1604
                        case IRasterLayerActions.BANDS_FILE_LIST:
1605
                                if (existColorTable() || getDataStore().isMosaic() || getDataStore().isTiled())
1606
                                        return false;
1607
                                break;
1608
                        case IRasterLayerActions.BANDS_RGB:
1609
                                if (existColorTable())
1610
                                        return false;
1611
                                break;
1612
                        case IRasterLayerActions.REPROJECT:
1613
                                if (!isReproyectable())
1614
                                        return false;
1615
                                break;
1616
                        case IRasterLayerActions.CREATEOVERVIEWS:
1617
                                return overviewsSupport();
1618
                        case IRasterLayerActions.OPACITY:
1619
                        case IRasterLayerActions.TRANSPARENCY:
1620
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1621
                        case IRasterLayerActions.ENHANCED:
1622
                        case IRasterLayerActions.PANSHARPENING:
1623
                        case IRasterLayerActions.SELECT_LAYER:
1624
                        case IRasterLayerActions.SAVE_COLORINTERP:
1625
                                return true;
1626
                        case IRasterLayerActions.REMOTE_ACTIONS:
1627
                                return false;
1628
                        case IRasterLayerActions.TAILTRIM:
1629
                        case IRasterLayerActions.GEOLOCATION:
1630
                                return !(getDataStore().isTiled());
1631
                }
1632
                return true;
1633
        }
1634

    
1635
        /*
1636
         * (non-Javadoc)
1637
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1638
         */
1639
        public void setVisible(boolean visibility) {
1640
                if(visibility)
1641
                        state.disableStopped();
1642
                else
1643
                        enableStopped();
1644

    
1645
                if(isAwake() || isClosed())
1646
                        try {
1647
                                this.load();
1648
                        } catch (LoadLayerException e) {
1649
                                e.printStackTrace();
1650
                        }
1651

    
1652
                /*
1653
                 * Cuando se modifica la visibilidad de una capa raster se hace un updateDrawVersion de todas las
1654
                 * capas raster de ese MapContext. Esto es porque la estrategia utilizada por RasterDrawStrategy hace
1655
                 * que se cacheen en blanco las capas raster que est?n ocultas debajo de otras. Al hacer invisibles las
1656
                 * de arriba la cache que estaba en blanco hace que no se pinte nada. Para evitar esto las marcamos todas
1657
                 * como que han sido modificadas para que se vuelvan a leer.
1658
                 */
1659
                if(getMapContext() != null) {
1660
                        ArrayList<FLayer> listLayers = new ArrayList<FLayer>();
1661
                        listLayers = RasterDrawStrategy.getLayerList(getMapContext().getLayers(), listLayers);
1662
                        for (int i = 0; i < listLayers.size(); i++)
1663
                                if(listLayers.get(i) instanceof DefaultFLyrRaster)
1664
                                        ((DefaultFLyrRaster)listLayers.get(i)).updateDrawVersion();
1665
                }
1666

    
1667
                super.setVisible(visibility);
1668
        }
1669

    
1670
        /**
1671
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1672
         * @return valor de transparencia
1673
         */
1674
        public int getTransparency() {
1675
                try {
1676
                        return getRender().getLastTransparency().getOpacity();
1677
                } catch (NullPointerException e) {
1678
                        return super.getTransparency();
1679
                }
1680
        }
1681

    
1682
        /**
1683
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1684
         * o no.
1685
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1686
         */
1687
        public boolean isTransparent() {
1688
                return getRender().getLastTransparency().isTransparencyActive();
1689
        }
1690

    
1691
        /**
1692
         * Asigna la transparencia de la siguiente renderizaci?n
1693
         * @param valor de transparencia
1694
         */
1695
        public void setTransparency(int trans) {
1696
                super.setTransparency(trans);
1697
                try {
1698
                        getRender().getLastTransparency().setOpacity(trans);
1699
                } catch (NullPointerException e) {
1700
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1701
                }
1702
        }
1703

    
1704
        /**
1705
         *
1706
         * @return ROIs asociadas a la capa raster.
1707
         */
1708
        public ArrayList<ROI> getRois() {
1709
                return rois;
1710
        }
1711

    
1712
        /**
1713
         * Establece las ROI asociadas a la capa raster.
1714
         *
1715
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1716
         */
1717
        public void setRois(ArrayList<ROI> rois) {
1718
                this.rois = rois;
1719
        }
1720

    
1721
        /**
1722
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1723
         * devolver? null.
1724
         * @return TreeMap con la lista de capas a dibujar
1725
         */
1726
        public HashMap<DefaultFLyrRaster, Boolean> getRasterStrategy() {
1727
                if(strategy != null)
1728
                        return strategy.getStrategy();
1729
                return null;
1730
        }
1731

    
1732
        /**
1733
         * @return the configuration
1734
         */
1735
        static public IConfiguration getConfiguration() {
1736
                return configuration;
1737
        }
1738

    
1739
        /**
1740
         * @param configuration the configuration to set
1741
         */
1742
        static public void setConfiguration(IConfiguration configuration) {
1743
                DefaultFLyrRaster.configuration = configuration;
1744
        }
1745

    
1746
        /*
1747
         * (non-Javadoc)
1748
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#reload()
1749
         */
1750
        public void reload() throws ReloadLayerException {
1751
                try {
1752
                        super.reload();
1753
                        if (getMapContext() == null)
1754
                                return;
1755
                        if (isStopped())
1756
                                disableStopped();
1757
                        load();
1758
                        getMapContext().invalidate();
1759
                } catch (LoadLayerException e) {
1760
                        setAvailable(false);
1761
                        throw new ReloadLayerException(getName(), e);
1762
                }
1763
        }
1764

    
1765
        /**
1766
         * Devuelve si la capa tiene soporte para poder generar overviews
1767
         * @return
1768
         */
1769
        public boolean overviewsSupport() {
1770
                if ((getDataStore() != null) && (getDataStore().overviewsSupport()))
1771
                        return true;
1772

    
1773
                return false;
1774
        }
1775

    
1776
        /**
1777
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1778
         * en escala de grises
1779
         * @return
1780
         */
1781
        public boolean isRenderingAsGray() {
1782
                int[] renderBands = getRender().getRenderBands();
1783
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1784
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1785
                        return true;
1786
                return false;
1787
        }
1788

    
1789
        /*
1790
         * (non-Javadoc)
1791
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
1792
         */
1793
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1794
                updateDrawVersion();
1795
        }
1796

    
1797
        /*
1798
         * (non-Javadoc)
1799
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#adjustWorldRequest(java.awt.geom.Point2D)
1800
         */
1801
        public Point2D adjustWorldRequest(Point2D req) {
1802
                Envelope ext = null;
1803

    
1804
                ext = getFullEnvelope();
1805
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
1806
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
1807
                return req;
1808
        }
1809

    
1810
        /*
1811
         * (non-Javadoc)
1812
         * @see org.gvsig.fmap.mapcontext.layers.FLyrDefault#cloneLayer()
1813
         */
1814
        public FLayer cloneLayer() throws Exception {
1815
                RasterDataStore  ds = getDataStore().cloneDataStore();
1816
                DefaultFLyrRaster newLayer = new DefaultFLyrRaster();
1817
                newLayer.setName(getName());
1818
                newLayer.setOpenRasterStore(ds);
1819
                newLayer.firstLoad = firstLoad;
1820
                
1821
                List<RasterFilter> filters = getRender().getFilterList().getStatusCloned();
1822

    
1823
                //Hacemos una copia de las bandas a renderizar
1824
                if(getRender().getRenderBands() != null) {
1825
                        int[] rb = new int[getRender().getRenderBands().length];
1826
                        for (int i = 0; i < rb.length; i++)
1827
                                rb[i] = getRender().getRenderBands()[i];
1828
                        newLayer.getRender().setRenderBands(rb);
1829
                }
1830

    
1831
                //Asignamos el entorno
1832
                if(newLayer.getRender().getFilterList() == null)
1833
                        newLayer.getRender().setFilterList(RasterLocator.getManager().createEmptyFilterList(getRender().getFilterList().getInitDataType()));
1834
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
1835
                newLayer.getRender().getFilterList().setStatus(filters);
1836

    
1837
                // Asignamos los valores noData del original
1838
                newLayer.setNoDataValue(getNoDataValue());
1839
                if(getDataStore().getNoDataValue().isDefined())
1840
                        newLayer.setNoDataTransparent(true);
1841
                newLayer.enableOpen();
1842
                
1843
                return newLayer;
1844
        }
1845
        
1846
        /*
1847
         * (non-Javadoc)
1848
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileLayer()
1849
         */
1850
        public FLayer getFileLayer() throws RasterDriverException {
1851
                try {
1852
                        return cloneLayer();
1853
                } catch (Exception e) {
1854
                }
1855
                return null;
1856
        }
1857
        
1858
        /*
1859
         * (non-Javadoc)
1860
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#addFile(java.lang.String)
1861
         */
1862
        public void addFile(String file) throws InvalidSourceException {
1863
                getDataStore().addFile(file);
1864
        }
1865
        
1866
        /*
1867
         * (non-Javadoc)
1868
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#removeFile(java.lang.String)
1869
         */
1870
        public void removeFile(String file) {
1871
                getDataStore().removeFile(file);
1872
        }
1873

    
1874
        /*****************************************************/
1875

    
1876
        public void disableStopped() {
1877
                if(state != null)
1878
                        state.disableStopped();
1879
        }
1880

    
1881
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1882

    
1883
        public void enableClosed() throws NotAvailableStateException {
1884
                if(state != null)
1885
                        state.enableClosed();
1886
        }
1887

    
1888
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1889

    
1890
        public void enableStopped() {state.enableStopped();}
1891

    
1892
        public boolean isAwake() {return state.isAwake();}
1893

    
1894
        public boolean isClosed() {return state.isClosed();}
1895

    
1896
        public boolean isOpen() {return state.isOpen();}
1897

    
1898
        public boolean isStopped() {return state.isStopped();}
1899

    
1900

    
1901
        @SuppressWarnings("unchecked")
1902
        public Set getMetadataChildren() {
1903
                return null;
1904
        }
1905

    
1906
        public Object getMetadataID() {
1907
                return getName();
1908
        }
1909

    
1910
        public String getMetadataName() {
1911
                return null;
1912
        }
1913

    
1914
        /*
1915
         * (non-Javadoc)
1916
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getDataStore()
1917
         */
1918
        public RasterDataStore getDataStore() {
1919
                if(dataStore != null) {
1920
                        RasterDataParameters params = (RasterDataParameters)dataStore.getParameters();
1921
                        if (getCoordTrans() != null && params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
1922
                                this.dataStore.setCoordTrans(getCoordTrans());
1923
                        }
1924
                }
1925
                return this.dataStore;
1926
        }
1927
        
1928
        /*
1929
         * (non-Javadoc)
1930
         * @see org.cresques.geo.Projected#getProjection()
1931
         */
1932
        public IProjection getProjection() {
1933
                RasterDataParameters p = (RasterDataParameters)getDataStore().getParameters();
1934
                if(p.getReprojectionOption() == RasterDataParameters.DONT_CHANGE_PROJECTION)
1935
                        return null;
1936
                return getDataStore().getProjection();
1937
        }
1938

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

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

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

    
2003
        @Override
2004
        protected void doDispose() throws BaseException {
2005
                if(render != null)
2006
                        render.dispose();
2007
                if(getDataStore() != null)
2008
                        getDataStore().dispose();
2009
                finalize();
2010
        }
2011

    
2012
        /*
2013
         * (non-Javadoc)
2014
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#getZoomLevel()
2015
         */
2016
        public int getZoomLevel() {
2017
                return zoomLevel;
2018
        }
2019

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

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

    
2145
        /*
2146
         * (non-Javadoc)
2147
         * @see org.gvsig.fmap.mapcontext.layers.operations.Classifiable#getGeometryType()
2148
         */
2149
        public GeometryType getGeometryType() throws ReadException {
2150
                try {
2151
                        return GeometryLocator.getGeometryManager().getGeometryType(TYPES.SURFACE, SUBTYPES.GEOM2D);
2152
                } catch (GeometryTypeNotSupportedException e) {
2153
                        throw new ReadException(getDataStore().getName(), e);
2154
                } catch (GeometryTypeNotValidException e) {
2155
                        throw new ReadException(getDataStore().getName(), e);
2156
                } 
2157
        }
2158
        
2159
        public void setDataStore(DataStore dataStore, String domain) throws LoadLayerException {
2160
                setDataStore(dataStore);
2161
        }
2162
        
2163
        /*
2164
         * (non-Javadoc)
2165
         * @see java.lang.Object#finalize()
2166
         */
2167
        protected void finalize() {
2168
                layerChangeSupport             = null;
2169
                state                          = null;
2170
                lastLegend                     = null;
2171
                colorTableLoadedFromProject    = null;
2172
                if(rois != null) {
2173
                        rois.clear();
2174
                        rois = null;
2175
                }
2176
                strategy                       = null;
2177
                configuration                  = null;
2178
                fileUtil                       = null;
2179
                rasterUtil                     = null;
2180
                crsUtil                        = null;
2181
                mathUtil                       = null;
2182
                uri                            = null;
2183
                affineTransformList            = null;
2184
                readingData                    = null;
2185
                dataStore                      = null;
2186
                render                         = null;
2187
        }
2188

    
2189
}