Statistics
| Revision:

gvsig-raster / org.gvsig.raster / branches / org.gvsig.raster_dataaccess_refactoring / org.gvsig.raster.fmap / src / main / java / org / gvsig / raster / fmap / layers / DefaultFLyrRaster.java @ 2316

History | View | Annotate | Download (61.7 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.QueryException;
65
import org.gvsig.fmap.dal.coverage.exception.ROIException;
66
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
67
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
68
import org.gvsig.fmap.dal.coverage.grid.Grid;
69
import org.gvsig.fmap.dal.coverage.grid.RasterFilter;
70
import org.gvsig.fmap.dal.coverage.grid.RasterFilterList;
71
import org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager;
72
import org.gvsig.fmap.dal.coverage.grid.render.Render;
73
import org.gvsig.fmap.dal.coverage.grid.render.VisualPropertyEvent;
74
import org.gvsig.fmap.dal.coverage.grid.render.VisualPropertyListener;
75
import org.gvsig.fmap.dal.coverage.process.TaskEventManager;
76
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
77
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
78
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
79
import org.gvsig.fmap.dal.coverage.store.parameter.RasterFileStoreParameters;
80
import org.gvsig.fmap.dal.coverage.store.parameter.TileDataParameters;
81
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
82
import org.gvsig.fmap.dal.coverage.store.props.ColorTable;
83
import org.gvsig.fmap.dal.coverage.store.props.Statistics;
84
import org.gvsig.fmap.dal.coverage.util.CRSUtils;
85
import org.gvsig.fmap.dal.coverage.util.ColorConversion;
86
import org.gvsig.fmap.dal.coverage.util.FileUtils;
87
import org.gvsig.fmap.dal.coverage.util.Historical;
88
import org.gvsig.fmap.dal.coverage.util.MathUtils;
89
import org.gvsig.fmap.dal.coverage.util.ProviderServices;
90
import org.gvsig.fmap.dal.coverage.util.RasterUtils;
91
import org.gvsig.fmap.dal.exception.CloseException;
92
import org.gvsig.fmap.dal.exception.DataException;
93
import org.gvsig.fmap.dal.exception.InitializeException;
94
import org.gvsig.fmap.dal.exception.ReadException;
95
import org.gvsig.fmap.dal.raster.spi.CoverageStoreProviderServices;
96
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
97
import org.gvsig.fmap.geom.Geometry.TYPES;
98
import org.gvsig.fmap.geom.GeometryLocator;
99
import org.gvsig.fmap.geom.GeometryManager;
100
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
101
import org.gvsig.fmap.geom.primitive.Envelope;
102
import org.gvsig.fmap.geom.type.GeometryType;
103
import org.gvsig.fmap.geom.type.GeometryTypeNotSupportedException;
104
import org.gvsig.fmap.geom.type.GeometryTypeNotValidException;
105
import org.gvsig.fmap.mapcontext.MapContextLocator;
106
import org.gvsig.fmap.mapcontext.MapContextManager;
107
import org.gvsig.fmap.mapcontext.ViewPort;
108
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
109
import org.gvsig.fmap.mapcontext.exceptions.ReloadLayerException;
110
import org.gvsig.fmap.mapcontext.layers.FLayer;
111
import org.gvsig.fmap.mapcontext.layers.FLyrDefault;
112
import org.gvsig.fmap.mapcontext.layers.LayerChangeSupport;
113
import org.gvsig.fmap.mapcontext.layers.LayerListener;
114
import org.gvsig.fmap.mapcontext.layers.Tiling;
115
import org.gvsig.fmap.mapcontext.layers.operations.Classifiable;
116
import org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint;
117
import org.gvsig.fmap.mapcontext.layers.operations.SingleLayer;
118
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
119
import org.gvsig.fmap.mapcontext.rendering.legend.events.listeners.LegendListener;
120
import org.gvsig.raster.fmap.legend.ColorTableLegend;
121
import org.gvsig.raster.roi.ROI;
122
import org.gvsig.raster.util.RasterNotLoadException;
123
import org.gvsig.tools.ToolsLocator;
124
import org.gvsig.tools.dynobject.DynClass;
125
import org.gvsig.tools.dynobject.DynObjectManager;
126
import org.gvsig.tools.dynobject.DynObjectSet;
127
import org.gvsig.tools.dynobject.DynStruct;
128
import org.gvsig.tools.exception.BaseException;
129
import org.gvsig.tools.persistence.PersistenceManager;
130
import org.gvsig.tools.persistence.PersistentState;
131
import org.gvsig.tools.persistence.exception.PersistenceException;
132
import org.gvsig.tools.persistence.exception.PersistenceRuntimeException;
133
import org.gvsig.tools.task.Cancellable;
134
import org.gvsig.tools.task.SimpleTaskStatus;
135
import org.gvsig.tools.task.TaskStatusManager;
136
import org.gvsig.tools.task.impl.BaseTaskStatus;
137
import org.slf4j.Logger;
138
import org.slf4j.LoggerFactory;
139

    
140
/**
141
 * Raster layer
142
 * 
143
 * @author Nacho Brodin (nachobrodin@gmail.com)
144
 */
145
@SuppressWarnings("deprecation")
146
public class DefaultFLyrRaster extends FLyrDefault implements FLyrRaster, Multiresolution, InfoByPoint, Classifiable,
147
                IRasterLayerActions, ILayerState, VisualPropertyListener, SingleLayer {
148
        public static final String      PERSISTENT_NAME                = "FLyrRasterSE_Persistent";
149
    public static final String      PERSISTENT_DESCRIPTION         = "FLyrRasterSE Persistent";
150
    private RasterManager           rManager                       = RasterLocator.getManager();
151
        private boolean                 mustTileDraw                   = false;
152
        private boolean                 mustTilePrint                  = true;
153
        private int                     maxTileDrawWidth               = 200;
154
        private int                     maxTileDrawHeight              = 200;
155
        private int                     maxTilePrintWidth              = 1500;
156
        private int                     maxTilePrintHeight             = 1500;
157
        private boolean                 firstLoad                      = false;
158
        private boolean                 removeRasterFlag               = true;
159
        protected RasterDataStore       dataStore                      = null;
160
        protected Render                render                         = null;
161
        private int                     posX                           = 0;
162
        private int                     posY                           = 0;
163
        private double                  posXWC                         = 0;
164
        private int                     posYWC                         = 0;
165
        private int                     r                              = 0;
166
        private int                     g                              = 0;
167
        private int                     b                              = 0;
168
        private LayerChangeSupport      layerChangeSupport             = new LayerChangeSupport();
169
        private FLyrState               state                          = new FLyrState();
170
        protected ILegend               lastLegend                     = null;
171
        protected ColorTable            colorTableLoadedFromProject    = null;
172
        protected boolean               loadedFromProject              = false;
173
        private RasterDrawStrategy      strategy                       = null;
174
        static private IConfiguration   configuration                  = new DefaultLayerConfiguration();
175
        protected int                   zoomLevel                      =  1;
176
        public boolean                  recalcLevel                    = true;
177
        private String                  uri                            = null;
178
        
179
        private static GeometryManager  geomManager                          = GeometryLocator.getGeometryManager();
180
        private static final Logger     logger                         = LoggerFactory.getLogger(DefaultFLyrRaster.class);
181
        protected FileUtils             fileUtil                       = RasterLocator.getManager().getFileUtils();
182
        protected RasterUtils           rasterUtil                     = RasterLocator.getManager().getRasterUtils();
183
        protected CRSUtils              crsUtil                        = RasterLocator.getManager().getCRSUtils();
184
        protected MathUtils             mathUtil                       = RasterLocator.getManager().getMathUtils();
185
        
186
        public class RasterTaskStatus extends BaseTaskStatus {
187
                Cancellable c = null;
188
                
189
                public RasterTaskStatus(String tittle, Cancellable c) {
190
                        super(tittle);
191
                        this.c = c;
192
                }
193
                
194
                public boolean isCancellationRequested() {
195
                        if(c != null)
196
                                return this.c.isCanceled();
197
                        return false;
198
                }
199
                
200
                public void cancelRequest() {
201
                        if(c != null)
202
                                this.c.setCanceled(true);
203
                }
204
        }
205

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

    
249
                return lyr;
250
        }
251

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

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

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

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

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

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

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

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

    
317
        /**
318
         * Acciones de inicializaci?n despu?s de que la fuente de datos
319
         * de la capa est? asignada. 
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().getRenderingTransparency() != null) {
379
                        getRender().getRenderingTransparency().setNoData(getDataStore().getNoDataValue());
380
                        getRender().getRenderingTransparency().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

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

    
406
                filterList.setInitDataType(getDataType()[0]);
407

    
408
                // Quitamos la leyenda
409
                lastLegend = null;
410

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

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

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

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

    
466
                Statistics stats = getDataStore().getStatistics();
467
                ColorTableLibrary colorTableLibrary = rManager.getDataStructFactory().getColorTableLibrary();
468

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

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

    
486
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
487

    
488
                                                        setLastLegend(colorTable);
489

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

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

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

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

    
547
                try {
548
                        if (!isOpen())
549
                                return;
550

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

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

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

    
600
                        }
601
                        
602
                        //callLegendChanged(null);
603
                } finally {
604
                        disableStopped();
605
                        task.setEvent(null);
606
                }
607
        }
608

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

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

    
671
        public Envelope getFullEnvelope() {
672
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
673
                //un extent aunque la capa no est? abierta
674
                if(/*!isOpen() || */getDataStore() == null || getDataStore().getExtent() == null)
