Statistics
| Revision:

gvsig-raster / org.gvsig.raster / trunk / org.gvsig.raster / org.gvsig.raster.fmap / src / main / java / org / gvsig / raster / fmap / layers / DefaultFLyrRaster.java @ 2840

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

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

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

    
246
                return lyr;
247
        }
248

    
249
        public void setName(String name) {
250
                super.setName(name);
251

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

    
262
        public void wakeUp(){
263
                try {
264
                        reload();
265
                } catch (ReloadLayerException e) {
266
                        // No se ha podido recuperar la capa con exito
267
                }
268
        }
269

    
270
        public void load() throws LoadLayerException {
271
                if (isStopped() || getDataStore() == null)
272
                        return;
273

    
274
                enableStopped(); // Paramos la capa mientras se hace un load
275

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

    
292
                if (test != -1) {
293
                        String urlECW = uri.substring(test + 6);
294
                        uri = "ecwp://" + urlECW;
295
                        System.err.println(test + " " + uri);
296
                }
297

    
298
                try {
299
                        if(!getDataStore().isOpen())
300
                                dataStore = rManager.getProviderServices().open(params);
301
                        else
302
                                dataStore.reload();
303
                } catch (NotSupportedExtensionException e) {
304
                        throw new LoadLayerException(this.getName());
305
                } catch (RasterDriverException e) {
306
                        throw new LoadLayerException(this.getName());
307
                }
308
        }
309
        
310
        public void setLayerInitialized(boolean initialized) {
311
                layerInitialize = initialized;
312
        }
313

    
314
        /**
315
         * Acciones de inicializaci?n despu?s de que la fuente de datos
316
         * de la capa est? asignada. 
317
         * @throws FilePaletteException 
318
         */
319
        public void init() throws LoadLayerException, FilePaletteException {
320
                layerInitialize = true;
321
                
322
                if (getDataStore() == null)
323
                        throw new LoadLayerException("Formato no valido", new IOException());
324

    
325
                render = getDataStore().getRender();
326
                render.addVisualPropertyListener(this);
327
                initFilters();
328

    
329
                //Inicializaci?n del historico de transformaciones
330
                affineTransformList.clear();
331
                affineTransformList.add(this.getAffineTransform());
332

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

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

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

    
373
        public void setNoDataTransparent(boolean t) {
374
                getNoDataValue().setNoDataTransparent(t);
375
                if(getRender().getRenderingTransparency() != null) {
376
                        getRender().getRenderingTransparency().setNoData(getDataStore().getNoDataValue());
377
                        getRender().getRenderingTransparency().activeTransparency();
378
                }
379
        }
380

    
381
        /**
382
         * Initializes the filter list to render this raster layer
383
         * @throws FilePaletteException 
384
         */
385
        protected void initFilters() throws FilePaletteException {
386
                if(getDataType() == null)
387
                        return;
388
                        
389
                RasterFilterList filterList = rManager.createEmptyFilterList(getDataType()[0]);
390
                if(loadedFromProject) {
391
                        filterList = getDataStore().getRender().getFilterList();
392
                }
393

    
394
                if(getDataStore() == null)
395
                        return;
396
                
397
                if(getDataStore().getNoDataValue() != null) {
398
                        getDataStore().getNoDataValue().load();
399
                }
400

    
401
                filterList.setInitDataType(getDataType()[0]);
402

    
403
                // Quitamos la leyenda
404
                lastLegend = null;
405

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

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

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

    
456
                String palettesPath = System.getProperty("user.home") +
457
                File.separator +
458
                "gvSIG" + // PluginServices.getArguments()[0] +
459
                File.separator + "colortable";
460

    
461
                Statistics stats = getDataStore().getStatistics();
462
                ColorTableLibrary colorTableLibrary = rManager.getDataStructFactory().getColorTableLibrary();
463

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

    
476
                                                        ColorTable colorTable = colorTableLibrary.createColorTable();
477
                                                        colorTable.setName(paletteName);
478
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
479
                                                        colorTable.setInterpolated(true);
480

    
481
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
482

    
483
                                                        setLastLegend(colorTable);
484

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

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

    
514
        public boolean isReproyectable() {
515
                if (getDataStore() == null)
516
                        return false;
517
                return getDataStore().isReproyectable();
518
        }
519

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

    
542
                try {
543
                        if (!isOpen())
544
                                return;
545

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

    
557
                        strategy = new RasterDrawStrategy(getMapContext(), this);
558
                        strategy.stackStrategy();
559
                        HashMap<DefaultFLyrRaster, Boolean> tStr = strategy.getStrategy();
560
                        if (tStr != null &&
561
                                tStr.get(this) != null &&
562
                                ((Boolean) (tStr.get(this))).booleanValue() == false) {
563
                                disableStopped();
564
                                return;
565
                        }
566

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

    
595
                        }
596
                        
597
                        //callLegendChanged(null);
598
                } finally {
599
                        disableStopped();
600
                        task.setEvent(null);
601
                }
602
        }
603

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

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

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

    
673
                Rectangle2D e = getDataStore().getExtent().toRectangle2D();
674
                try {
675
                        return geomManager.createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
676
                                        .getMaxY(), SUBTYPES.GEOM2D);
677

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

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

    
713
        public double getMaxX() {
714
                if(getFullEnvelope() != null)
715
                        return getFullEnvelope().getMaximum(0);
716
                return -1;
717
        }
718

    
719
        public double getMaxY() {
720
                if(getFullEnvelope() != null)
721
                        return this.getFullEnvelope().getMaximum(1);
722
                return -1;
723
        }
724

    
725
        public double getMinX() {
726
                if(getFullEnvelope() != null)
727
                        return getFullEnvelope().getMinimum(0);
728
                return -1;
729
        }
730

    
731
        public double getMinY() {
732
                if(getFullEnvelope() != null)
733
                        return getFullEnvelope().getMinimum(1);
734
                return -1;
735
        }
736

    
737
        public String queryByPoint(Point p) {
738
                if (!isOpen())
739
                        return null;
740
                ColorConversion conv = rManager.getColorConversion();
741

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

    
744
                ArrayList<Object> attr = getAttributes();
745
                data += "  <raster\n";
746
                data += "    File=\"" + getFile() + "\"\n";
747
                for (int i = 0; i < attr.size(); i++) {
748
                        Object[] a = (Object[]) attr.get(i);
749

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

    
768
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
769
                return data;
770
        }
771

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

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

    
798
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
799
                        double scale, PrintAttributes propeties) throws ReadException {
800

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

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

    
832
        /*public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
833
                        double scale) throws ReadException {
834
                if(!isOpen())
835
                        return;
836

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

842
                int numW, numH;
843
                int stepX, stepY;
844
                int xProv, yProv;
845
                int A = 1500;
846
                int H = 1500;
847
                int altoAux, anchoAux;
848

849
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
850

851
                // Vamos a hacerlo en trozos de AxH
852
                Rectangle r = g.getClipBounds();
853
                numW = (r.width) / A;
854
                numH = (r.height) / H;
855

856
                double[] srcPts = new double[8];
857
                double[] dstPts = new double[8];
858

859
                yProv = r.y;
860
                for (stepY = 0; stepY < numH + 1; stepY++) {
861
                        if ((yProv + H) > r.getMaxY())
862
                                altoAux = (int) r.getMaxY() - yProv;
863
                        else
864
                                altoAux = H;
865

866
                        xProv = r.x;
867
                        for (stepX = 0; stepX < numW + 1; stepX++) {
868
                                if ((xProv + A) > r.getMaxX())
869
                                        anchoAux = (int) r.getMaxX() - xProv;
870
                                else
871
                                        anchoAux = A;
872

873
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
874

875
                                // Parte que dibuja
876
                                srcPts[0] = xProv;
877
                                srcPts[1] = yProv;
878
                                srcPts[2] = xProv + anchoAux + 1;
879
                                srcPts[3] = yProv;
880
                                srcPts[4] = xProv + anchoAux + 1;
881
                                srcPts[5] = yProv + altoAux + 1;
882
                                srcPts[6] = xProv;
883
                                srcPts[7] = yProv + altoAux + 1;
884

885
                                try {
886
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
887
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
888
                                        // Extent extent = new Extent(rectCuadricula);
889

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

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

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

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

    
942
                        if (this.isRemoveRasterFlag()) {
943
                                if (getDataStore() != null) {
944
                                        String[] files = getFileName().clone();
945

    
946
                                        try {
947
                                                getDataStore().close();
948
                                        } catch (CloseException e) {
949
                                        }
950

    
951
                                        dataStore = null;
952
                                        if(render != null)
953
                                                render.dispose();
954
                                        render = null;
955
                                        // System.gc();
956
                                        this.setRemoveRasterFlag(true);
957

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

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

    
984
        public boolean isRemoveRasterFlag() {
985
                return removeRasterFlag;
986
        }
987

    
988
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
989
                this.removeRasterFlag = removeRasterFlag;
990
        }
991

    
992
        public String getTocImageIcon() {
993
                return "map-ok-ico";
994
        }
995

    
996
        public int[] getTileSize() {
997
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
998
                return size;
999
        }
1000

    
1001
        public boolean isTiled() {
1002
                return mustTileDraw;
1003
        }
1004

    
1005
        public boolean isGeoreferenced() {
1006
                return getDataStore().isGeoreferenced();
1007
        }
1008

    
1009
        public NoData getNoDataValue() {
1010
                return getDataStore().getNoDataValue();
1011
        }
1012

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

    
1022
        /**
1023
         * Gets the height in world coordinates of this raster layer
1024
         */
1025
        public double getWCHeight() {
1026
                return getFullEnvelope().getMaximum(1);
1027
        }
1028

    
1029
        /**
1030
         * Gets the width in world coordinates of this raster layer
1031
         */
1032
        public double getWCWidth() {
1033
                return getFullEnvelope().getMaximum(0);
1034
        }
1035

    
1036
        /**
1037
         * Gets the size of all files of this raster layer
1038
         */
1039
        public long[] getFileSize() {
1040
                if (getDataStore() == null)
1041
                        return null;
1042

    
1043
                return getDataStore().getFileSizeByProvider();
1044
        }
1045

    
1046
        /**
1047
         * Gets the list of file names
1048
         */
1049
        public String[] getFileName() {
1050
                if (getDataStore() == null)
1051
                        return null;
1052

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

    
1056
        /**
1057
         * Returns the number of files in this raster layer
1058
         */
1059
        public int getFileCount() {
1060
                return getDataStore().getProviderCount();
1061
        }
1062

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

    
1082
        public int[] getDataType() {
1083
                return getDataStore().getDataType();
1084
        }
1085

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

    
1205
        public int[] getBandCountFromDataset() {
1206
                return getDataStore().getBandCountByProvider();
1207
        }
1208

    
1209
        public String getColorInterpretation(int band, int dataset) {
1210
                if (this.getDataStore().getColorInterpretation().get(band) == null)
1211
                        return "Undefined";
1212
                return this.getDataStore().getColorInterpretation().get(band);
1213
        }
1214

    
1215
        public String getWktProjection() throws RasterDriverException {
1216
                return getDataStore().getWktProjection();
1217
        }
1218

    
1219
        public boolean isRGB() {
1220
                if ((getDataStore() == null) || (render == null))
1221
                        return false;
1222

    
1223
                if (getDataStore().getDataType()[0] != Buffer.TYPE_BYTE)
1224
                        return false;
1225

    
1226
                boolean R = false;
1227
                boolean G = false;
1228
                boolean B = false;
1229

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

    
1245
                if (R && G && B)
1246
                        return true;
1247

    
1248
                return false;
1249
        }
1250

    
1251
        /**
1252
         * Obtiene el tama?o de celda de la fuente de datos
1253
         * @return double con el tama?o de celda
1254
         */
1255
        public double getCellSize() {
1256
                return (getDataStore() != null) ? getDataStore().getCellSize() : 1;
1257
        }
1258

    
1259
        public Extent getFullRasterExtent() {
1260
                return this.getDataStore().getExtent();
1261
        }
1262

    
1263

    
1264
        /**
1265
         * Devuelve el fichero asociado a la capa o null si no tiene.
1266
         * @return Fichero.
1267
         */
1268
        public File getFile() {
1269
                if(getDataStore().getParameters() instanceof RasterFileStoreParameters)
1270
                        return ((RasterFileStoreParameters)getDataStore().getParameters()).getFile();
1271
                return new File("");
1272
        }
1273

    
1274
        /**
1275
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1276
         * @param file Fichero a consultar
1277
         * @return true si es aceptado y false si no lo es.
1278
         */
1279
        public boolean isFileAccepted(File file) {
1280
                return getDataStore().isFileSupported(file.getName());
1281
        }
1282
        
1283
        /**
1284
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1285
         * @param file Fichero a consultar
1286
         * @return true si es aceptado y false si no lo es.
1287
         */
1288
        public static boolean isFileSupported(File file) {
1289
                return RasterLocator.getManager().getProviderServices().isExtensionSupported(file.getName());
1290
        }
1291

    
1292
        public boolean existColorTable() {
1293
                return getRender().existColorTable();
1294
        }
1295

    
1296
        /**
1297
         * Returns true if the data store has an alpha band
1298
         */
1299
        public boolean existsAlphaBand() {
1300
                if(getDataStore().getColorInterpretation() != null)
1301
                        return getDataStore().getColorInterpretation().hasAlphaBand();
1302
                else
1303
                        return false;
1304
        }
1305

    
1306
        public int getAlphaBandNumber() {
1307
                if(getDataStore().getColorInterpretation() != null)
1308
                        return getDataStore().getColorInterpretation().getBand(ColorInterpretation.ALPHA_BAND);
1309
                return -1;
1310
        }
1311

    
1312
        /**
1313
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1314
         * capa busque una leyenda valida.
1315
         * @param ct
1316
         */
1317
        public void setLastLegend(ColorTable ct) {
1318
                lastLegend = ColorTableLegend.createLegend(ct);
1319
        }
1320

    
1321
        /**
1322
         * Devuelve la Leyenda de la capa.
1323
         * @return Leyenda.
1324
         */
1325
        public ILegend getLegend() {
1326
                if (lastLegend != null)
1327
                        return lastLegend;
1328

    
1329
                return null;
1330
        }
1331

    
1332
        public void addLegendListener(LegendListener listener) {
1333
                layerChangeSupport.addLayerListener(listener);
1334
        }
1335

    
1336
        public int getShapeType() {
1337
                return TYPES.SURFACE;
1338
        }
1339

    
1340
        public void removeLegendListener(LegendListener listener) {
1341
                if(layerChangeSupport != null)
1342
                        layerChangeSupport.removeLayerListener(listener);
1343
        }
1344

    
1345
        public boolean isInside(Point2D p) {
1346
                 return getDataStore().isInside(p);
1347
        }
1348

    
1349
        public AffineTransform getAffineTransform() {
1350
                return getDataStore().getAffineTransform();
1351
        }
1352

    
1353
        public void setAffineTransform(AffineTransform transf) {
1354
                if(transf == null)
1355
                        return;
1356
                affineTransformList.add(transf);
1357
                getDataStore().setAffineTransform(transf);
1358
                updateDrawVersion();
1359
        }
1360

    
1361
        public void setAffineTransformWithoutHistorical(AffineTransform transf) {
1362
                getDataStore().setAffineTransform(transf);
1363
                updateDrawVersion();
1364
        }
1365

    
1366
        public Historical getAffineTransformHistorical() {
1367
                return this.affineTransformList;
1368
        }
1369

    
1370
        public void saveGeoToRmf() throws RmfSerializerException {
1371
                if (!isOpen())
1372
                        return;
1373

    
1374
                getDataStore().saveGeoreferencingToRmf();
1375
                
1376
                affineTransformList.clear();
1377
                affineTransformList.add(this.getAffineTransform());
1378
        }
1379

    
1380
        public boolean isActionEnabled(int action) {
1381
                switch (action) {
1382
                        case IRasterLayerActions.BANDS_FILE_LIST:
1383
                                if (existColorTable() || getDataStore().isMosaic())
1384
                                        return false;
1385
                                break;
1386
                        case IRasterLayerActions.BANDS_RGB:
1387
                                if (existColorTable())
1388
                                        return false;
1389
                                break;
1390
                        case IRasterLayerActions.REPROJECT:
1391
                                if (!isReproyectable())
1392
                                        return false;
1393
                                break;
1394
                        case IRasterLayerActions.CREATEOVERVIEWS:
1395
                                return overviewsSupport();
1396
                        case IRasterLayerActions.OPACITY:
1397
                        case IRasterLayerActions.TRANSPARENCY:
1398
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1399
                        case IRasterLayerActions.ENHANCED:
1400
                        case IRasterLayerActions.PANSHARPENING:
1401
                        case IRasterLayerActions.SELECT_LAYER:
1402
                        case IRasterLayerActions.SAVE_COLORINTERP:
1403
                                return true;
1404
                        case IRasterLayerActions.REMOTE_ACTIONS:
1405
                                return false;
1406
                        case IRasterLayerActions.TAILTRIM:
1407
                        case IRasterLayerActions.GEOLOCATION:
1408
                                return !(getDataStore().isTiled());
1409
                }
1410
                return true;
1411
        }
1412

    
1413
        public void setVisible(boolean visibility) {
1414
                if(visibility)
1415
                        state.disableStopped();
1416
                else
1417
                        enableStopped();
1418

    
1419
                if(isAwake() || isClosed())
1420
                        try {
1421
                                this.load();
1422
                        } catch (LoadLayerException e) {
1423
                                e.printStackTrace();
1424
                        }
1425

    
1426
                /*
1427
                 * Cuando se modifica la visibilidad de una capa raster se hace un updateDrawVersion de todas las
1428
                 * capas raster de ese MapContext. Esto es porque la estrategia utilizada por RasterDrawStrategy hace
1429
                 * que se cacheen en blanco las capas raster que est?n ocultas debajo de otras. Al hacer invisibles las
1430
                 * de arriba la cache que estaba en blanco hace que no se pinte nada. Para evitar esto las marcamos todas
1431
                 * como que han sido modificadas para que se vuelvan a leer.
1432
                 */
1433
                if(getMapContext() != null) {
1434
                        ArrayList<FLayer> listLayers = new ArrayList<FLayer>();
1435
                        listLayers = RasterDrawStrategy.getLayerList(getMapContext().getLayers(), listLayers);
1436
                        for (int i = 0; i < listLayers.size(); i++)
1437
                                if(listLayers.get(i) instanceof DefaultFLyrRaster)
1438
                                        ((DefaultFLyrRaster)listLayers.get(i)).updateDrawVersion();
1439
                }
1440

    
1441
                super.setVisible(visibility);
1442
        }
1443

    
1444
        /**
1445
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1446
         * @return valor de transparencia
1447
         */
1448
        public int getTransparency() {
1449
                try {
1450
                        return getRender().getRenderingTransparency().getOpacity();
1451
                } catch (NullPointerException e) {
1452
                        return super.getTransparency();
1453
                }
1454
        }
1455

    
1456
        /**
1457
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1458
         * o no.
1459
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1460
         */
1461
        public boolean isTransparent() {
1462
                return getRender().getRenderingTransparency().isTransparencyActive();
1463
        }
1464

    
1465
        /**
1466
         * Asigna la transparencia de la siguiente renderizaci?n
1467
         * @param valor de transparencia
1468
         */
1469
        public void setTransparency(int trans) {
1470
                super.setTransparency(trans);
1471
                try {
1472
                        getRender().getRenderingTransparency().setOpacity(trans);
1473
                } catch (NullPointerException e) {
1474
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1475
                }
1476
        }
1477

    
1478
        public List<ROI> getRois() throws ROIException {
1479
                return getDataStore().getRois(getMapContext().getProjection());
1480
        }
1481

    
1482
        public void setRois(List<ROI> rois) {
1483
                getDataStore().setRois(rois);
1484
        }
1485
        
1486
        public void setROIsFiles(List<File> file) throws RmfSerializerException {
1487
                getDataStore().saveROIFileListToRmf(file);
1488
        }
1489
        
1490
        public List<File> getROIsFiles() throws RmfSerializerException {
1491
                return getDataStore().getROIFileListFromRmf();
1492
        }
1493

    
1494
        /**
1495
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1496
         * devolver? null.
1497
         * @return TreeMap con la lista de capas a dibujar
1498
         */
1499
        public HashMap<DefaultFLyrRaster, Boolean> getRasterStrategy() {
1500
                if(strategy != null)
1501
                        return strategy.getStrategy();
1502
                return null;
1503
        }
1504

    
1505
        /**
1506
         * @return the configuration
1507
         */
1508
        static public IConfiguration getConfiguration() {
1509
                return configuration;
1510
        }
1511

    
1512
        /**
1513
         * @param configuration the configuration to set
1514
         */
1515
        static public void setConfiguration(IConfiguration configuration) {
1516
                DefaultFLyrRaster.configuration = configuration;
1517
        }
1518

    
1519
        public void reload() throws ReloadLayerException {
1520
                try {
1521
                        super.reload();
1522
                        load();
1523
                        if (isStopped())
1524
                                disableStopped();
1525
                        if (getMapContext() != null)
1526
                                getMapContext().invalidate();
1527
                } catch (LoadLayerException e) {
1528
                        setAvailable(false);
1529
                        throw new ReloadLayerException(getName(), e);
1530
                }
1531
        }
1532

    
1533
        /**
1534
         * Devuelve si la capa tiene soporte para poder generar overviews
1535
         * @return
1536
         */
1537
        public boolean overviewsSupport() {
1538
                if ((getDataStore() != null) && (getDataStore().overviewsSupport()))
1539
                        return true;
1540

    
1541
                return false;
1542
        }
1543

    
1544
        /**
1545
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1546
         * en escala de grises
1547
         * @return
1548
         */
1549
        public boolean isRenderingAsGray() {
1550
                int[] renderBands = getRender().getRenderColorInterpretation().buildRenderBands();
1551
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1552
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1553
                        return true;
1554
                return false;
1555
        }
1556

    
1557
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1558
                updateDrawVersion();
1559
        }
1560

    
1561
        public Point2D adjustWorldRequest(Point2D req) {
1562
                Envelope ext = null;
1563

    
1564
                ext = getFullEnvelope();
1565
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
1566
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
1567
                return req;
1568
        }
1569

    
1570
        public FLayer cloneLayer() throws Exception {
1571
                RasterDataStore  ds = getDataStore().cloneDataStore();
1572
                DefaultFLyrRaster newLayer = new DefaultFLyrRaster();
1573
                newLayer.setName(getName());
1574
                newLayer.setOpenRasterStore(ds);
1575
                newLayer.firstLoad = firstLoad;
1576
                
1577
                List<RasterFilter> filters = getRender().getFilterList().getStatusCloned();
1578

    
1579
                //Hacemos una copia de las bandas a renderizar
1580
                if(getRender().getRenderColorInterpretation() != null) {
1581
                        newLayer.getRender().setRenderColorInterpretation(getRender().getRenderColorInterpretation().cloneColorInterpretation());
1582
                }
1583

    
1584
                //Asignamos el entorno
1585
                if(newLayer.getRender().getFilterList() == null)
1586
                        newLayer.getRender().setFilterList(RasterLocator.getManager().createEmptyFilterList(getRender().getFilterList().getInitDataType()));
1587
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
1588
                newLayer.getRender().getFilterList().setStatus(filters);
1589

    
1590
                // Asignamos los valores noData del original
1591
                newLayer.setNoDataValue(getNoDataValue());
1592
                if(getDataStore().getNoDataValue().isDefined())
1593
                        newLayer.setNoDataTransparent(true);
1594
                newLayer.enableOpen();
1595
                
1596
                return newLayer;
1597
        }
1598
        
1599
        public FLayer getFileLayer() throws RasterDriverException {
1600
                try {
1601
                        return cloneLayer();
1602
                } catch (Exception e) {
1603
                }
1604
                return null;
1605
        }
1606
        
1607
        public void addFile(String file) throws InvalidSourceException {
1608
                getDataStore().addFile(file);
1609
        }
1610
        
1611
        public void removeFile(String file) {
1612
                getDataStore().removeFile(file);
1613
        }
1614

    
1615
        /*****************************************************/
1616

    
1617
        public void disableStopped() {
1618
                if(state != null)
1619
                        state.disableStopped();
1620
        }
1621

    
1622
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1623

    
1624
        public void enableClosed() throws NotAvailableStateException {
1625
                if(state != null)
1626
                        state.enableClosed();
1627
        }
1628

    
1629
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1630

    
1631
        public void enableStopped() {state.enableStopped();}
1632

    
1633
        public boolean isAwake() {return state.isAwake();}
1634

    
1635
        public boolean isClosed() {return state.isClosed();}
1636

    
1637
        public boolean isOpen() {return state.isOpen();}
1638

    
1639
        public boolean isStopped() {return state.isStopped();}
1640

    
1641

    
1642
        @SuppressWarnings("rawtypes")
1643
        public Set getMetadataChildren() {
1644
                return null;
1645
        }
1646

    
1647
        public Object getMetadataID() {
1648
                return getName();
1649
        }
1650

    
1651
        public String getMetadataName() {
1652
                return null;
1653
        }
1654

    
1655
        public RasterDataStore getDataStore() {
1656
                if(dataStore != null) {
1657
                        RasterDataParameters params = (RasterDataParameters)dataStore.getParameters();
1658
                        if (getCoordTrans() != null && params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
1659
                                this.dataStore.setCoordTrans(getCoordTrans());
1660
                        }
1661
                }
1662
                return this.dataStore;
1663
        }
1664
        
1665
        public IProjection getProjection() {
1666
                RasterDataParameters p = (RasterDataParameters)getDataStore().getParameters();
1667
                if(p.getReprojectionOption() == RasterDataParameters.DONT_CHANGE_PROJECTION)
1668
                        return null;
1669
                return getDataStore().getProjection();
1670
        }
1671

    
1672
        public void setOpenRasterStore(DataStore dataStore) throws LoadLayerException {
1673
                if(dataStore instanceof CoverageStoreProviderServices) {
1674
                        try {
1675
                                this.dataStore = rManager.getProviderServices().open(
1676
                                                ((CoverageStoreProviderServices) dataStore).getProvider(), 
1677
                                                dataStore.getParameters());
1678
                        } catch (NotSupportedExtensionException e) {
1679
                                throw new LoadLayerException("Extension not supported", e);
1680
                        } catch (RasterDriverException e) {
1681
                                throw new LoadLayerException("Error opening the DataStore", e);
1682
                        }
1683
                } else
1684
                        this.dataStore = (RasterDataStore) dataStore;
1685
                try {
1686
                        enableAwake();
1687
                } catch (NotAvailableStateException e) {
1688
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
1689
                }
1690
                if(getDataStore().getProjection() != null) {
1691
                        try {
1692
                                getDataStore().setProjection(getDataStore().getProjection(), false);
1693
                                super.setProjection(getDataStore().getProjection());
1694
                        } catch (RmfSerializerException e) {
1695
                                //persist is false
1696
                        }
1697
                }
1698
        }
1699
        
1700
        public void setDataStore(DataStore dataStore) throws LoadLayerException {
1701
                setOpenRasterStore(dataStore);
1702
                load();
1703
        }
1704
        
1705
        public boolean isRemote() {
1706
                return false;
1707
        }
1708
        
1709
        /**
1710
         * Returns true if exists a process reading data from this layer
1711
         * @return
1712
         */
1713
        public boolean isReadingData() {
1714
                return readingData != null;
1715
        }
1716

    
1717
        /**
1718
         * When a process is using information of this layer this variable will contain
1719
         * the thread ID.
1720
         * @param readingData
1721
         */
1722
        public synchronized void setReadingData(String readingData) {
1723
                this.readingData = readingData;
1724
        }
1725
        
1726
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel,
1727
                        boolean fast)
1728
                        throws LoadLayerException, DataException {
1729
                return null;
1730
        }
1731

    
1732
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel)
1733
                        throws LoadLayerException, DataException {
1734
                return null;
1735
        }
