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

History | View | Annotate | Download (62.2 KB)

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

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

    
40
import org.cresques.cts.IProjection;
41
import org.gvsig.compat.print.PrintAttributes;
42
import org.gvsig.fmap.crs.CRSFactory;
43
import org.gvsig.fmap.dal.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.ROIException;
65
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
66
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
67
import org.gvsig.fmap.dal.coverage.grid.Grid;
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.Geometry.SUBTYPES;
96
import org.gvsig.fmap.geom.Geometry.TYPES;
97
import org.gvsig.fmap.geom.GeometryLocator;
98
import org.gvsig.fmap.geom.GeometryManager;
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.roi.ROI;
121
import org.gvsig.raster.util.RasterNotLoadException;
122
import org.gvsig.tools.ToolsLocator;
123
import org.gvsig.tools.dynobject.DynClass;
124
import org.gvsig.tools.dynobject.DynObjectManager;
125
import org.gvsig.tools.dynobject.DynObjectSet;
126
import org.gvsig.tools.dynobject.DynStruct;
127
import org.gvsig.tools.exception.BaseException;
128
import org.gvsig.tools.persistence.PersistenceManager;
129
import org.gvsig.tools.persistence.PersistentState;
130
import org.gvsig.tools.persistence.exception.PersistenceException;
131
import org.gvsig.tools.task.Cancellable;
132
import org.gvsig.tools.task.SimpleTaskStatus;
133
import org.gvsig.tools.task.TaskStatusManager;
134
import org.gvsig.tools.task.impl.BaseTaskStatus;
135
import org.slf4j.Logger;
136
import org.slf4j.LoggerFactory;
137

    
138
/**
139
 * Raster layer
140
 * 
141
 * @author Nacho Brodin (nachobrodin@gmail.com)
142
 */
143
@SuppressWarnings("deprecation")
144
public class DefaultFLyrRaster extends FLyrDefault implements FLyrRaster, Multiresolution, InfoByPoint, Classifiable,
145
                IRasterLayerActions, ILayerState, VisualPropertyListener, SingleLayer {
146
        public static final String      PERSISTENT_NAME                = "FLyrRasterSE_Persistent";
147
    public static final String      PERSISTENT_DESCRIPTION         = "FLyrRasterSE Persistent";
148
    private RasterManager           rManager                       = RasterLocator.getManager();
149
        private boolean                 mustTileDraw                   = false;
150
        private boolean                 mustTilePrint                  = true;
151
        private int                     maxTileDrawWidth               = 200;
152
        private int                     maxTileDrawHeight              = 200;
153
        private int                     maxTilePrintWidth              = 1500;
154
        private int                     maxTilePrintHeight             = 1500;
155
        private boolean                 firstLoad                      = false;
156
        private boolean                 removeRasterFlag               = true;
157
        protected RasterDataStore       dataStore                      = null;
158
        protected Render                render                         = null;
159
        private int                     posX                           = 0;
160
        private int                     posY                           = 0;
161
        private double                  posXWC                         = 0;
162
        private int                     posYWC                         = 0;
163
        private int                     r                              = 0;
164
        private int                     g                              = 0;
165
        private int                     b                              = 0;
166
        private LayerChangeSupport      layerChangeSupport             = new LayerChangeSupport();
167
        private FLyrState               state                          = new FLyrState();
168
        protected ILegend               lastLegend                     = null;
169
        protected ColorTable            colorTableLoadedFromProject    = null;
170
        protected boolean               loadedFromProject              = false;
171
        private 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
        public class RasterTaskStatus extends BaseTaskStatus {
185
                Cancellable c = null;
186
                
187
                public RasterTaskStatus(String tittle, Cancellable c) {
188
                        super(tittle);
189
                        this.c = c;
190
                }
191
                
192
                public boolean isCancellationRequested() {
193
                        if(c != null)
194
                                return this.c.isCanceled();
195
                        return false;
196
                }
197
                
198
                public void cancelRequest() {
199
                        if(c != null)
200
                                this.c.setCanceled(true);
201
                }
202
        }
203

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

    
247
                return lyr;
248
        }
249

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

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

    
267
        public void wakeUp(){
268
                try {
269
                        reload();
270
                } catch (ReloadLayerException e) {
271
                        // No se ha podido recuperar la capa con exito
272
                }
273
        }
274

    
275
        public void load() throws LoadLayerException {
276
                if (isStopped() || getDataStore() == null)
277
                        return;
278

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

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

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

    
303
                try {
304
                        if(!getDataStore().isOpen())
305
                                dataStore = rManager.getProviderServices().open(params);
306
                        else
307
                                dataStore.reload();
308
                } catch (NotSupportedExtensionException e) {
309
                        throw new LoadLayerException(this.getName());
310
                } catch (RasterDriverException e) {
311
                        throw new LoadLayerException(this.getName());
312
                }
313
        }
314

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

    
328
                render = getDataStore().getRender();
329
                render.addVisualPropertyListener(this);
330
                initFilters();
331

    
332
                //Inicializaci?n del historico de transformaciones
333
                affineTransformList.clear();
334
                affineTransformList.add(this.getAffineTransform());
335

    
336
                try {
337
                        if(!isOpen())
338
                                enableOpen();
339
                } catch (NotAvailableStateException e) {
340
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Awake=" + isAwake(), e);
341
                }
342
        }
343

    
344
        public IProjection readProjection() throws RasterDriverException {
345
                try {
346
                        crsUtil.setCRSFactory(CRSFactory.cp);
347
                        if( getDataStore() == null )
348
                                return null;
349
                        return crsUtil.convertWktToIProjection(getDataStore().getWktProjection());
350
                } catch (Exception e) {
351
                        throw new RasterDriverException("Problems converting from WKT to IProjection", e);
352
                } catch (Error e) {
353
                        e.printStackTrace();
354
                        return null;
355
                }
356
        }
357

    
358
        /**
359
         * Crea el objeto renderizador de raster
360
         * @return Rendering
361
         */
362
        public Render getRender() {
363
                if (render == null) {
364
                        if(getDataStore() != null) {
365
                                render = getDataStore().getRender();
366
                                render.addVisualPropertyListener(this);
367
                        }
368
                }
369
                return render;
370
        }
371
        
372
        public String getURI() {
373
                return uri;
374
        }
375

    
376
        public void setNoDataTransparent(boolean t) {
377
                getNoDataValue().setNoDataTransparent(t);
378
                if(getRender().getLastTransparency() != null) {
379
                        getRender().getLastTransparency().setNoData(getDataStore().getNoDataValue());
380
                        getRender().getLastTransparency().activeTransparency();
381
                }
382
        }
383

    
384
        /**
385
         * Initializes the filter list to render this raster layer
386
         * @throws FilePaletteException 
387
         */