675
                        return null;
676

    
677
                Rectangle2D e = getDataStore().getExtent().toRectangle2D();
678
                try {
679
                        return geomManager.createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
680
                                        .getMaxY(), SUBTYPES.GEOM2D);
681

    
682
                        /*
683
                        No es necesario 
684
                        ICoordTrans ct = getCoordTrans();
685
                        RasterDataParameters params = (RasterDataParameters)getDataStore().getParameters();
686
                        if (ct != null && params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
687
                                env = env.convert(ct);
688
                        }
689
                        return env;*/
690

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

    
717
        public double getMaxX() {
718
                if(getFullEnvelope() != null)
719
                        return getFullEnvelope().getMaximum(0);
720
                return -1;
721
        }
722

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

    
729
        public double getMinX() {
730
                if(getFullEnvelope() != null)
731
                        return getFullEnvelope().getMinimum(0);
732
                return -1;
733
        }
734

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

    
741
        public String queryByPoint(Point p) {
742
                if (!isOpen())
743
                        return null;
744
                ColorConversion conv = rManager.getColorConversion();
745

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

    
748
                ArrayList<Object> attr = getAttributes();
749
                data += "  <raster\n";
750
                data += "    File=\"" + getFile() + "\"\n";
751
                for (int i = 0; i < attr.size(); i++) {
752
                        Object[] a = (Object[]) attr.get(i);
753

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

    
772
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
773
                return data;
774
        }
775

    
776
        /**
777
         * Filters a string for being suitable as XML Tag, erasing
778
         * all not alphabetic or numeric characters.
779
         * @param s
780
         * @return string normalized
781
         */
782
        private String normalizeAsXMLTag(String s) {
783
                return s.replaceAll("[^a-zA-Z0-9]", "");
784
        }
785

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

    
802
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
803
                        double scale, PrintAttributes propeties) throws ReadException {
804

    
805
                if (/*!isOpen() ||*/ !isVisible() || !isWithinScale(scale))
806
                        return;
807
                
808
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
809
                SimpleTaskStatus taskStatus = new RasterTaskStatus("Printing raster " + getName() + "...", cancel);
810
                manager.add(taskStatus);
811
                taskStatus.setAutoremove(true);
812

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

    
836
        /*public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
837
                        double scale) throws ReadException {
838
                if(!isOpen())
839
                        return;
840

841
                // Para no pedir imagenes demasiado grandes, vamos
842
                // a hacer lo mismo que hace EcwFile: chunkear.
843
                // Llamamos a drawView con cuadraditos m?s peque?os
844
                // del BufferedImage ni caso, cuando se imprime viene con null
845

846
                int numW, numH;
847
                int stepX, stepY;
848
                int xProv, yProv;
849
                int A = 1500;
850
                int H = 1500;
851
                int altoAux, anchoAux;
852

853
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
854

855
                // Vamos a hacerlo en trozos de AxH
856
                Rectangle r = g.getClipBounds();
857
                numW = (r.width) / A;
858
                numH = (r.height) / H;
859

860
                double[] srcPts = new double[8];
861
                double[] dstPts = new double[8];
862

863
                yProv = r.y;
864
                for (stepY = 0; stepY < numH + 1; stepY++) {
865
                        if ((yProv + H) > r.getMaxY())
866
                                altoAux = (int) r.getMaxY() - yProv;
867
                        else
868
                                altoAux = H;
869

870
                        xProv = r.x;
871
                        for (stepX = 0; stepX < numW + 1; stepX++) {
872
                                if ((xProv + A) > r.getMaxX())
873
                                        anchoAux = (int) r.getMaxX() - xProv;
874
                                else
875
                                        anchoAux = A;
876

877
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
878

879
                                // Parte que dibuja
880
                                srcPts[0] = xProv;
881
                                srcPts[1] = yProv;
882
                                srcPts[2] = xProv + anchoAux + 1;
883
                                srcPts[3] = yProv;
884
                                srcPts[4] = xProv + anchoAux + 1;
885
                                srcPts[5] = yProv + altoAux + 1;
886
                                srcPts[6] = xProv;
887
                                srcPts[7] = yProv + altoAux + 1;
888

889
                                try {
890
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
891
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
892
                                        // Extent extent = new Extent(rectCuadricula);
893

894
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
895
                                        ViewPort vp = (ViewPort)viewPort.clone();
896
                                        vp.setImageSize(tam);
897
                                        Envelope env = geomManager.createEnvelope(rectCuadricula
898
                                                        .getMinX(), rectCuadricula.getMinY(),
899
                                                        rectCuadricula.getMaxX(), rectCuadricula.getMaxY(),
900
                                                        SUBTYPES.GEOM2D);
901
                                        vp.setEnvelope(env);
902
                                        vp.setAffineTransform(mat);
903
                                        draw(null, g, vp, cancel, scale);
904

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

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

    
937
                // Salva a RMF
938
                if (getDataStore() != null)
939
                        // Guardamos la GeoReferenciacion de cada dataset
940
                        try {
941
                                getDataStore().saveGeoreferencingToRmf();
942
                        } catch (Exception e) {
943
                                logger.info("error_salvando_rmf", e);
944
                        }
945

    
946
                        if (this.isRemoveRasterFlag()) {
947
                                if (getDataStore() != null) {
948
                                        String[] files = getFileName().clone();
949

    
950
                                        try {
951
                                                getDataStore().close();
952
                                        } catch (CloseException e) {
953
                                        }
954

    
955
                                        dataStore = null;
956
                                        if(render != null)
957
                                                render.dispose();
958
                                        render = null;
959
                                        // System.gc();
960
                                        this.setRemoveRasterFlag(true);
961

    
962
                                        for (int i = 0; i < files.length; i++) {
963
                                                File file = new File(files[i]);
964
                                                File dirTemp = fileUtil.getTemporalFile();
965
                                                if(!file.exists())
966
                                                        continue;
967
                                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
968
                                                        file.delete();
969

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

    
988
        public boolean isRemoveRasterFlag() {
989
                return removeRasterFlag;
990
        }
991

    
992
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
993
                this.removeRasterFlag = removeRasterFlag;
994
        }
995

    
996
        public String getTocImageIcon() {
997
                return "map-ok-ico";
998
        }
999

    
1000
        public int[] getTileSize() {
1001
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1002
                return size;
1003
        }
1004

    
1005
        public boolean isTiled() {
1006
                return mustTileDraw;
1007
        }
1008

    
1009
        public boolean isGeoreferenced() {
1010
                return getDataStore().isGeoreferenced();
1011
        }
1012

    
1013
        public NoData getNoDataValue() {
1014
                return getDataStore().getNoDataValue();
1015
        }
1016

    
1017
        /**
1018
         * Sets the nodata value for this layer
1019
         * @param nd
1020
         */
1021
        public void setNoDataValue(NoData nd) {
1022
                if (getDataStore() != null)
1023
                        getDataStore().setNoDataValue(nd);
1024
        }
1025

    
1026
        /**
1027
         * Gets the height in world coordinates of this raster layer
1028
         */
1029
        public double getWCHeight() {
1030
                return getFullEnvelope().getMaximum(1);
1031
        }
1032

    
1033
        /**
1034
         * Gets the width in world coordinates of this raster layer
1035
         */
1036
        public double getWCWidth() {
1037
                return getFullEnvelope().getMaximum(0);
1038
        }
1039

    
1040
        /**
1041
         * Gets the size of all files of this raster layer
1042
         */
1043
        public long[] getFileSize() {
1044
                if (getDataStore() == null)
1045
                        return null;
1046

    
1047
                return getDataStore().getFileSizeByProvider();
1048
        }
1049

    
1050
        /**
1051
         * Gets the list of file names
1052
         */
1053
        public String[] getFileName() {
1054
                if (getDataStore() == null)
1055
                        return null;
1056

    
1057
                return getDataStore().getURIByProvider();
1058
        }
1059

    
1060
        /**
1061
         * Returns the number of files in this raster layer
1062
         */
1063
        public int getFileCount() {
1064
                return getDataStore().getProviderCount();
1065
        }
1066

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

    
1086
        public int[] getDataType() {
1087
                return getDataStore().getDataType();
1088
        }
1089

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

    
1209
        public int[] getBandCountFromDataset() {
1210
                return getDataStore().getBandCountByProvider();
1211
        }
1212

    
1213
        public String getColorInterpretation(int band, int dataset) {
1214
                if (this.getDataStore().getColorInterpretation().get(band) == null)
1215
                        return "Undefined";
1216
                return this.getDataStore().getColorInterpretation().get(band);
1217
        }
1218

    
1219
        public String getWktProjection() throws RasterDriverException {
1220
                return getDataStore().getWktProjection();
1221
        }
1222

    
1223
        public boolean isRGB() {
1224
                if ((getDataStore() == null) || (render == null))
1225
                        return false;
1226

    
1227
                if (getDataStore().getDataType()[0] != Buffer.TYPE_BYTE)
1228
                        return false;
1229

    
1230
                boolean R = false;
1231
                boolean G = false;
1232
                boolean B = false;
1233

    
1234
                int[] renderBands = render.getRenderColorInterpretation().buildRenderBands();
1235
                for (int i = 0; i < renderBands.length; i++)
1236
                        if (renderBands[i] >= 0)
1237
                                switch (i) {
1238
                                        case 0:
1239
                                                R = true;
1240
                                                break;
1241
                                        case 1:
1242
                                                G = true;
1243
                                                break;
1244
                                        case 2:
1245
                                                B = true;
1246
                                                break;
1247
                                }
1248

    
1249
                if (R && G && B)
1250
                        return true;
1251

    
1252
                return false;
1253
        }
1254

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

    
1279
        /**
1280
         * @deprecated Don't use a <code>Grid</code> object. This will be removed soon
1281
         */
1282
        public Grid getReadOnlyFullGrid(boolean interpolated) throws GridException, InterruptedException {
1283
                RasterQuery query = rManager.createQuery();
1284
                query.setReadOnly(true);
1285
                query.setAllDrawableBands();
1286
                Buffer bf = null;
1287
                try {
1288
                        query.setAreaOfInterest();
1289
                        bf = getDataStore().query(query);
1290
                } catch (QueryException e) {
1291
                        throw new GridException("Error reading buffer");
1292
                } catch (ProcessInterruptedException e) {
1293
                        throw new InterruptedException("Carga interrumpida");
1294
                } 
1295
                return rManager.createGrid(bf, getDataStore(), interpolated);
1296
        }
1297

    
1298
        /**
1299
         * Obtiene el tama?o de celda de la fuente de datos
1300
         * @return double con el tama?o de celda
1301
         */
1302
        public double getCellSize() {
1303
                return (getDataStore() != null) ? getDataStore().getCellSize() : 1;
1304
        }
1305

    
1306
        public Extent getFullRasterExtent() {
1307
                return this.getDataStore().getExtent();
1308
        }
1309

    
1310

    
1311
        /**
1312
         * Devuelve el fichero asociado a la capa o null si no tiene.
1313
         * @return Fichero.
1314
         */
1315
        public File getFile() {
1316
                if(getDataStore().getParameters() instanceof RasterFileStoreParameters)
1317
                        return ((RasterFileStoreParameters)getDataStore().getParameters()).getFile();
1318
                return new File("");
1319
        }
1320

    
1321
        /**
1322
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1323
         * @param file Fichero a consultar
1324
         * @return true si es aceptado y false si no lo es.
1325
         */
1326
        public boolean isFileAccepted(File file) {
1327
                return getDataStore().isFileSupported(file.getName());
1328
        }
1329
        
1330
        /**
1331
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1332
         * @param file Fichero a consultar
1333
         * @return true si es aceptado y false si no lo es.
1334
         */
1335
        public static boolean isFileSupported(File file) {
1336
                return RasterLocator.getManager().getProviderServices().isExtensionSupported(file.getName());
1337
        }
1338

    
1339
        public boolean existColorTable() {
1340
                return getRender().existColorTable();
1341
        }
1342

    
1343
        /**
1344
         * Returns true if the data store has an alpha band
1345
         */
1346
        public boolean existsAlphaBand() {
1347
                if(getDataStore().getColorInterpretation() != null)
1348
                        return getDataStore().getColorInterpretation().hasAlphaBand();
1349
                else
1350
                        return false;
1351
        }
1352

    
1353
        public int getAlphaBandNumber() {
1354
                if(getDataStore().getColorInterpretation() != null)
1355
                        return getDataStore().getColorInterpretation().getBand(ColorInterpretation.ALPHA_BAND);
1356
                return -1;
1357
        }
1358

    
1359
        /**
1360
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1361
         * capa busque una leyenda valida.
1362
         * @param ct
1363
         */
1364
        public void setLastLegend(ColorTable ct) {
1365
                lastLegend = ColorTableLegend.createLegend(ct);
1366
        }
1367

    
1368
        /**
1369
         * Devuelve la Leyenda de la capa.
1370
         * @return Leyenda.
1371
         */
1372
        public ILegend getLegend() {
1373
                if (lastLegend != null)
1374
                        return lastLegend;
1375

    
1376
                return null;
1377
        }
1378

    
1379
        public void addLegendListener(LegendListener listener) {
1380
                layerChangeSupport.addLayerListener(listener);
1381
        }
1382

    
1383
        public int getShapeType() {
1384
                return TYPES.SURFACE;
1385
        }
1386

    
1387
        public void removeLegendListener(LegendListener listener) {
1388
                if(layerChangeSupport != null)
1389
                        layerChangeSupport.removeLayerListener(listener);
1390
        }
1391

    
1392
        public boolean isInside(Point2D p) {
1393
                 return getDataStore().isInside(p);
1394
        }
1395

    
1396
        public AffineTransform getAffineTransform() {
1397
                return getDataStore().getAffineTransform();
1398
        }
1399

    
1400
        public void setAffineTransform(AffineTransform transf) {
1401
                if(transf == null)
1402
                        return;
1403
                affineTransformList.add(transf);
1404
                getDataStore().setAffineTransform(transf);
1405
                updateDrawVersion();
1406
        }
1407

    
1408
        public void setAffineTransformWithoutHistorical(AffineTransform transf) {
1409
                getDataStore().setAffineTransform(transf);
1410
                updateDrawVersion();
1411
        }
1412

    
1413
        public Historical getAffineTransformHistorical() {
1414
                return this.affineTransformList;
1415
        }
1416

    
1417
        public void saveGeoToRmf() throws RmfSerializerException {
1418
                if (!isOpen())
1419
                        return;
1420

    
1421
                getDataStore().saveGeoreferencingToRmf();
1422
                
1423
                affineTransformList.clear();
1424
                affineTransformList.add(this.getAffineTransform());
1425
        }
1426

    
1427
        public boolean isActionEnabled(int action) {
1428
                switch (action) {
1429
                        case IRasterLayerActions.BANDS_FILE_LIST:
1430
                                if (existColorTable() || getDataStore().isMosaic())
1431
                                        return false;
1432
                                break;
1433
                        case IRasterLayerActions.BANDS_RGB:
1434
                                if (existColorTable())
1435
                                        return false;
1436
                                break;
1437
                        case IRasterLayerActions.REPROJECT:
1438
                                if (!isReproyectable())
1439
                                        return false;
1440
                                break;
1441
                        case IRasterLayerActions.CREATEOVERVIEWS:
1442
                                return overviewsSupport();
1443
                        case IRasterLayerActions.OPACITY:
1444
                        case IRasterLayerActions.TRANSPARENCY:
1445
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1446
                        case IRasterLayerActions.ENHANCED:
1447
                        case IRasterLayerActions.PANSHARPENING:
1448
                        case IRasterLayerActions.SELECT_LAYER:
1449
                        case IRasterLayerActions.SAVE_COLORINTERP:
1450
                                return true;
1451
                        case IRasterLayerActions.REMOTE_ACTIONS:
1452
                                return false;
1453
                        case IRasterLayerActions.TAILTRIM:
1454
                        case IRasterLayerActions.GEOLOCATION:
1455
                                return !(getDataStore().isTiled());
1456
                }
1457
                return true;
1458
        }
1459

    
1460
        public void setVisible(boolean visibility) {
1461
                if(visibility)
1462
                        state.disableStopped();
1463
                else
1464
                        enableStopped();
1465

    
1466
                if(isAwake() || isClosed())
1467
                        try {
1468
                                this.load();
1469
                        } catch (LoadLayerException e) {
1470
                                e.printStackTrace();
1471
                        }
1472

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

    
1488
                super.setVisible(visibility);
1489
        }
1490

    
1491
        /**
1492
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1493
         * @return valor de transparencia
1494
         */
1495
        public int getTransparency() {
1496
                try {
1497
                        return getRender().getRenderingTransparency().getOpacity();
1498
                } catch (NullPointerException e) {
1499
                        return super.getTransparency();
1500
                }
1501
        }
1502

    
1503
        /**
1504
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1505
         * o no.
1506
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1507
         */
1508
        public boolean isTransparent() {
1509
                return getRender().getRenderingTransparency().isTransparencyActive();
1510
        }
1511

    
1512
        /**
1513
         * Asigna la transparencia de la siguiente renderizaci?n
1514
         * @param valor de transparencia
1515
         */
1516
        public void setTransparency(int trans) {
1517
                super.setTransparency(trans);
1518
                try {
1519
                        getRender().getRenderingTransparency().setOpacity(trans);
1520
                } catch (NullPointerException e) {
1521
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1522
                }
1523
        }
1524

    
1525
        public List<ROI> getRois() throws ROIException {
1526
                return getDataStore().getRois(getMapContext().getProjection());
1527
        }
1528

    
1529
        public void setRois(List<ROI> rois) {
1530
                getDataStore().setRois(rois);
1531
        }
1532
        
1533
        public void setROIsFiles(List<File> file) throws RmfSerializerException {
1534
                getDataStore().saveROIFileListToRmf(file);
1535
        }
1536
        
1537
        public List<File> getROIsFiles() throws RmfSerializerException {
1538
                return getDataStore().getROIFileListFromRmf();
1539
        }
1540

    
1541
        /**
1542
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1543
         * devolver? null.
1544
         * @return TreeMap con la lista de capas a dibujar
1545
         */
1546
        public HashMap<DefaultFLyrRaster, Boolean> getRasterStrategy() {
1547
                if(strategy != null)
1548
                        return strategy.getStrategy();
1549
                return null;
1550
        }
1551

    
1552
        /**
1553
         * @return the configuration
1554
         */
1555
        static public IConfiguration getConfiguration() {
1556
                return configuration;
1557
        }
1558

    
1559
        /**
1560
         * @param configuration the configuration to set
1561
         */
1562
        static public void setConfiguration(IConfiguration configuration) {
1563
                DefaultFLyrRaster.configuration = configuration;
1564
        }
1565

    
1566
        public void reload() throws ReloadLayerException {
1567
                try {
1568
                        super.reload();
1569
                        load();
1570
                        if (isStopped())
1571
                                disableStopped();
1572
                        if (getMapContext() != null)
1573
                                getMapContext().invalidate();
1574
                } catch (LoadLayerException e) {
1575
                        setAvailable(false);
1576
                        throw new ReloadLayerException(getName(), e);
1577
                }
1578
        }
1579

    
1580
        /**
1581
         * Devuelve si la capa tiene soporte para poder generar overviews
1582
         * @return
1583
         */
1584
        public boolean overviewsSupport() {
1585
                if ((getDataStore() != null) && (getDataStore().overviewsSupport()))
1586
                        return true;
1587

    
1588
                return false;
1589
        }
1590

    
1591
        /**
1592
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1593
         * en escala de grises
1594
         * @return
1595
         */
1596
        public boolean isRenderingAsGray() {
1597
                int[] renderBands = getRender().getRenderColorInterpretation().buildRenderBands();
1598
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1599
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1600
                        return true;
1601
                return false;
1602
        }
1603

    
1604
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1605
                updateDrawVersion();
1606
        }