1736

    
1737
        @Override
1738
        protected void doDispose() throws BaseException {
1739
                if(render != null)
1740
                        render.dispose();
1741
                if(getDataStore() != null)
1742
                        getDataStore().dispose();
1743
                finalize();
1744
        }
1745

    
1746
        public int getZoomLevel() {
1747
                return zoomLevel;
1748
        }
1749

    
1750
        public void setZoomLevel(int zoomLevel) {
1751
                this.zoomLevel = zoomLevel;
1752
        }
1753
        
1754
        public boolean increaseZoomLevel() {
1755
                if(zoomLevel < (this.getDataStore().getZoomLevels() - 1)) { 
1756
                        zoomLevel ++;
1757
                        recalcLevel = false;
1758
                        return true;
1759
                }
1760
                return false;
1761
        }
1762
        
1763
        public boolean decreaseZoomLevel() {
1764
                if(zoomLevel > 0) { 
1765
                        zoomLevel --;
1766
                        recalcLevel = false;
1767
                        return true;
1768
                }
1769
                return false;
1770
        }
1771
        
1772
        public Envelope getCoordsInLevel(Point2D center, int level, int w, int h) throws CreateEnvelopeException {
1773
                Extent ex = getDataStore().getCoordsInLevel(center, level, w, h);
1774
                return geomManager.createEnvelope(ex.getULX(), ex.getULY(), ex.getLRX(), ex.getLRY(), SUBTYPES.GEOM2D);
1775
        }