388
        protected void initFilters() throws FilePaletteException {
389
                if(getDataType() == null)
390
                        return;
391
                        
392
                RasterFilterList filterList = rManager.createEmptyFilterList(getDataType()[0]);
393
                if(loadedFromProject) {
394
                        filterList = getDataStore().getRender().getFilterList();
395
                }
396
                filterList.addEnvParam("IStatistics", getDataStore().getStatistics());
397
                filterList.addEnvParam("MultiRasterDataset", getDataStore());
398

    
399
                if(getDataStore() == null)
400
                        return;
401
                
402
                if(getDataStore().getNoDataValue() != null) {
403
                        getDataStore().getNoDataValue().load();
404
                        if(getDataStore().getNoDataValue().isDefined())
405
                                setNoDataTransparent(true);
406
                }
407

    
408
                filterList.setInitDataType(getDataType()[0]);
409

    
410
                // Quitamos la leyenda
411
                lastLegend = null;
412

    
413
                try {
414
                        //Si en la carga del proyecto se carg? una tabla de color asignamos esta
415
                        if(colorTableLoadedFromProject != null) {
416
                                setLastLegend(colorTableLoadedFromProject);
417
                                RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
418
                                Params params = filterList.createEmptyFilterParams();
419
                                params.setParam("colorTable", colorTableLoadedFromProject);
420
                                colorTableManager.addFilter(params);
421
                        } else
422
                                //sino ponemos la tabla asociada al raster
423
                                if (getDataStore().getColorTable() != null) {
424
                                        ColorTable table = getDataStore().getColorTable();
425
                                        setLastLegend(table);
426
                                        RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
427
                                        Params params = filterList.createEmptyFilterParams();
428
                                        params.setParam("colorTable", table);
429
                                        colorTableManager.addFilter(params);
430
                                } else //sino hace lo que dice en las preferencias
431
                                        if(getDataStore().needEnhanced() || 
432
                                                        (loadedFromProject && filterList.get("enhanced_stretch") != null)) 
433
                                                loadEnhancedOrColorTable(filterList);
434
                        colorTableLoadedFromProject = null;
435

    
436
                        getRender().setFilterList(filterList);
437
                        // Inicializo la transparencia para el render
438
                        if(!loadedFromProject) {
439
                                getRender().setLastTransparency(getDataStore().getTransparency().cloneTransparency());
440
                        }
441
                        loadedFromProject = false;
442
                } catch (FilterTypeException e) {
443
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
444
                        logger.error("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
445
                } catch (FilterManagerException e) {
446
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
447
                        logger.error("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
448
                }
449
        }
450

    
451
        /**
452
         * Mira la configuracion para saber si debe cargar un realce o una tabla
453
         * de color por defecto
454
         * @param filterManager
455
         * @throws FilterTypeException
456
         * @throws FilePaletteException 
457
         */
458
        private void loadEnhancedOrColorTable(RasterFilterList filterList) throws FilterTypeException, FilterManagerException, FilePaletteException {
459
                String colorTableName = null;
460
                if(configuration != null)
461
                        colorTableName = configuration.getValueString("loadlayer_usecolortable", (String) null);
462

    
463
                String palettesPath = System.getProperty("user.home") +
464
                File.separator +
465
                "gvSIG" + // PluginServices.getArguments()[0] +
466
                File.separator + "colortable";
467

    
468
                Statistics stats = getDataStore().getStatistics();
469
                ColorTableLibrary colorTableLibrary = rManager.getDataStructFactory().getColorTableLibrary();
470

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

    
483
                                                        ColorTable colorTable = colorTableLibrary.createColorTable();
484
                                                        colorTable.setName(paletteName);
485
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
486
                                                        colorTable.setInterpolated(true);
487

    
488
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
489

    
490
                                                        setLastLegend(colorTable);
491

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

    
508
                        RasterFilterListManager enhancementManager = filterList.getManagerByID("EnhancementStretch");
509
                        RasterFilter f = filterList.getByName("enhanced_stretch");
510
                        if(f == null) {
511
                                Params params = filterList.createEmptyFilterParams();
512
                                params.setParam("stats", stats);
513
                                params.setParam("remove", new Boolean(false));
514
                                params.setParam("renderBands", getRender().getRenderBands());
515
                                params.setParam("stretchs", null);//coge el LinearStretchParams por defecto
516
                                params.setParam("rgb", new Boolean(true));
517
                                enhancementManager.addFilter(params);
518
                        }
519
        }
520

    
521
        public boolean isReproyectable() {
522
                if (getDataStore() == null)
523
                        return false;
524
                return getDataStore().isReproyectable();
525
        }
526

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

    
549
                try {
550
                        if (!isOpen())
551
                                return;
552

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

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

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

    
606
                        }
607
                        
608
                        //callLegendChanged(null);
609
                } finally {
610
                        disableStopped();
611
                        task.setEvent(null);
612
                }
613
        }
614

    
615
        protected void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws RasterDriverException, InvalidSetViewException, InterruptedException {
616
                Envelope adjustedExtent = vp.getAdjustedExtent();
617
                if (adjustedExtent == null)
618
                        return;
619
                Extent e = rManager.getDataStructFactory().createExtent(adjustedExtent.getLowerCorner().getX(),
620
                                adjustedExtent.getUpperCorner().getY(), adjustedExtent
621
                                                .getUpperCorner().getX(),
622
                                adjustedExtent
623
                                                .getLowerCorner().getY());
624
                Dimension imgSz = vp.getImageSize();
625
                ViewPortData vp2 = rManager.getDataStructFactory().createViewPortData(vp.getProjection(), e, imgSz );
626
                vp2.setMat(vp.getAffineTransform());
627
                //vp2.setTime(vp.getTime()); 
628
                
629
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
630
                SimpleTaskStatus taskStatus = new RasterTaskStatus("Drawing " + getName() + "...", cancel);
631
                manager.add(taskStatus);
632
                taskStatus.setAutoremove(true);
633
                
634
                //Crea la reproyecci?n al vuelo la primera vez
635
                RasterDataParameters params = (RasterDataParameters)getDataStore().getParameters();
636
                if(!getRender().isReprojectingOnTheFly() && 
637
                        getDataStore().getProjection() != null &&
638
                        params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
639
                        getRender().createReprojectionOnTheFly(getDataStore(), getCoordTrans(), taskStatus);
640
                }
641
                
642
                try {
643
                        if(getDataStore().isTiled()) {
644
                                getRender().drawTiledService(g, vp2, vp.getImageSize(), taskStatus);
645
                        } else {
646
                                getRender().draw(g, vp2, taskStatus);
647
                        }
648
                } catch (ProcessInterruptedException e1) {
649
                } finally {
650
                        taskStatus.terminate();
651
                }
652
        }
653

    
654
        /**
655
         * Inserta la proyecci?n.
656
         *
657
         * @param proj Proyecci?n.
658
         */
659
        public void setProjection(IProjection proj) {
660
                try {
661
                        getDataStore().setProjection(proj, true);
662
                        super.setProjection(proj);
663
                } catch (RmfSerializerException e) {
664
                        logger.error("Error saving the projection", e);
665
                }
666
        }
667
        
668
        public void setProjection(IProjection proj, boolean persist) {
669
                try {
670
                        getDataStore().setProjection(proj, persist);
671
                        super.setProjection(proj);
672
                } catch (RmfSerializerException e) {
673
                        logger.error("Error saving the projection", e);
674
                }
675
        }