1607

    
1608
        public Point2D adjustWorldRequest(Point2D req) {
1609
                Envelope ext = null;
1610

    
1611
                ext = getFullEnvelope();
1612
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
1613
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
1614
                return req;
1615
        }
1616

    
1617
        public FLayer cloneLayer() throws Exception {
1618
                RasterDataStore  ds = getDataStore().cloneDataStore();
1619
                DefaultFLyrRaster newLayer = new DefaultFLyrRaster();
1620
                newLayer.setName(getName());
1621
                newLayer.setOpenRasterStore(ds);
1622
                newLayer.firstLoad = firstLoad;
1623
                
1624
                List<RasterFilter> filters = getRender().getFilterList().getStatusCloned();
1625

    
1626
                //Hacemos una copia de las bandas a renderizar
1627
                if(getRender().getRenderColorInterpretation() != null) {
1628
                        newLayer.getRender().setRenderColorInterpretation(getRender().getRenderColorInterpretation().cloneColorInterpretation());
1629
                }
1630

    
1631
                //Asignamos el entorno
1632
                if(newLayer.getRender().getFilterList() == null)
1633
                        newLayer.getRender().setFilterList(RasterLocator.getManager().createEmptyFilterList(getRender().getFilterList().getInitDataType()));
1634
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
1635
                newLayer.getRender().getFilterList().setStatus(filters);
1636

    
1637
                // Asignamos los valores noData del original
1638
                newLayer.setNoDataValue(getNoDataValue());
1639
                if(getDataStore().getNoDataValue().isDefined())
1640
                        newLayer.setNoDataTransparent(true);
1641
                newLayer.enableOpen();
1642
                
1643
                return newLayer;
1644
        }