1776
        
1777
        public boolean isEnabledMultiresolution() {
1778
                return getDataStore().isTiled();
1779
        }
1780
        
1781
        public void setTileServer(Class<?> tileServer) throws InitializeException {
1782
                getDataStore().setTileServer(tileServer);
1783
        }
1784
        
1785
        @Override
1786
        public void loadFromState(PersistentState state)
1787
                        throws PersistenceException {
1788
                try {
1789
                        super.loadFromState(state);
1790
                        this.dataStore = (RasterDataStore)state.get("rasterdatastore");
1791
                } catch (PersistenceRuntimeException e) {
1792
                        logger.debug("Unable to load store from persistence in layer: " + this.getName(), e);
1793
                        this.setAvailable(false);
1794
                        return;
1795
                }
1796
                this.lastLegend = (ILegend)state.get("legend");
1797
                this.colorTableLoadedFromProject = (ColorTable)state.get("colortable");
1798
                this.zoomLevel = state.getInt("zoomLevel");
1799
                this.recalcLevel = state.getBoolean("recalcLevel");
1800
                loadedFromProject = true;
1801
        }
1802

    
1803
        @Override
1804
        public void saveToState(PersistentState state) throws PersistenceException {
1805
                super.saveToState(state);
1806
                
1807
                state.set("rasterdatastore", getDataStore());        
1808
                state.set("legend", lastLegend);        
1809
                state.set("colortable", getRender().getColorTable());        
1810
                state.set("zoomLevel", zoomLevel);        
1811
                state.set("recalcLevel", recalcLevel);        
1812
        }        