676

    
677
        public Envelope getFullEnvelope() {
678
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
679
                //un extent aunque la capa no est? abierta
680
                if(/*!isOpen() || */getDataStore() == null || getDataStore().getExtent() == null)
681
                        return null;
682

    
683
                Rectangle2D e = getDataStore().getExtent().toRectangle2D();
684
                try {
685
                        return geomManager.createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
686
                                        .getMaxY(), SUBTYPES.GEOM2D);
687

    
688
                        /*
689
                        No es necesario 
690
                        ICoordTrans ct = getCoordTrans();
691
                        RasterDataParameters params = (RasterDataParameters)getDataStore().getParameters();
692
                        if (ct != null && params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
693
                                env = env.convert(ct);
694
                        }
695
                        return env;*/
696

    
697
                } catch (CreateEnvelopeException e1) {
698
                        logger.error("Error creating the envelope", e);
699
                        return null;
700
                }
701
        }
702
        
703
        /**
704
         * Obtiene el valor del pixel del Image en la posici?n x,y
705
         * @param x Posici?n x
706
         * @param y Posici?n y
707
         * @return valor de pixel
708
         */
709
//        public int[] getPixel(int pxx, int pxy) {
710
//                int[] argb = { -1, -1, -1, -1 };
711
//                if (!isOpen() || (image == null))
712
//                        return argb;
713
//                if (pxx >= 0 && pxx < image.getWidth() && pxy >= 0 && pxy < image.getHeight()) {
714
//                        int value = image.getRGB(pxx, pxy);
715
//                        argb[0] = ((value & 0xff000000) >> 24);
716
//                        argb[1] = ((value & 0x00ff0000) >> 16);
717
//                        argb[2] = ((value & 0x0000ff00) >> 8);
718
//                        argb[3] = (value & 0x000000ff);
719
//                }
720
//                return argb;
721
//        }
722

    
723
        public double getMaxX() {
724
                if(getFullEnvelope() != null)
725
                        return getFullEnvelope().getMaximum(0);
726
                return -1;
727
        }
728

    
729
        public double getMaxY() {
730
                if(getFullEnvelope() != null)
731
                        return this.getFullEnvelope().getMaximum(1);
732
                return -1;
733
        }
734

    
735
        public double getMinX() {
736
                if(getFullEnvelope() != null)
737
                        return getFullEnvelope().getMinimum(0);
738
                return -1;
739
        }
740

    
741
        public double getMinY() {
742
                if(getFullEnvelope() != null)
743
                        return getFullEnvelope().getMinimum(1);
744
                return -1;
745
        }
746

    
747
        public String queryByPoint(Point p) {
748
                if (!isOpen())
749
                        return null;
750
                ColorConversion conv = rManager.getColorConversion();
751

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

    
754
                ArrayList<Object> attr = getAttributes();
755
                data += "  <raster\n";
756
                data += "    File=\"" + getFile() + "\"\n";
757
                for (int i = 0; i < attr.size(); i++) {
758
                        Object[] a = (Object[]) attr.get(i);
759

    
760
                        data += "    " + a[0].toString() + "=";
761
                        if (a[1].toString() instanceof String)
762
                                data += "\"" + a[1].toString() + "\"\n";
763
                        else
764
                                data += a[1].toString() + "\n";
765
                }
766
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
767
                data += "    Point_WC=\"" + mathUtil.format(posXWC, 3) + " , " + mathUtil.format(posYWC, 3) + "\"\n";
768
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
769
                double[] cmyk = conv.RGBtoCMYK(r & 0xff, g & 0xff, b & 0xff, 1D);
770
                data += "    CMYK=\"" + mathUtil.format(cmyk[0], 4) + ", " + mathUtil.format(cmyk[1], 4) + ", " + mathUtil.format(cmyk[2], 4) + "," + mathUtil.format(cmyk[3], 4) + "\"\n";
771
                double[] hsl = conv.RGBtoHSL(r & 0xff, g & 0xff, b & 0xff);
772
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
773
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
774
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
775
                data += "    HSL=\"" + mathUtil.format(hsl[0], 4) + ", " + mathUtil.format(hsl[1], 4) + ", " + mathUtil.format(hsl[2], 4) + "\"\n";
776
                data += "  />\n";
777

    
778
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
779
                return data;
780
        }
781

    
782
        /**
783
         * Filters a string for being suitable as XML Tag, erasing
784
         * all not alphabetic or numeric characters.
785
         * @param s
786
         * @return string normalized
787
         */
788
        private String normalizeAsXMLTag(String s) {
789
                return s.replaceAll("[^a-zA-Z0-9]", "");
790
        }
791

    
792
        public ArrayList<Object> getAttributes() {
793
                ArrayList<Object> attr = new ArrayList<Object>();
794
                if(!isOpen())
795
                        return attr;
796
                Object [][] a = {
797
                        {"Filename", getDataStore().getName()},
798
                        {"Filesize", new Long(getDataStore().getFileSize())},
799
                        {"Width", new Integer((int)getDataStore().getWidth())},
800
                        {"Height", new Integer((int)getDataStore().getHeight())},
801
                        {"Bands", new Integer(getDataStore().getBandCount())}
802
                };
803
                for (int i = 0; i < a.length; i++)
804
                        attr.add(a[i]);
805
                return attr;
806
        }
807

    
808
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
809
                        double scale, PrintAttributes propeties) throws ReadException {
810

    
811
                if (/*!isOpen() ||*/ !isVisible() || !isWithinScale(scale))
812
                        return;
813
                
814
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
815
                SimpleTaskStatus taskStatus = new RasterTaskStatus("Printing raster " + getName() + "...", cancel);
816
                manager.add(taskStatus);
817
                taskStatus.setAutoremove(true);
818

    
819
                if (!mustTilePrint)
820
                        draw(null, g, viewPort, cancel,scale);
821
                else {
822
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
823
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
824
                        taskStatus.setRangeOfValues(0, tiles.getNumTiles());
825
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
826
                                // Parte que dibuja
827
                                try {
828
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
829
                                        draw(null, g, vp, cancel, scale);
830
                                        taskStatus.setCurValue(tileNr);
831
                                } catch (NoninvertibleTransformException e) {
832
                                        throw new ReadException("Error en la transformaci?n.", e);
833
                                } finally {
834
                                        taskStatus.terminate();
835
                                }
836
                        }
837
                }
838
                
839
                taskStatus.terminate();
840
        }
841

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

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

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

859
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
860

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

866
                double[] srcPts = new double[8];
867
                double[] dstPts = new double[8];
868

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

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

883
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
884

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

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

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

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

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

    
943
                // Salva a RMF
944
                if (getDataStore() != null)
945
                        // Guardamos la GeoReferenciacion de cada dataset
946
                        try {
947
                                getDataStore().saveGeoreferencingToRmf();
948
                        } catch (Exception e) {
949
                                logger.info("error_salvando_rmf", e);
950
                        }