1645
        
1646
        public FLayer getFileLayer() throws RasterDriverException {
1647
                try {
1648
                        return cloneLayer();
1649
                } catch (Exception e) {
1650
                }
1651
                return null;
1652
        }
1653
        
1654
        public void addFile(String file) throws InvalidSourceException {
1655
                getDataStore().addFile(file);
1656
        }
1657
        
1658
        public void removeFile(String file) {
1659
                getDataStore().removeFile(file);
1660
        }
1661

    
1662
        /*****************************************************/
1663

    
1664
        public void disableStopped() {
1665
                if(state != null)
1666
                        state.disableStopped();
1667
        }
1668

    
1669
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1670

    
1671
        public void enableClosed() throws NotAvailableStateException {
1672
                if(state != null)
1673
                        state.enableClosed();
1674
        }
1675

    
1676
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1677

    
1678
        public void enableStopped() {state.enableStopped();}
1679

    
1680
        public boolean isAwake() {return state.isAwake();}
1681

    
1682
        public boolean isClosed() {return state.isClosed();}
1683

    
1684
        public boolean isOpen() {return state.isOpen();}
1685

    
1686
        public boolean isStopped() {return state.isStopped();}
1687

    
1688

    
1689
        @SuppressWarnings("rawtypes")
1690
        public Set getMetadataChildren() {
1691
                return null;
1692
        }