1813
        
1814
        public static void registerPersistence() {
1815
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
1816
                DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
1817
                if( definition == null ) {
1818
                        if (manager.getDefinition(FLyrDefault.class) == null) {
1819
                                FLyrDefault.registerPersistent();
1820
                        }
1821
                        definition = manager.addDefinition(
1822
                                        DefaultFLyrRaster.class,
1823
                                        PERSISTENT_NAME,
1824
                                        PERSISTENT_DESCRIPTION,
1825
                                        null, 
1826
                                        null
1827
                        );
1828
                        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE, "FLyrDefault");
1829
                        
1830
                        registerPersistence(definition);
1831
                }
1832
        }
1833
        
1834
        public static void registerPersistence(DynStruct definition) {
1835
                definition.addDynFieldObject("rasterdatastore").setClassOfValue(RasterDataStore.class).setMandatory(false);
1836
                definition.addDynFieldObject("legend").setClassOfValue(ILegend.class).setMandatory(false);
1837
                definition.addDynFieldObject("colortable").setClassOfValue(ColorTable.class).setMandatory(false);
1838
                definition.addDynFieldInt("zoomlevel").setMandatory(false);
1839
                definition.addDynFieldBoolean("recalcLevel").setMandatory(false);
1840
        }
1841

    
1842
        public GeometryType getGeometryType() throws ReadException {
1843
                try {
1844
                        return GeometryLocator.getGeometryManager().getGeometryType(TYPES.SURFACE, SUBTYPES.GEOM2D);
1845
                } catch (GeometryTypeNotSupportedException e) {
1846
                        throw new ReadException(getDataStore().getName(), e);
1847
                } catch (GeometryTypeNotValidException e) {
1848
                        throw new ReadException(getDataStore().getName(), e);
1849
                } 
1850
        }
1851
        
1852
        public void setDataStore(DataStore dataStore, String domain) throws LoadLayerException {
1853
                setDataStore(dataStore);
1854
        }
1855
        
1856
        protected void finalize() {
1857
                layerChangeSupport             = null;
1858
                state                          = null;
1859
                lastLegend                     = null;
1860
                colorTableLoadedFromProject    = null;
1861
                strategy                       = null;
1862
                configuration                  = null;
1863
                fileUtil                       = null;
1864
                rasterUtil                     = null;
1865
                crsUtil                        = null;
1866
                mathUtil                       = null;
1867
                uri                            = null;
1868
                affineTransformList            = null;
1869
                readingData                    = null;
1870
                dataStore                      = null;
1871
                render                         = null;
1872
        }
1873

    
1874
}