951

    
952
                        if (this.isRemoveRasterFlag()) {
953
                                if (getDataStore() != null) {
954
                                        String[] files = getFileName().clone();
955

    
956
                                        try {
957
                                                getDataStore().close();
958
                                        } catch (CloseException e) {
959
                                        }
960

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

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

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

    
994
        public boolean isRemoveRasterFlag() {
995
                return removeRasterFlag;
996
        }
997

    
998
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
999
                this.removeRasterFlag = removeRasterFlag;
1000
        }
1001

    
1002
        public String getTocImageIcon() {
1003
                return "map-ok-ico";
1004
        }
1005

    
1006
        public int[] getTileSize() {
1007
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1008
                return size;
1009
        }
1010

    
1011
        public boolean isTiled() {
1012
                return mustTileDraw;
1013
        }
1014

    
1015
        public boolean isGeoreferenced() {
1016
                return getDataStore().isGeoreferenced();
1017
        }
1018

    
1019
        public NoData getNoDataValue() {
1020
                return getDataStore().getNoDataValue();
1021
        }
1022

    
1023
        /**
1024
         * Sets the nodata value for this layer
1025
         * @param nd
1026
         */
1027
        public void setNoDataValue(NoData nd) {
1028
                if (getDataStore() != null)
1029
                        getDataStore().setNoDataValue(nd);
1030
        }
1031

    
1032
        /**
1033
         * Gets the height in world coordinates of this raster layer
1034
         */
1035
        public double getWCHeight() {
1036
                return getFullEnvelope().getMaximum(1);
1037
        }
1038

    
1039
        /**
1040
         * Gets the width in world coordinates of this raster layer
1041
         */
1042
        public double getWCWidth() {
1043
                return getFullEnvelope().getMaximum(0);
1044
        }
1045

    
1046
        /**
1047
         * Gets the size of all files of this raster layer
1048
         */
1049
        public long[] getFileSize() {
1050
                if (getDataStore() == null)
1051
                        return null;
1052

    
1053
                return getDataStore().getFileSizeByProvider();
1054
        }
1055

    
1056
        /**
1057
         * Gets the list of file names
1058
         */
1059
        public String[] getFileName() {
1060
                if (getDataStore() == null)
1061
                        return null;
1062

    
1063
                return getDataStore().getURIByProvider();
1064
        }
1065

    
1066
        /**
1067
         * Returns the number of files in this raster layer
1068
         */
1069
        public int getFileCount() {
1070
                return getDataStore().getProviderCount();
1071
        }
1072

    
1073
        /*
1074
         * (non-Javadoc)
1075
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileFormat()
1076
         */
1077
        public String getFileFormat() {
1078
                if(getDataStore().getSourceType() == RasterDataStore.FILE) {
1079
                        String fName = getDataStore().getName();
1080
                        int index = fName.lastIndexOf(".") + 1;
1081
                        String ext = null;
1082
                        if (index > 0)
1083
                                ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1084
                        return ext;
1085
                }
1086
                if(getDataStore().getSourceType() == RasterDataStore.POSTGIS) {
1087
                        return "POSTGIS";
1088
                }
1089
                return null;
1090
        }
1091

    
1092
        public int[] getDataType() {
1093
                return getDataStore().getDataType();
1094
        }
1095

    
1096
        /**
1097
         * Sets the filter list
1098
         */
1099
        public void setRenderFilterList(RasterFilterList filterList) {
1100
                getRender().setFilterList(filterList);
1101
        }
1102
        
1103
        public DynObjectSet getInfo(org.gvsig.fmap.geom.primitive.Point p, double tolerance) throws LoadLayerException, DataException {
1104
                DynObjectSetRasterInfo info = new DynObjectSetRasterInfo();
1105
                
1106
                if (!isOpen()) {
1107
                        info.addField("Layer not open", normalizeAsXMLTag(getName()), 0);
1108
                        return info;
1109
                }
1110
                
1111
                Point2D pReal = new Point2D.Double(p.getX(), p.getY());
1112
                Point2D px = new Point2D.Double();
1113
                if(        pReal.getX() > this.getMinX() &&
1114
                        pReal.getX() < this.getMaxX() &&
1115
                        pReal.getY() > this.getMinY() &&
1116
                        pReal.getY() < this.getMaxY()) {
1117
                        px = transformPoint(pReal);
1118
                }
1119
                //int[] rgb = getPixel((int) p.getX(), (int) p.getY());
1120
                //ColorConversion conv = rManager.getColorConversion();
1121
                
1122
                info.addField("File", normalizeAsXMLTag(getName()), 0);
1123
                info.addField("View Point", "[" + p.getX() + " , " + p.getY() + "]", 1);
1124
                info.addField("World Point", "[" + mathUtil.format(pReal.getX(), 3) + " , " + mathUtil.format(pReal.getY(), 3) + "]", 2);
1125
                if (px == null)
1126
                        info.addField("Pixel Point", "Out", 3);
1127
                else
1128
                        info.addField("Pixel Point", "[" + (int) px.getX() + ",  " + (int) px.getY() + "]", 3);
1129
        
1130
                //La informaci?n RGB no puede obtener de la capa
1131
                
1132
                /*info.addField("RGB", "[" + rgb[1] + ",  " + rgb[2] + ",  " + rgb[3] + "]", 4);
1133
                double[] cmyk = conv.RGBtoCMYK(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff, 1D);
1134
                info.addField("CMYK", "[" + mathUtil.format(cmyk[0], 4) + ",  " + mathUtil.format(cmyk[1], 4) + ",  " + mathUtil.format(cmyk[2], 4) + ",  " + mathUtil.format(cmyk[3], 4) + "]", 5);
1135
                double[] hsl = conv.RGBtoHSL(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff);
1136
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
1137
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
1138
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
1139
                info.addField("HSL", "[" + mathUtil.format(hsl[0], 4) + ",  " + mathUtil.format(hsl[1], 4) + ",  " + mathUtil.format(hsl[2], 4) + "]", 6);*/
1140
                
1141
                String data = "[";
1142
                try {
1143
                        if (px != null) {
1144
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3) {
1145
                                        for(int i = 0; i < getDataStore().getBandCount(); i++) {
1146
                                                if(getDataStore().isInside(pReal)) {
1147
                                                        Point2D pxAux = transformPoint(pReal);
1148
                                                        int val = ((Integer)getDataStore().getData((int)pxAux.getX(), 
1149
                                                                        (int)pxAux.getY(), i)).intValue();
1150
                                                        if(getDataType()[0] == Buffer.TYPE_BYTE)
1151
                                                                data += (val & 0x000000ff) + ",  ";
1152
                                                        else
1153
                                                                data += val + ",  ";
1154
                                                }
1155
                                        }
1156
                                }
1157
                                if(getDataType()[0] == 4) {
1158
                                        for(int i = 0; i < getDataStore().getBandCount(); i++) {
1159
                                                if(getDataStore().isInside(pReal)) {
1160
                                                        Point2D pxAux = transformPoint(pReal);
1161
                                                        data += ((Float)getDataStore().getData((int)pxAux.getX(), 
1162
                                                                        (int)pxAux.getY(), i)).floatValue() + ",  ";
1163
                                                }
1164
                                        }
1165
                                }
1166
                                if(getDataType()[0] == 5) {
1167
                                        for(int i = 0; i < getDataStore().getBandCount(); i++) {
1168
                                                if(getDataStore().isInside(pReal)) {
1169
                                                        Point2D pxAux = transformPoint(pReal);
1170
                                                        data += ((Double)getDataStore().getData((int)pxAux.getX(), 
1171
                                                                        (int)pxAux.getY(), i)).doubleValue() + ",  ";
1172
                                                }
1173
                                        }
1174
                                }
1175
                        }
1176
                        data +=  "]";
1177
                        info.addField("Band Value", data, 7);
1178
                } catch (RasterDriverException ex) {
1179
                        throw new LoadLayerException("Error en el acceso al dataset", ex);
1180
                } catch (InvalidSetViewException ex) {
1181
                        throw new LoadLayerException("Error en la asignaci?n de la vista en getData", ex);
1182
                } catch (FileNotOpenException ex) {
1183
                        throw new LoadLayerException("Fichero no abierto en el dataset", ex);
1184
                }
1185
                return info;
1186
        }