1693

    
1694
        public Object getMetadataID() {
1695
                return getName();
1696
        }
1697

    
1698
        public String getMetadataName() {
1699
                return null;
1700
        }
1701

    
1702
        public RasterDataStore getDataStore() {
1703
                if(dataStore != null) {
1704
                        RasterDataParameters params = (RasterDataParameters)dataStore.getParameters();
1705
                        if (getCoordTrans() != null && params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
1706
                                this.dataStore.setCoordTrans(getCoordTrans());
1707
                        }
1708
                }
1709
                return this.dataStore;
1710
        }
1711
        
1712
        public IProjection getProjection() {
1713
                RasterDataParameters p = (RasterDataParameters)getDataStore().getParameters();
1714
                if(p.getReprojectionOption() == RasterDataParameters.DONT_CHANGE_PROJECTION)
1715
                        return null;
1716
                return getDataStore().getProjection();
1717
        }
1718

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

    
1764
        /**
1765
         * When a process is using information of this layer this variable will contain
1766
         * the thread ID.
1767
         * @param readingData
1768
         */
1769
        public synchronized void setReadingData(String readingData) {
1770
                this.readingData = readingData;
1771
        }
1772
        
1773
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel,
1774
                        boolean fast)
1775
                        throws LoadLayerException, DataException {
1776
                return null;
1777
        }
