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

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.setTime(vp.getTime()); 
617
                
618
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
619
                SimpleTaskStatus taskStatus = new RasterTaskStatus("Drawing " + getName() + "...", cancel);
620
                manager.add(taskStatus);
621
                taskStatus.setAutoremove(true);
622
                
623
                //Crea la reproyecci?n al vuelo la primera vez
624
                RasterDataParameters params = (RasterDataParameters)getDataStore().getParameters();
625
                if(!getRender().isReprojectingOnTheFly() && 
626
                        getDataStore().getProjection() != null &&
627
                        params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
628
                        getRender().createReprojectionOnTheFly(getDataStore(), getCoordTrans(), taskStatus);
629
                }
630
                
631
                try {
632
                        if(getDataStore().isTiled()) {
633
                                getRender().drawTiledService(g, vp2, vp.getImageSize(), taskStatus);
634
                        } else {
635
                                getRender().draw(g, vp2, taskStatus);
636
                        }
637
                } catch (ProcessInterruptedException e1) {
638
                } finally {
639
                        taskStatus.terminate();
640
                }
641
        }
642

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1247
                return false;
1248
        }
1249

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

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

    
1262

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

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

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

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

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

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

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

    
1328
                return null;
1329
        }
1330

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1440
                super.setVisible(visibility);
1441
        }
1442

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

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

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

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

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

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

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

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

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

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

    
1540
                return false;
1541
        }
1542

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

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

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

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

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

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

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

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

    
1614
        /*****************************************************/
1615

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

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

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

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

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

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

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

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

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

    
1640

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

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

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

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

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

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

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

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

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

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

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

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

    
1873
}