1187
        
1188
        /**
1189
         * Transforma un punto real a coordenadas pixel
1190
         * 
1191
         * @param numberBand
1192
         * @param pReal
1193
         * @return
1194
         * @throws LoadLayerException 
1195
         * @throws ReadDriverException
1196
         */
1197
        private Point2D transformPoint(Point2D pReal) throws LoadLayerException {
1198
                AffineTransform at = getDataStore().getAffineTransform();
1199
                Point2D px = new Point2D.Double();
1200
                //px = new Point2D.Double(pReal.getX(), pReal.getY());
1201
                try {
1202
                        at.inverseTransform(pReal, px);
1203
                        return px;
1204
                } catch (NoninvertibleTransformException e) {
1205
                        throw new LoadLayerException("Error en la transformaci?n del punto", e);
1206
                }
1207
        }
1208
        
1209
        public Object getInfo(String key) {
1210
                if (key.equals("DriverName"))
1211
                        return "gvSIG Raster Driver";
1212
                return null;
1213
        }
1214

    
1215
        public int[] getBandCountFromDataset() {
1216
                return getDataStore().getBandCountByProvider();
1217
        }
1218

    
1219
        public String getColorInterpretation(int band, int dataset) {
1220
                if (this.getDataStore().getColorInterpretation().get(band) == null)
1221
                        return "Undefined";
1222
                return this.getDataStore().getColorInterpretation().get(band);
1223
        }
1224

    
1225
        public String getWktProjection() throws RasterDriverException {
1226
                return getDataStore().getWktProjection();
1227
        }
1228

    
1229
        public boolean isRGB() {
1230
                if ((getDataStore() == null) || (render == null))
1231
                        return false;
1232

    
1233
                if (getDataStore().getDataType()[0] != Buffer.TYPE_BYTE)
1234
                        return false;
1235

    
1236
                boolean R = false;
1237
                boolean G = false;
1238
                boolean B = false;
1239

    
1240
                int[] renderBands = render.getRenderBands();
1241
                for (int i = 0; i < renderBands.length; i++)
1242
                        if (renderBands[i] >= 0)
1243
                                switch (i) {
1244
                                        case 0:
1245
                                                R = true;
1246
                                                break;
1247
                                        case 1:
1248
                                                G = true;
1249
                                                break;
1250
                                        case 2:
1251
                                                B = true;
1252
                                                break;
1253
                                }
1254

    
1255
                if (R && G && B)
1256
                        return true;
1257

    
1258
                return false;
1259
        }
1260

    
1261
        /**
1262
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1263
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1264
         * cacheado o no dependiendo del tama?o de esta.
1265
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1266
         * @return Grid.
1267
         * @throws InterruptedException
1268
         * @deprecated Don't use a <code>Grid</code> object. This will be removed soon
1269
         */
1270
        public Grid getFullGrid(boolean interpolated) throws GridException, InterruptedException {
1271
                RasterQuery query = rManager.createQuery();
1272
                query.setAllDrawableBands();
1273
                Buffer bf = null;
1274
                try {
1275
                        query.setAreaOfInterest();
1276
                        bf = getDataStore().query(query);
1277
                } catch (RasterDriverException e) {
1278
                        throw new GridException("Error reading buffer");
1279
                } catch (ProcessInterruptedException e) {
1280
                        throw new InterruptedException("Carga interrumpida");
1281
                } catch (InvalidSetViewException e) {
1282
                        throw new GridException("Error reading buffer");
1283
                }
1284
                return rManager.createGrid(bf, getDataStore(), interpolated);
1285
        }
1286

    
1287
        /**
1288
         * @deprecated Don't use a <code>Grid</code> object. This will be removed soon
1289
         */
1290
        public Grid getReadOnlyFullGrid(boolean interpolated) throws GridException, InterruptedException {
1291
                RasterQuery query = rManager.createQuery();
1292
                query.setReadOnly(true);
1293
                query.setAllDrawableBands();
1294
                Buffer bf = null;
1295
                try {
1296
                        query.setAreaOfInterest();
1297
                        bf = getDataStore().query(query);
1298
                } catch (RasterDriverException e) {
1299
                        throw new GridException("Error reading buffer");
1300
                } catch (ProcessInterruptedException e) {
1301
                        throw new InterruptedException("Carga interrumpida");
1302
                } catch (InvalidSetViewException e) {
1303
                        throw new GridException("Error reading buffer");
1304
                }
1305
                return rManager.createGrid(bf, getDataStore(), interpolated);
1306
        }
1307

    
1308
        /**
1309
         * Obtiene el tama?o de celda de la fuente de datos
1310
         * @return double con el tama?o de celda
1311
         */
1312
        public double getCellSize() {
1313
                return (getDataStore() != null) ? getDataStore().getCellSize() : 1;
1314
        }
1315

    
1316
        public Extent getFullRasterExtent() {
1317
                return this.getDataStore().getExtent();
1318
        }
1319

    
1320

    
1321
        /**
1322
         * Devuelve el fichero asociado a la capa o null si no tiene.
1323
         * @return Fichero.
1324
         */
1325
        public File getFile() {
1326
                if(getDataStore().getParameters() instanceof RasterFileStoreParameters)
1327
                        return ((RasterFileStoreParameters)getDataStore().getParameters()).getFile();
1328
                return new File("");
1329
        }
1330

    
1331
        /**
1332
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1333
         * @param file Fichero a consultar
1334
         * @return true si es aceptado y false si no lo es.
1335
         */
1336
        public boolean isFileAccepted(File file) {
1337
                return getDataStore().isFileSupported(file.getName());
1338
        }
1339
        
1340
        /**
1341
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1342
         * @param file Fichero a consultar
1343
         * @return true si es aceptado y false si no lo es.
1344
         */
1345
        public static boolean isFileSupported(File file) {
1346
                return RasterLocator.getManager().getProviderServices().isExtensionSupported(file.getName());
1347
        }