1778

    
1779
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel)
1780
                        throws LoadLayerException, DataException {
1781
                return null;
1782
        }
1783

    
1784
        @Override
1785
        protected void doDispose() throws BaseException {
1786
                if(render != null)
1787
                        render.dispose();
1788
                if(getDataStore() != null)
1789
                        getDataStore().dispose();
1790
                finalize();
1791
        }
1792

    
1793
        public int getZoomLevel() {
1794
                return zoomLevel;
1795
        }
1796

    
1797
        public void setZoomLevel(int zoomLevel) {
1798
                this.zoomLevel = zoomLevel;
1799
        }
1800
        
1801
        public boolean increaseZoomLevel() {
1802
                if(zoomLevel < (this.getDataStore().getZoomLevels() - 1)) { 
1803
                        zoomLevel ++;
1804
                        recalcLevel = false;
1805
                        return true;
1806
                }
1807
                return false;
1808
        }
1809
        
1810
        public boolean decreaseZoomLevel() {
1811
                if(zoomLevel > 0) { 
1812
                        zoomLevel --;
1813
                        recalcLevel = false;
1814
                        return true;
1815
                }
1816
                return false;
1817
        }
1818
        
1819
        public Envelope getCoordsInLevel(Point2D center, int level, int w, int h) throws CreateEnvelopeException {
1820
                Extent ex = getDataStore().getCoordsInLevel(center, level, w, h);
1821
                return geomManager.createEnvelope(ex.getULX(), ex.getULY(), ex.getLRX(), ex.getLRY(), SUBTYPES.GEOM2D);
1822
        }
1823
        
1824
        public boolean isEnabledMultiresolution() {
1825
                return getDataStore().isTiled();
1826
        }
1827
        
1828
        public void setTileServer(Class<?> tileServer) throws InitializeException {
1829
                getDataStore().setTileServer(tileServer);
1830
        }
1831
        
1832
        @Override
1833
        public void loadFromState(PersistentState state)
1834
                        throws PersistenceException {
1835
                try {
1836
                        super.loadFromState(state);
1837
                        this.dataStore = (RasterDataStore)state.get("rasterdatastore");
1838
                } catch (PersistenceRuntimeException e) {
1839
                        logger.debug("Unable to load store from persistence in layer: " + this.getName(), e);
1840
                        this.setAvailable(false);
1841
                        return;
1842
                }
1843
                this.lastLegend = (ILegend)state.get("legend");
1844
                this.colorTableLoadedFromProject = (ColorTable)state.get("colortable");
1845
                this.zoomLevel = state.getInt("zoomLevel");
1846
                this.recalcLevel = state.getBoolean("recalcLevel");
1847
                loadedFromProject = true;
1848
        }
1849

    
1850
        @Override
1851
        public void saveToState(PersistentState state) throws PersistenceException {
1852
                super.saveToState(state);
1853
                
1854
                state.set("rasterdatastore", getDataStore());        
1855
                state.set("legend", lastLegend);        
1856
                state.set("colortable", getRender().getColorTable());        
1857
                state.set("zoomLevel", zoomLevel);        
1858
                state.set("recalcLevel", recalcLevel);        
1859
        }        