1348

    
1349
        public boolean existColorTable() {
1350
                return getRender().existColorTable();
1351
        }
1352

    
1353
        /**
1354
         * Returns true if the data store has an alpha band
1355
         */
1356
        public boolean existsAlphaBand() {
1357
                if(getDataStore().getColorInterpretation() != null)
1358
                        return getDataStore().getColorInterpretation().hasAlphaBand();
1359
                else
1360
                        return false;
1361
        }
1362

    
1363
        public int getAlphaBandNumber() {
1364
                if(getDataStore().getColorInterpretation() != null)
1365
                        return getDataStore().getColorInterpretation().getBand(ColorInterpretation.ALPHA_BAND);
1366
                return -1;
1367
        }
1368

    
1369
        /**
1370
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1371
         * capa busque una leyenda valida.
1372
         * @param ct
1373
         */
1374
        public void setLastLegend(ColorTable ct) {
1375
                lastLegend = ColorTableLegend.createLegend(ct);
1376
        }
1377

    
1378
        /**
1379
         * Devuelve la Leyenda de la capa.
1380
         * @return Leyenda.
1381
         */
1382
        public ILegend getLegend() {
1383
                if (lastLegend != null)
1384
                        return lastLegend;
1385

    
1386
                return null;
1387
        }
1388

    
1389
        public void addLegendListener(LegendListener listener) {
1390
                layerChangeSupport.addLayerListener(listener);
1391
        }
1392

    
1393
        public int getShapeType() {
1394
                return TYPES.SURFACE;
1395
        }
1396

    
1397
        public void removeLegendListener(LegendListener listener) {
1398
                if(layerChangeSupport != null)
1399
                        layerChangeSupport.removeLayerListener(listener);
1400
        }
1401

    
1402
        public boolean isInside(Point2D p) {
1403
                 return getDataStore().isInside(p);
1404
        }
1405

    
1406
        public AffineTransform getAffineTransform() {
1407
                return getDataStore().getAffineTransform();
1408
        }
1409

    
1410
        public void setAffineTransform(AffineTransform transf) {
1411
                if(transf == null)
1412
                        return;
1413
                affineTransformList.add(transf);
1414
                getDataStore().setAffineTransform(transf);
1415
                updateDrawVersion();
1416
        }
1417

    
1418
        public void setAffineTransformWithoutHistorical(AffineTransform transf) {
1419
                getDataStore().setAffineTransform(transf);
1420
                updateDrawVersion();
1421
        }
1422

    
1423
        public Historical getAffineTransformHistorical() {
1424
                return this.affineTransformList;
1425
        }
1426

    
1427
        public void saveGeoToRmf() throws RmfSerializerException {
1428
                if (!isOpen())
1429
                        return;
1430

    
1431
                getDataStore().saveGeoreferencingToRmf();
1432
                
1433
                affineTransformList.clear();
1434
                affineTransformList.add(this.getAffineTransform());
1435
        }
1436

    
1437
        public boolean isActionEnabled(int action) {
1438
                switch (action) {
1439
                        case IRasterLayerActions.BANDS_FILE_LIST:
1440
                                if (existColorTable() || getDataStore().isMosaic())
1441
                                        return false;
1442
                                break;
1443
                        case IRasterLayerActions.BANDS_RGB:
1444
                                if (existColorTable())
1445
                                        return false;
1446
                                break;
1447
                        case IRasterLayerActions.REPROJECT:
1448
                                if (!isReproyectable())
1449
                                        return false;
1450
                                break;
1451
                        case IRasterLayerActions.CREATEOVERVIEWS:
1452
                                return overviewsSupport();
1453
                        case IRasterLayerActions.OPACITY:
1454
                        case IRasterLayerActions.TRANSPARENCY:
1455
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1456
                        case IRasterLayerActions.ENHANCED:
1457
                        case IRasterLayerActions.PANSHARPENING:
1458
                        case IRasterLayerActions.SELECT_LAYER:
1459
                        case IRasterLayerActions.SAVE_COLORINTERP:
1460
                                return true;
1461
                        case IRasterLayerActions.REMOTE_ACTIONS:
1462
                                return false;
1463
                        case IRasterLayerActions.TAILTRIM:
1464
                        case IRasterLayerActions.GEOLOCATION:
1465
                                return !(getDataStore().isTiled());
1466
                }
1467
                return true;
1468
        }
1469

    
1470
        public void setVisible(boolean visibility) {
1471
                if(visibility)
1472
                        state.disableStopped();
1473
                else
1474
                        enableStopped();
1475

    
1476
                if(isAwake() || isClosed())
1477
                        try {
1478
                                this.load();
1479
                        } catch (LoadLayerException e) {
1480
                                e.printStackTrace();
1481
                        }
1482

    
1483
                /*
1484
                 * Cuando se modifica la visibilidad de una capa raster se hace un updateDrawVersion de todas las
1485
                 * capas raster de ese MapContext. Esto es porque la estrategia utilizada por RasterDrawStrategy hace
1486
                 * que se cacheen en blanco las capas raster que est?n ocultas debajo de otras. Al hacer invisibles las
1487
                 * de arriba la cache que estaba en blanco hace que no se pinte nada. Para evitar esto las marcamos todas
1488
                 * como que han sido modificadas para que se vuelvan a leer.
1489
                 */
1490
                if(getMapContext() != null) {
1491
                        ArrayList<FLayer> listLayers = new ArrayList<FLayer>();
1492
                        listLayers = RasterDrawStrategy.getLayerList(getMapContext().getLayers(), listLayers);
1493
                        for (int i = 0; i < listLayers.size(); i++)
1494
                                if(listLayers.get(i) instanceof DefaultFLyrRaster)
1495
                                        ((DefaultFLyrRaster)listLayers.get(i)).updateDrawVersion();
1496
                }
1497

    
1498
                super.setVisible(visibility);
1499
        }
1500

    
1501
        /**
1502
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1503
         * @return valor de transparencia
1504
         */
1505
        public int getTransparency() {
1506
                try {
1507
                        return getRender().getLastTransparency().getOpacity();
1508
                } catch (NullPointerException e) {
1509
                        return super.getTransparency();
1510
                }
1511
        }
1512

    
1513
        /**
1514
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1515
         * o no.
1516
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1517
         */
1518
        public boolean isTransparent() {
1519
                return getRender().getLastTransparency().isTransparencyActive();
1520
        }
1521

    
1522
        /**
1523
         * Asigna la transparencia de la siguiente renderizaci?n
1524
         * @param valor de transparencia
1525
         */
1526
        public void setTransparency(int trans) {
1527
                super.setTransparency(trans);
1528
                try {
1529
                        getRender().getLastTransparency().setOpacity(trans);
1530
                } catch (NullPointerException e) {
1531
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1532
                }
1533
        }
1534

    
1535
        public List<ROI> getRois() throws ROIException {
1536
                return getDataStore().getRois(getMapContext().getProjection());
1537
        }
1538

    
1539
        public void setRois(List<ROI> rois) {
1540
                getDataStore().setRois(rois);
1541
        }
1542
        
1543
        public void setROIsFiles(List<File> file) throws RmfSerializerException {
1544
                getDataStore().saveROIFileListToRmf(file);
1545
        }
1546
        
1547
        public List<File> getROIsFiles() throws RmfSerializerException {
1548
                return getDataStore().getROIFileListFromRmf();
1549
        }
1550

    
1551
        /**
1552
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1553
         * devolver? null.
1554
         * @return TreeMap con la lista de capas a dibujar
1555
         */
1556
        public HashMap<DefaultFLyrRaster, Boolean> getRasterStrategy() {
1557
                if(strategy != null)
1558
                        return strategy.getStrategy();
1559
                return null;
1560
        }
1561

    
1562
        /**
1563
         * @return the configuration
1564
         */
1565
        static public IConfiguration getConfiguration() {
1566
                return configuration;
1567
        }
1568

    
1569
        /**
1570
         * @param configuration the configuration to set
1571
         */
1572
        static public void setConfiguration(IConfiguration configuration) {
1573
                DefaultFLyrRaster.configuration = configuration;
1574
        }
1575

    
1576
        public void reload() throws ReloadLayerException {
1577
                try {
1578
                        super.reload();
1579
                        load();
1580
                        if (isStopped())
1581
                                disableStopped();
1582
                        if (getMapContext() != null)
1583
                                getMapContext().invalidate();
1584
                } catch (LoadLayerException e) {
1585
                        setAvailable(false);
1586
                        throw new ReloadLayerException(getName(), e);
1587
                }
1588
        }
1589

    
1590
        /**
1591
         * Devuelve si la capa tiene soporte para poder generar overviews
1592
         * @return
1593
         */
1594
        public boolean overviewsSupport() {
1595
                if ((getDataStore() != null) && (getDataStore().overviewsSupport()))
1596
                        return true;
1597

    
1598
                return false;
1599
        }
1600

    
1601
        /**
1602
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1603
         * en escala de grises
1604
         * @return
1605
         */
1606
        public boolean isRenderingAsGray() {
1607
                int[] renderBands = getRender().getRenderBands();
1608
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1609
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1610
                        return true;
1611
                return false;
1612
        }
1613

    
1614
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1615
                updateDrawVersion();
1616
        }
1617

    
1618
        public Point2D adjustWorldRequest(Point2D req) {
1619
                Envelope ext = null;
1620

    
1621
                ext = getFullEnvelope();
1622
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
1623
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
1624
                return req;
1625
        }
1626

    
1627
        public FLayer cloneLayer() throws Exception {
1628
                RasterDataStore  ds = getDataStore().cloneDataStore();
1629
                DefaultFLyrRaster newLayer = new DefaultFLyrRaster();
1630
                newLayer.setName(getName());
1631
                newLayer.setOpenRasterStore(ds);
1632
                newLayer.firstLoad = firstLoad;
1633
                
1634
                List<RasterFilter> filters = getRender().getFilterList().getStatusCloned();
1635

    
1636
                //Hacemos una copia de las bandas a renderizar
1637
                if(getRender().getRenderBands() != null) {
1638
                        int[] rb = new int[getRender().getRenderBands().length];
1639
                        for (int i = 0; i < rb.length; i++)
1640
                                rb[i] = getRender().getRenderBands()[i];
1641
                        newLayer.getRender().setRenderBands(rb);
1642
                }
1643

    
1644
                //Asignamos el entorno
1645
                if(newLayer.getRender().getFilterList() == null)
1646
                        newLayer.getRender().setFilterList(RasterLocator.getManager().createEmptyFilterList(getRender().getFilterList().getInitDataType()));
1647
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
1648
                newLayer.getRender().getFilterList().setStatus(filters);
1649

    
1650
                // Asignamos los valores noData del original
1651
                newLayer.setNoDataValue(getNoDataValue());
1652
                if(getDataStore().getNoDataValue().isDefined())
1653
                        newLayer.setNoDataTransparent(true);
1654
                newLayer.enableOpen();
1655
                
1656
                return newLayer;
1657
        }
1658
        
1659
        public FLayer getFileLayer() throws RasterDriverException {
1660
                try {
1661
                        return cloneLayer();
1662
                } catch (Exception e) {
1663
                }
1664
                return null;
1665
        }
1666
        
1667
        public void addFile(String file) throws InvalidSourceException {
1668
                getDataStore().addFile(file);
1669
        }
1670
        
1671
        public void removeFile(String file) {
1672
                getDataStore().removeFile(file);
1673
        }
1674

    
1675
        /*****************************************************/
1676

    
1677
        public void disableStopped() {
1678
                if(state != null)
1679
                        state.disableStopped();
1680
        }
1681

    
1682
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1683

    
1684
        public void enableClosed() throws NotAvailableStateException {
1685
                if(state != null)
1686
                        state.enableClosed();
1687
        }
1688

    
1689
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1690

    
1691
        public void enableStopped() {state.enableStopped();}
1692

    
1693
        public boolean isAwake() {return state.isAwake();}
1694

    
1695
        public boolean isClosed() {return state.isClosed();}
1696

    
1697
        public boolean isOpen() {return state.isOpen();}
1698

    
1699
        public boolean isStopped() {return state.isStopped();}
1700

    
1701

    
1702
        @SuppressWarnings("rawtypes")
1703
        public Set getMetadataChildren() {
1704
                return null;
1705
        }
1706

    
1707
        public Object getMetadataID() {
1708
                return getName();
1709
        }
1710

    
1711
        public String getMetadataName() {
1712
                return null;
1713
        }
1714

    
1715
        public RasterDataStore getDataStore() {
1716
                if(dataStore != null) {
1717
                        RasterDataParameters params = (RasterDataParameters)dataStore.getParameters();
1718
                        if (getCoordTrans() != null && params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
1719
                                this.dataStore.setCoordTrans(getCoordTrans());
1720
                        }
1721
                }
1722
                return this.dataStore;
1723
        }
1724
        
1725
        public IProjection getProjection() {
1726
                RasterDataParameters p = (RasterDataParameters)getDataStore().getParameters();
1727
                if(p.getReprojectionOption() == RasterDataParameters.DONT_CHANGE_PROJECTION)
1728
                        return null;
1729
                return getDataStore().getProjection();
1730
        }
1731

    
1732
        public void setOpenRasterStore(DataStore dataStore) throws LoadLayerException {
1733
                if(dataStore instanceof CoverageStoreProviderServices) {
1734
                        try {
1735
                                this.dataStore = rManager.getProviderServices().open(
1736
                                                ((CoverageStoreProviderServices) dataStore).getProvider(), 
1737
                                                dataStore.getParameters());
1738
                        } catch (NotSupportedExtensionException e) {
1739
                                throw new LoadLayerException("Extension not supported", e);
1740
                        } catch (RasterDriverException e) {
1741
                                throw new LoadLayerException("Error opening the DataStore", e);
1742
                        }
1743
                } else
1744
                        this.dataStore = (RasterDataStore) dataStore;
1745
                try {
1746
                        enableAwake();
1747
                } catch (NotAvailableStateException e) {
1748
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
1749
                }
1750
                if(getDataStore().getProjection() != null) {
1751
                        try {
1752
                                getDataStore().setProjection(getDataStore().getProjection(), false);
1753
                                super.setProjection(getDataStore().getProjection());
1754
                        } catch (RmfSerializerException e) {
1755
                                //persist is false
1756
                        }
1757
                }
1758
        }