1860
        
1861
        public static void registerPersistence() {
1862
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
1863
                DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
1864
                if( definition == null ) {
1865
                        if (manager.getDefinition(FLyrDefault.class) == null) {
1866
                                FLyrDefault.registerPersistent();
1867
                        }
1868
                        definition = manager.addDefinition(
1869
                                        DefaultFLyrRaster.class,
1870
                                        PERSISTENT_NAME,
1871
                                        PERSISTENT_DESCRIPTION,
1872
                                        null, 
1873
                                        null
1874
                        );
1875
                        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE, "FLyrDefault");
1876
                        
1877
                        registerPersistence(definition);
1878
                }
1879
        }
1880
        
1881
        public static void registerPersistence(DynStruct definition) {
1882
                definition.addDynFieldObject("rasterdatastore").setClassOfValue(RasterDataStore.class).setMandatory(false);
1883
                definition.addDynFieldObject("legend").setClassOfValue(ILegend.class).setMandatory(false);
1884
                definition.addDynFieldObject("colortable").setClassOfValue(ColorTable.class).setMandatory(false);
1885
                definition.addDynFieldInt("zoomlevel").setMandatory(false);
1886
                definition.addDynFieldBoolean("recalcLevel").setMandatory(false);
1887
        }
1888

    
1889
        public GeometryType getGeometryType() throws ReadException {
1890
                try {
1891
                        return GeometryLocator.getGeometryManager().getGeometryType(TYPES.SURFACE, SUBTYPES.GEOM2D);
1892
                } catch (GeometryTypeNotSupportedException e) {
1893
                        throw new ReadException(getDataStore().getName(), e);
1894
                } catch (GeometryTypeNotValidException e) {
1895
                        throw new ReadException(getDataStore().getName(), e);
1896
                } 
1897
        }
1898
        
1899
        public void setDataStore(DataStore dataStore, String domain) throws LoadLayerException {
1900
                setDataStore(dataStore);
1901
        }
1902
        
1903
        protected void finalize() {
1904
                layerChangeSupport             = null;
1905
                state                          = null;
1906
                lastLegend                     = null;
1907
                colorTableLoadedFromProject    = null;
1908
                strategy                       = null;
1909
                configuration                  = null;
1910
                fileUtil                       = null;
1911
                rasterUtil                     = null;
1912
                crsUtil                        = null;
1913
                mathUtil                       = null;
1914
                uri                            = null;
1915
                affineTransformList            = null;
1916
                readingData                    = null;
1917
                dataStore                      = null;
1918
                render                         = null;
1919
        }
1920

    
1921
}