1759
        
1760
        public void setDataStore(DataStore dataStore) throws LoadLayerException {
1761
                setOpenRasterStore(dataStore);
1762
                load();
1763
        }
1764
        
1765
        public boolean isRemote() {
1766
                return false;
1767
        }
1768
        
1769
        /**
1770
         * Returns true if exists a process reading data from this layer
1771
         * @return
1772
         */
1773
        public boolean isReadingData() {
1774
                return readingData != null;
1775
        }
1776

    
1777
        /**
1778
         * When a process is using information of this layer this variable will contain
1779
         * the thread ID.
1780
         * @param readingData
1781
         */
1782
        public synchronized void setReadingData(String readingData) {
1783
                this.readingData = readingData;
1784
        }
1785
        
1786
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel,
1787
                        boolean fast)
1788
                        throws LoadLayerException, DataException {
1789
                return null;
1790
        }
1791

    
1792
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel)
1793
                        throws LoadLayerException, DataException {
1794
                return null;
1795
        }
1796

    
1797
        @Override
1798
        protected void doDispose() throws BaseException {
1799
                if(render != null)
1800
                        render.dispose();
1801
                if(getDataStore() != null)
1802
                        getDataStore().dispose();
1803
                finalize();
1804
        }
1805

    
1806
        public int getZoomLevel() {
1807
                return zoomLevel;
1808
        }
1809

    
1810
        public void setZoomLevel(int zoomLevel) {
1811
                this.zoomLevel = zoomLevel;
1812
        }
1813
        
1814
        public boolean increaseZoomLevel() {
1815
                if(zoomLevel < (this.getDataStore().getZoomLevels() - 1)) { 
1816
                        zoomLevel ++;
1817
                        recalcLevel = false;
1818
                        return true;
1819
                }
1820
                return false;
1821
        }
1822
        
1823
        public boolean decreaseZoomLevel() {
1824
                if(zoomLevel > 0) { 
1825
                        zoomLevel --;
1826
                        recalcLevel = false;
1827
                        return true;
1828
                }
1829
                return false;
1830
        }
1831
        
1832
        public Envelope getCoordsInLevel(Point2D center, int level, int w, int h) throws CreateEnvelopeException {
1833
                Extent ex = getDataStore().getCoordsInLevel(center, level, w, h);
1834
                return geomManager.createEnvelope(ex.getULX(), ex.getULY(), ex.getLRX(), ex.getLRY(), SUBTYPES.GEOM2D);
1835
        }
1836
        
1837
        public boolean isEnabledMultiresolution() {
1838
                return getDataStore().isTiled();
1839
        }
1840
        
1841
        public void setTileServer(Class<?> tileServer) throws InitializeException {
1842
                getDataStore().setTileServer(tileServer);
1843
        }
1844
        
1845
        protected boolean loadLayer = true;
1846
        
1847
        @Override
1848
        public void loadFromState(PersistentState state)
1849
                        throws PersistenceException {
1850
                super.loadFromState(state);
1851
        
1852
                if(!loadLayer)
1853
                        return;
1854
                
1855
                this.zoomLevel = state.getInt("zoomLevel");
1856
                this.recalcLevel = state.getBoolean("recalcLevel");
1857
                if(getDataStore() == null)
1858
                        this.dataStore = (RasterDataStore)state.get("rasterdatastore");
1859
                this.lastLegend = (ILegend)state.get("legend");
1860
                this.colorTableLoadedFromProject = (ColorTable)state.get("colortable");
1861
                this.zoomLevel = state.getInt("zoomLevel");
1862
                this.recalcLevel = state.getBoolean("recalcLevel");
1863
                loadedFromProject = true;
1864
        }
1865

    
1866
        @Override
1867
        public void saveToState(PersistentState state) throws PersistenceException {
1868
                super.saveToState(state);
1869
                
1870
                state.set("rasterdatastore", getDataStore());        
1871
                state.set("legend", lastLegend);        
1872
                state.set("colortable", getRender().getColorTable());        
1873
                state.set("zoomLevel", zoomLevel);        
1874
                state.set("recalcLevel", recalcLevel);        
1875
        }        
1876
        
1877
        public static void registerPersistence() {
1878
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
1879
                DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
1880
                if( definition == null ) {
1881
                        if (manager.getDefinition(FLyrDefault.class) == null) {
1882
                                FLyrDefault.registerPersistent();
1883
                        }
1884
                        definition = manager.addDefinition(
1885
                                        DefaultFLyrRaster.class,
1886
                                        PERSISTENT_NAME,
1887
                                        PERSISTENT_DESCRIPTION,
1888
                                        null, 
1889
                                        null
1890
                        );
1891
                        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE, "FLyrDefault");
1892
                        
1893
                        registerPersistence(definition);
1894
                }
1895
        }
1896
        
1897
        public static void registerPersistence(DynStruct definition) {
1898
                definition.addDynFieldObject("rasterdatastore").setClassOfValue(RasterDataStore.class).setMandatory(true);
1899
                definition.addDynFieldObject("legend").setClassOfValue(ILegend.class).setMandatory(false);
1900
                definition.addDynFieldObject("colortable").setClassOfValue(ColorTable.class).setMandatory(false);
1901
                definition.addDynFieldInt("zoomlevel").setMandatory(false);
1902
                definition.addDynFieldBoolean("recalcLevel").setMandatory(false);
1903
        }
1904

    
1905
        public GeometryType getGeometryType() throws ReadException {
1906
                try {
1907
                        return GeometryLocator.getGeometryManager().getGeometryType(TYPES.SURFACE, SUBTYPES.GEOM2D);
1908
                } catch (GeometryTypeNotSupportedException e) {
1909
                        throw new ReadException(getDataStore().getName(), e);
1910
                } catch (GeometryTypeNotValidException e) {
1911
                        throw new ReadException(getDataStore().getName(), e);
1912
                } 
1913
        }
1914
        
1915
        public void setDataStore(DataStore dataStore, String domain) throws LoadLayerException {
1916
                setDataStore(dataStore);
1917
        }
1918
        
1919
        protected void finalize() {
1920
                layerChangeSupport             = null;
1921
                state                          = null;
1922
                lastLegend                     = null;
1923
                colorTableLoadedFromProject    = null;
1924
                strategy                       = null;
1925
                configuration                  = null;
1926
                fileUtil                       = null;
1927
                rasterUtil                     = null;
1928
                crsUtil                        = null;
1929
                mathUtil                       = null;
1930
                uri                            = null;
1931
                affineTransformList            = null;
1932
                readingData                    = null;
1933
                dataStore                      = null;
1934
                render                         = null;
1935
        }
1936

    
1937
}