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

History | View | Annotate | Download (60.8 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.net.URI;
36
import java.util.ArrayList;
37
import java.util.HashMap;
38
import java.util.List;
39
import java.util.Set;
40

    
41
import org.cresques.cts.IProjection;
42

    
43
import org.gvsig.compat.print.PrintAttributes;
44
import org.gvsig.fmap.crs.CRSFactory;
45
import org.gvsig.fmap.dal.DataStore;
46
import org.gvsig.fmap.dal.DataStoreParameters;
47
import org.gvsig.fmap.dal.coverage.RasterLibrary;
48
import org.gvsig.fmap.dal.coverage.RasterLocator;
49
import org.gvsig.fmap.dal.coverage.RasterManager;
50
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
51
import org.gvsig.fmap.dal.coverage.datastruct.ColorItem;
52
import org.gvsig.fmap.dal.coverage.datastruct.ColorTableLibrary;
53
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
54
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
55
import org.gvsig.fmap.dal.coverage.datastruct.Params;
56
import org.gvsig.fmap.dal.coverage.datastruct.ViewPortData;
57
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
58
import org.gvsig.fmap.dal.coverage.exception.FilePaletteException;
59
import org.gvsig.fmap.dal.coverage.exception.FilterManagerException;
60
import org.gvsig.fmap.dal.coverage.exception.FilterTypeException;
61
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
62
import org.gvsig.fmap.dal.coverage.exception.InvalidSourceException;
63
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
64
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
65
import org.gvsig.fmap.dal.coverage.exception.QueryException;
66
import org.gvsig.fmap.dal.coverage.exception.ROIException;
67
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
68
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
69
import org.gvsig.fmap.dal.coverage.grid.RasterFilter;
70
import org.gvsig.fmap.dal.coverage.grid.RasterFilterList;
71
import org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager;
72
import org.gvsig.fmap.dal.coverage.grid.render.Render;
73
import org.gvsig.fmap.dal.coverage.grid.render.VisualPropertyEvent;
74
import org.gvsig.fmap.dal.coverage.grid.render.VisualPropertyListener;
75
import org.gvsig.fmap.dal.coverage.process.TaskEventManager;
76
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
77
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
78
import org.gvsig.fmap.dal.coverage.store.parameter.RasterFileStoreParameters;
79
import org.gvsig.fmap.dal.coverage.store.parameter.TileDataParameters;
80
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
81
import org.gvsig.fmap.dal.coverage.store.props.ColorTable;
82
import org.gvsig.fmap.dal.coverage.store.props.Statistics;
83
import org.gvsig.fmap.dal.coverage.util.CRSUtils;
84
import org.gvsig.fmap.dal.coverage.util.ColorConversion;
85
import org.gvsig.fmap.dal.coverage.util.FileUtils;
86
import org.gvsig.fmap.dal.coverage.util.Historical;
87
import org.gvsig.fmap.dal.coverage.util.MathUtils;
88
import org.gvsig.fmap.dal.coverage.util.ProviderServices;
89
import org.gvsig.fmap.dal.coverage.util.RasterUtils;
90
import org.gvsig.fmap.dal.exception.CloseException;
91
import org.gvsig.fmap.dal.exception.DataException;
92
import org.gvsig.fmap.dal.exception.InitializeException;
93
import org.gvsig.fmap.dal.exception.ReadException;
94
import org.gvsig.fmap.dal.raster.spi.CoverageStoreProviderServices;
95
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
96
import org.gvsig.fmap.geom.Geometry.TYPES;
97
import org.gvsig.fmap.geom.GeometryLocator;
98
import org.gvsig.fmap.geom.GeometryManager;
99
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
100
import org.gvsig.fmap.geom.primitive.Envelope;
101
import org.gvsig.fmap.geom.type.GeometryType;
102
import org.gvsig.fmap.geom.type.GeometryTypeNotSupportedException;
103
import org.gvsig.fmap.geom.type.GeometryTypeNotValidException;
104
import org.gvsig.fmap.mapcontext.MapContextLocator;
105
import org.gvsig.fmap.mapcontext.MapContextManager;
106
import org.gvsig.fmap.mapcontext.ViewPort;
107
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
108
import org.gvsig.fmap.mapcontext.exceptions.ReloadLayerException;
109
import org.gvsig.fmap.mapcontext.layers.FLayer;
110
import org.gvsig.fmap.mapcontext.layers.FLyrDefault;
111
import org.gvsig.fmap.mapcontext.layers.LayerChangeSupport;
112
import org.gvsig.fmap.mapcontext.layers.LayerListener;
113
import org.gvsig.fmap.mapcontext.layers.Tiling;
114
import org.gvsig.fmap.mapcontext.layers.operations.Classifiable;
115
import org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint;
116
import org.gvsig.fmap.mapcontext.layers.operations.SingleLayer;
117
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
118
import org.gvsig.fmap.mapcontext.rendering.legend.events.listeners.LegendListener;
119
import org.gvsig.raster.fmap.legend.ColorTableLegend;
120
import org.gvsig.raster.roi.ROI;
121
import org.gvsig.raster.util.RasterNotLoadException;
122
import org.gvsig.tools.ToolsLocator;
123
import org.gvsig.tools.dynobject.DynClass;
124
import org.gvsig.tools.dynobject.DynObjectManager;
125
import org.gvsig.tools.dynobject.DynObjectSet;
126
import org.gvsig.tools.dynobject.DynStruct;
127
import org.gvsig.tools.exception.BaseException;
128
import org.gvsig.tools.persistence.PersistenceManager;
129
import org.gvsig.tools.persistence.PersistentState;
130
import org.gvsig.tools.persistence.exception.PersistenceException;
131
import org.gvsig.tools.persistence.exception.PersistenceRuntimeException;
132
import org.gvsig.tools.task.Cancellable;
133
import org.gvsig.tools.task.SimpleTaskStatus;
134
import org.gvsig.tools.task.TaskStatusManager;
135
import org.gvsig.tools.task.impl.BaseTaskStatus;
136

    
137
import org.slf4j.Logger;
138
import org.slf4j.LoggerFactory;
139

    
140
/**
141
 * Raster layer
142
 *
143
 * @author Nacho Brodin (nachobrodin@gmail.com)
144
 */
145
@SuppressWarnings("deprecation")
146
public class DefaultFLyrRaster extends FLyrDefault implements FLyrRaster, Multiresolution, InfoByPoint, Classifiable,
147
                IRasterLayerActions, ILayerState, VisualPropertyListener, SingleLayer {
148

    
149
        public static final String      PERSISTENT_NAME                = "FLyrRasterSE_Persistent";
150
    public static final String      PERSISTENT_DESCRIPTION         = "FLyrRasterSE Persistent";
151
    private RasterManager           rManager                       = RasterLocator.getManager();
152
        private boolean                 mustTileDraw                   = false;
153
        private boolean                 mustTilePrint                  = true;
154
        private int                     maxTileDrawWidth               = 200;
155
        private int                     maxTileDrawHeight              = 200;
156
        private int                     maxTilePrintWidth              = 1500;
157
        private int                     maxTilePrintHeight             = 1500;
158
        private boolean                 firstLoad                      = false;
159
        private boolean                 removeRasterFlag               = true;
160
        protected RasterDataStore       dataStore                      = null;
161
        protected Render                render                         = null;
162
        private int                     posX                           = 0;
163
        private int                     posY                           = 0;
164
        private double                  posXWC                         = 0;
165
        private int                     posYWC                         = 0;
166
        private int                     r                              = 0;
167
        private int                     g                              = 0;
168
        private int                     b                              = 0;
169
        private LayerChangeSupport      layerChangeSupport             = new LayerChangeSupport();
170
        private FLyrState               state                          = new FLyrState();
171
        protected ILegend               lastLegend                     = null;
172
        protected ColorTable            colorTableLoadedFromProject    = null;
173
        protected boolean               loadedFromProject              = false;
174
        private RasterDrawStrategy      strategy                       = null;
175
        static private IConfiguration   configuration                  = new DefaultLayerConfiguration();
176
        protected int                   zoomLevel                      =  1;
177
        public boolean                  recalcLevel                    = true;
178
        private URI                  uri                            = null;
179

    
180
        private static GeometryManager  geomManager                          = GeometryLocator.getGeometryManager();
181
        private static final Logger     logger                         = LoggerFactory.getLogger(DefaultFLyrRaster.class);
182
        protected FileUtils             fileUtil                       = RasterLocator.getManager().getFileUtils();
183
        protected RasterUtils           rasterUtil                     = RasterLocator.getManager().getRasterUtils();
184
        protected CRSUtils              crsUtil                        = RasterLocator.getManager().getCRSUtils();
185
        protected MathUtils             mathUtil                       = RasterLocator.getManager().getMathUtils();
186

    
187
        public class RasterTaskStatus extends BaseTaskStatus {
188
                Cancellable c = null;
189

    
190
                public RasterTaskStatus(String tittle, Cancellable c) {
191
                        super(tittle);
192
                        this.c = c;
193
                }
194

    
195
                public boolean isCancellationRequested() {
196
                        if(c != null)
197
                                return this.c.isCanceled();
198
                        return false;
199
                }
200

    
201
                public void cancelRequest() {
202
                        if(c != null)
203
                                this.c.setCanceled(true);
204
                }
205
        }
206

    
207
        /**
208
         * Lista de transformaciones afines que son aplicadas. Esta lista es
209
         * simplemente un historico que no se utiliza. Es posible utilizarlo para
210
         * recuperar transformaciones anteriores.
211
         */
212
        private Historical              affineTransformList    = null;
213
        protected String                readingData            = null;
214
        //It is set to true if the method init has been called at least once
215
        private boolean                 layerInitialize        = false;
216

    
217
        public DefaultFLyrRaster() {
218
                affineTransformList = rManager.createHistoricalService();
219
        }
220

    
221
        public static void registerDynClass() {
222
                DynObjectManager manager = ToolsLocator.getDynObjectManager();
223
            DynClass dynClass = manager.add("RasterInfo", "Raster layer Info by point");
224
            dynClass.setNamespace("InfoByPoint");
225
            dynClass.addDynFieldString("File");
226
            dynClass.addDynFieldString("View Point");
227
            dynClass.addDynFieldString("Pixel Point");
228
            dynClass.addDynFieldString("RGB");
229
            dynClass.addDynFieldString("CMYK");
230
            dynClass.addDynFieldString("HSL");
231
            dynClass.addDynFieldString("Band Value");
232
            dynClass.addDynFieldString("World Point");
233
        }
234

    
235
        /**
236
         * Builds a new raster layer
237
         * @param fileName
238
         * @return
239
         * @throws RasterNotLoadException
240
         * @throws LoadLayerException
241
         */
242
        public static DefaultFLyrRaster createLayer(String layerName, File file) throws LoadLayerException {
243
                ProviderServices provServ = RasterLocator.getManager().getProviderServices();
244
                RasterDataParameters storeParameters = provServ.createParameters(file.getName());
245
                storeParameters.setURI(file.toURI());
246

    
247
                MapContextManager mcm = MapContextLocator.getMapContextManager();
248
                DefaultFLyrRaster lyr = (DefaultFLyrRaster) mcm.createLayer(layerName, storeParameters);
249

    
250
                return lyr;
251
        }
252

    
253
        public void setName(String name) {
254
                super.setName(name);
255

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

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

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

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

    
280
                boolean test = false;
281
                DataStoreParameters params = getDataStore().getParameters();
282
                DataStoreParameters p = params;
283
                if (params != null) {
284
                        if(params instanceof TileDataParameters) {
285
                                uri = ((RasterDataParameters)params).getURI();
286
                                if(uri == null)
287
                                        p = (DataStoreParameters)((TileDataParameters)params).getDataParameters();
288
                        }
289
                        if(uri == null) {
290
                                if(params instanceof RasterDataParameters)
291
                                        uri = ((RasterDataParameters)p).getURI();
292
                        }
293
                }
294

    
295
                try {
296
                        if(!getDataStore().isOpen())
297
                                dataStore = rManager.getProviderServices().open(params);
298
                        else
299
                                dataStore.reload();
300
                } catch (NotSupportedExtensionException e) {
301
                        throw new LoadLayerException(this.getName());
302
                } catch (RasterDriverException e) {
303
                        throw new LoadLayerException(this.getName());
304
                }
305
        }
306

    
307
        public void setLayerInitialized(boolean initialized) {
308
                layerInitialize = initialized;
309
        }
310

    
311
        /**
312
         * Acciones de inicializaci?n despu?s de que la fuente de datos
313
         * de la capa est? asignada.
314
         * @throws FilePaletteException
315
         */
316
        public void init() throws LoadLayerException, FilePaletteException {
317
                layerInitialize = true;
318

    
319
                if (getDataStore() == null)
320
                        throw new LoadLayerException("Formato no valido", new IOException());
321

    
322
                render = getDataStore().getRender();
323
                render.addVisualPropertyListener(this);
324
                initFilters();
325

    
326
                //Inicializaci?n del historico de transformaciones
327
                affineTransformList.clear();
328
                affineTransformList.add(this.getAffineTransform());
329

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

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

    
352
        /**
353
         * Crea el objeto renderizador de raster
354
         * @return Rendering
355
         */
356
        public Render getRender() {
357
                if (render == null) {
358
                        if(getDataStore() != null) {
359
                                render = getDataStore().getRender();
360
                                render.addVisualPropertyListener(this);
361
                        }
362
                }
363
                return render;
364
        }
365

    
366
        public URI getURI() {
367
                return uri;
368
        }
369

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

    
378
        /**
379
         * Initializes the filter list to render this raster layer
380
         * @throws FilePaletteException
381
         */
382
        protected void initFilters() throws FilePaletteException {
383
                if(getDataType() == null)
384
                        return;
385

    
386
                RasterFilterList filterList = rManager.createEmptyFilterList(getDataType()[0]);
387
                if(loadedFromProject) {
388
                        filterList = getDataStore().getRender().getFilterList();
389
                }
390

    
391
                if(getDataStore() == null)
392
                        return;
393

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

    
398
                filterList.setInitDataType(getDataType()[0]);
399

    
400
                // Quitamos la leyenda
401
                lastLegend = null;
402

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

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

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

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

    
458
                Statistics stats = getDataStore().getStatistics();
459
                ColorTableLibrary colorTableLibrary = rManager.getDataStructFactory().getColorTableLibrary();
460

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

    
473
                                                        ColorTable colorTable = colorTableLibrary.createColorTable();
474
                                                        colorTable.setName(paletteName);
475
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
476
                                                        colorTable.setInterpolated(true);
477

    
478
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
479

    
480
                                                        setLastLegend(colorTable);
481

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

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

    
511
        public boolean isReproyectable() {
512
                if (getDataStore() == null)
513
                        return false;
514
                return getDataStore().isReproyectable();
515
        }
516

    
517
        /**
518
         * @throws ReadException
519
         * @throws ReadDriverException
520
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
521
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
522
         *                 com.iver.utiles.swing.threads.Cancellable)
523
         */
524
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadException {
525
                TaskEventManager task = rManager.getRasterTask();
526
                task.setEvent(null);
527

    
528
                if(!layerInitialize) {
529
                        if (getDataStore() != null)
530
                                try {
531
                                        this.init();
532
                                } catch (FilePaletteException e) {
533
                                        throw new ReadException("Error in raster legend", e);
534
                                } catch (LoadLayerException e) {
535
                                        throw new ReadException("Error initializing the layer", e);
536
                                }
537
                }
538

    
539
                try {
540
                        if (!isOpen())
541
                                return;
542

    
543
                        enableStopped();
544
                        // callLegendChanged(null);
545

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

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

    
564
                        if (isWithinScale(scale)) {
565

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

    
592
                        }
593

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

    
601
        protected void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws QueryException, InterruptedException {
602
                Envelope adjustedExtent = vp.getAdjustedExtent();
603
                if (adjustedExtent == null)
604
                        return;
605
                Extent e = rManager.getDataStructFactory().createExtent(adjustedExtent.getLowerCorner().getX(),
606
                                adjustedExtent.getUpperCorner().getY(), adjustedExtent
607
                                                .getUpperCorner().getX(),
608
                                adjustedExtent
609
                                                .getLowerCorner().getY());
610
                Dimension imgSz = vp.getImageSize();
611
                ViewPortData vp2 = rManager.getDataStructFactory().createViewPortData(vp.getProjection(), e, imgSz );
612
                vp2.setMat(vp.getAffineTransform());
613
                vp2.setDPI((int)vp.getDPI());
614
                //vp2.setTime(vp.getTime());
615

    
616
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
617
                SimpleTaskStatus taskStatus = new RasterTaskStatus("Drawing " + getName() + "...", cancel);
618
                manager.add(taskStatus);
619
                taskStatus.setAutoremove(true);
620

    
621
                //Crea la reproyecci?n al vuelo la primera vez
622
                RasterDataParameters params = (RasterDataParameters)getDataStore().getParameters();
623
                if(!getRender().isReprojectingOnTheFly() &&
624
                        getDataStore().getProjection() != null &&
625
                        params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
626
                        getRender().createReprojectionOnTheFly(getDataStore(), getCoordTrans(), taskStatus);
627
                }
628

    
629
                try {
630
                        if(getDataStore().isTiled()) {
631
                                getRender().drawTiledService(g, vp2, vp.getImageSize(), taskStatus);
632
                        } else {
633
                                getRender().draw(g, vp2, taskStatus);
634
                        }
635
                } catch (ProcessInterruptedException e1) {
636
                } finally {
637
                        taskStatus.terminate();
638
                }
639
        }
640

    
641
        /**
642
         * Inserta la proyecci?n.
643
         *
644
         * @param proj Proyecci?n.
645
         */
646
        public void setProjection(IProjection proj) {
647
                try {
648
                        getDataStore().setProjection(proj, true);
649
                        super.setProjection(proj);
650
                } catch (RmfSerializerException e) {
651
                        logger.error("Error saving the projection", e);
652
                }
653
        }
654

    
655
        public void setProjection(IProjection proj, boolean persist) {
656
                try {
657
                        getDataStore().setProjection(proj, persist);
658
                        super.setProjection(proj);
659
                } catch (RmfSerializerException e) {
660
                        logger.error("Error saving the projection", e);
661
                }
662
        }
663

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

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

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

    
684
                } catch (CreateEnvelopeException e1) {
685
                        logger.error("Error creating the envelope", e);
686
                        return null;
687
                }
688
        }
689

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

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

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

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

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

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

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

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

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

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

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

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

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

    
798
                if (/*!isOpen() ||*/ !isVisible() || !isWithinScale(scale))
799
                        return;
800

    
801
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
802
                SimpleTaskStatus taskStatus = new RasterTaskStatus("Printing raster " + getName() + "...", cancel);
803
                manager.add(taskStatus);
804
                taskStatus.setAutoremove(true);
805

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

    
826
                taskStatus.terminate();
827
        }
828

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

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

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

846
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
847

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

853
                double[] srcPts = new double[8];
854
                double[] dstPts = new double[8];
855

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

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

870
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
871

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

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

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

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

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

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

    
939
        if (this.isRemoveRasterFlag()) {
940
            if (getDataStore() != null) {
941
                URI[] uris = getUris().clone();
942

    
943
                try {
944
                    getDataStore().close();
945
                } catch (CloseException e) {
946
                }
947

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

    
955
                for (int i = 0; i < uris.length; i++) {
956
                    if ("FILE".equalsIgnoreCase(uris[i].getScheme())) {
957
                        File file = new File(uris[i]);
958
                        File dirTemp = fileUtil.getTemporalFile();
959
                        if (!file.exists())
960
                            continue;
961
                        if (dirTemp.compareTo(file.getParentFile()) == 0) {
962
                            file.delete();
963

    
964
                            // Borramos todos los ficheros que puedan tener
965
                            // 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
        }
980
        updateDrawVersion();
981
        return super.layerListeners.remove(o);
982
    }
983

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

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

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

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

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

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

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

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

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

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

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

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

    
1046
           /**
1047
     * Gets the list of URIs
1048
     */
1049
    public URI[] getUris() {
1050
        if (getDataStore() == null)
1051
            return null;
1052

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

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

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

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

    
1086
        /**
1087
         * Sets the filter list
1088
         */
1089
        public void setRenderFilterList(RasterFilterList filterList) {
1090
                getRender().setFilterList(filterList);
1091
        }
1092

    
1093
        public DynObjectSet getInfo(org.gvsig.fmap.geom.primitive.Point p, double tolerance) throws LoadLayerException, DataException {
1094
                DynObjectSetRasterInfo info = new DynObjectSetRasterInfo();
1095

    
1096
                if (!isOpen()) {
1097
                        info.addField("Layer not open", normalizeAsXMLTag(getName()), 0);
1098
                        return info;
1099
                }
1100

    
1101
                Point2D pReal = new Point2D.Double(p.getX(), p.getY());
1102
                Point2D px = new Point2D.Double();
1103
                if(        pReal.getX() > this.getMinX() &&
1104
                        pReal.getX() < this.getMaxX() &&
1105
                        pReal.getY() > this.getMinY() &&
1106
                        pReal.getY() < this.getMaxY()) {
1107
                        px = transformPoint(pReal);
1108
                }
1109
                //int[] rgb = getPixel((int) p.getX(), (int) p.getY());
1110
                //ColorConversion conv = rManager.getColorConversion();
1111

    
1112
                info.addField("File", normalizeAsXMLTag(getName()), 0);
1113
                info.addField("View Point", "[" + p.getX() + " , " + p.getY() + "]", 1);
1114
                info.addField("World Point", "[" + mathUtil.format(pReal.getX(), 3) + " , " + mathUtil.format(pReal.getY(), 3) + "]", 2);
1115
                if (px == null)
1116
                        info.addField("Pixel Point", "Out", 3);
1117
                else
1118
                        info.addField("Pixel Point", "[" + (int) px.getX() + ",  " + (int) px.getY() + "]", 3);
1119

    
1120
                //La informaci?n RGB no puede obtener de la capa
1121

    
1122
                /*info.addField("RGB", "[" + rgb[1] + ",  " + rgb[2] + ",  " + rgb[3] + "]", 4);
1123
                double[] cmyk = conv.RGBtoCMYK(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff, 1D);
1124
                info.addField("CMYK", "[" + mathUtil.format(cmyk[0], 4) + ",  " + mathUtil.format(cmyk[1], 4) + ",  " + mathUtil.format(cmyk[2], 4) + ",  " + mathUtil.format(cmyk[3], 4) + "]", 5);
1125
                double[] hsl = conv.RGBtoHSL(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff);
1126
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
1127
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
1128
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
1129
                info.addField("HSL", "[" + mathUtil.format(hsl[0], 4) + ",  " + mathUtil.format(hsl[1], 4) + ",  " + mathUtil.format(hsl[2], 4) + "]", 6);*/
1130

    
1131
                String data = "[";
1132
                try {
1133
                        if (px != null) {
1134
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3) {
1135
                                        for(int i = 0; i < getDataStore().getBandCount(); i++) {
1136
                                                if(getDataStore().isInside(pReal)) {
1137
                                                        Point2D pxAux = transformPoint(pReal);
1138
                                                        int val = ((Integer)getDataStore().getData((int)pxAux.getX(),
1139
                                                                        (int)pxAux.getY(), i)).intValue();
1140
                                                        if(getDataType()[0] == Buffer.TYPE_BYTE)
1141
                                                                data += (val & 0x000000ff) + ",  ";
1142
                                                        else
1143
                                                                data += val + ",  ";
1144
                                                }
1145
                                        }
1146
                                }
1147
                                if(getDataType()[0] == 4) {
1148
                                        for(int i = 0; i < getDataStore().getBandCount(); i++) {
1149
                                                if(getDataStore().isInside(pReal)) {
1150
                                                        Point2D pxAux = transformPoint(pReal);
1151
                                                        data += ((Float)getDataStore().getData((int)pxAux.getX(),
1152
                                                                        (int)pxAux.getY(), i)).floatValue() + ",  ";
1153
                                                }
1154
                                        }
1155
                                }
1156
                                if(getDataType()[0] == 5) {
1157
                                        for(int i = 0; i < getDataStore().getBandCount(); i++) {
1158
                                                if(getDataStore().isInside(pReal)) {
1159
                                                        Point2D pxAux = transformPoint(pReal);
1160
                                                        data += ((Double)getDataStore().getData((int)pxAux.getX(),
1161
                                                                        (int)pxAux.getY(), i)).doubleValue() + ",  ";
1162
                                                }
1163
                                        }
1164
                                }
1165
                        }
1166
                        data +=  "]";
1167
                        info.addField("Band Value", data, 7);
1168
                } catch (RasterDriverException ex) {
1169
                        throw new LoadLayerException("Error en el acceso al dataset", ex);
1170
                } catch (InvalidSetViewException ex) {
1171
                        throw new LoadLayerException("Error en la asignaci?n de la vista en getData", ex);
1172
                } catch (FileNotOpenException ex) {
1173
                        throw new LoadLayerException("Fichero no abierto en el dataset", ex);
1174
                }
1175
                return info;
1176
        }
1177

    
1178
        /**
1179
         * Transforma un punto real a coordenadas pixel
1180
         *
1181
         * @param numberBand
1182
         * @param pReal
1183
         * @return
1184
         * @throws LoadLayerException
1185
         * @throws ReadDriverException
1186
         */
1187
        private Point2D transformPoint(Point2D pReal) throws LoadLayerException {
1188
                AffineTransform at = getDataStore().getAffineTransform();
1189
                Point2D px = new Point2D.Double();
1190
                //px = new Point2D.Double(pReal.getX(), pReal.getY());
1191
                try {
1192
                        at.inverseTransform(pReal, px);
1193
                        return px;
1194
                } catch (NoninvertibleTransformException e) {
1195
                        throw new LoadLayerException("Error en la transformaci?n del punto", e);
1196
                }
1197
        }
1198

    
1199
        public Object getInfo(String key) {
1200
                if (key.equals("DriverName"))
1201
                        return "gvSIG Raster Driver";
1202
                return null;
1203
        }
1204

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

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

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

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

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

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

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

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

    
1248
                return false;
1249
        }
1250

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

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

    
1263

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

    
1274
        /**
1275
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1276
         * @param file Fichero a consultar
1277
         * @return true si es aceptado y false si no lo es.
1278
         */
1279
        public boolean isFileAccepted(File file) {
1280
                return getDataStore().isFileSupported(file.getName());
1281
        }
1282

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

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

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

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

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

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

    
1329
                return null;
1330
        }
1331

    
1332
        public void addLegendListener(LegendListener listener) {
1333
                if(layerChangeSupport != null){
1334
                        layerChangeSupport.addLayerListener(listener);
1335
                }
1336
        }
1337

    
1338
        public int getShapeType() {
1339
                return TYPES.SURFACE;
1340
        }
1341

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

    
1347
        public boolean isInside(Point2D p) {
1348
                 return getDataStore().isInside(p);
1349
        }
1350

    
1351
        public AffineTransform getAffineTransform() {
1352
                return getDataStore().getAffineTransform();
1353
        }
1354

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

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

    
1368
        public Historical getAffineTransformHistorical() {
1369
                return this.affineTransformList;
1370
        }
1371

    
1372
        public void saveGeoToRmf() throws RmfSerializerException {
1373
                if (!isOpen())
1374
                        return;
1375

    
1376
                getDataStore().saveGeoreferencingToRmf();
1377

    
1378
                affineTransformList.clear();
1379
                affineTransformList.add(this.getAffineTransform());
1380
        }
1381

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

    
1418
        public void setVisible(boolean visibility) {
1419
                        if((state != null) && visibility)
1420
                                state.disableStopped();
1421
                        else
1422
                                enableStopped();
1423

    
1424
                        if(isAwake() || isClosed())
1425
                                try {
1426
                                        this.load();
1427
                                } catch (LoadLayerException e) {
1428
                                        e.printStackTrace();
1429
                                }
1430

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

    
1446
                        super.setVisible(visibility);
1447
        }
1448

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

    
1461
        /**
1462
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1463
         * o no.
1464
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1465
         */
1466
        public boolean isTransparent() {
1467
                return getRender().getRenderingTransparency().isTransparencyActive();
1468
        }
1469

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

    
1483
        public List<ROI> getRois() throws ROIException {
1484
                return getDataStore().getRois(getMapContext().getProjection());
1485
        }
1486

    
1487
        public void setRois(List<ROI> rois) {
1488
                getDataStore().setRois(rois);
1489
        }
1490

    
1491
        public void setROIsFiles(List<File> file) throws RmfSerializerException {
1492
                getDataStore().saveROIFileListToRmf(file);
1493
        }
1494

    
1495
        public List<File> getROIsFiles() throws RmfSerializerException {
1496
                return getDataStore().getROIFileListFromRmf();
1497
        }
1498

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

    
1510
        /**
1511
         * @return the configuration
1512
         */
1513
        static public IConfiguration getConfiguration() {
1514
                return configuration;
1515
        }
1516

    
1517
        /**
1518
         * @param configuration the configuration to set
1519
         */
1520
        static public void setConfiguration(IConfiguration configuration) {
1521
                DefaultFLyrRaster.configuration = configuration;
1522
        }
1523

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

    
1538
        /**
1539
         * Devuelve si la capa tiene soporte para poder generar overviews
1540
         * @return
1541
         */
1542
        public boolean overviewsSupport() {
1543
                if ((getDataStore() != null) && (getDataStore().overviewsSupport()))
1544
                        return true;
1545

    
1546
                return false;
1547
        }
1548

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

    
1562
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1563
                updateDrawVersion();
1564
        }
1565

    
1566
        public Point2D adjustWorldRequest(Point2D req) {
1567
                Envelope ext = null;
1568

    
1569
                ext = getFullEnvelope();
1570
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
1571
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
1572
                return req;
1573
        }
1574

    
1575
        public FLayer cloneLayer() throws Exception {
1576
                RasterDataStore  ds = getDataStore().cloneDataStore();
1577
                DefaultFLyrRaster newLayer = new DefaultFLyrRaster();
1578
                newLayer.setName(getName());
1579
                newLayer.setOpenRasterStore(ds);
1580
                newLayer.firstLoad = firstLoad;
1581

    
1582
                List<RasterFilter> filters = getRender().getFilterList().getStatusCloned();
1583

    
1584
                //Hacemos una copia de las bandas a renderizar
1585
                if(getRender().getRenderColorInterpretation() != null) {
1586
                        newLayer.getRender().setRenderColorInterpretation(getRender().getRenderColorInterpretation().cloneColorInterpretation());
1587
                }
1588

    
1589
                //Asignamos el entorno
1590
                if(newLayer.getRender().getFilterList() == null)
1591
                        newLayer.getRender().setFilterList(RasterLocator.getManager().createEmptyFilterList(getRender().getFilterList().getInitDataType()));
1592
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
1593
                newLayer.getRender().getFilterList().setStatus(filters);
1594

    
1595
                // Asignamos los valores noData del original
1596
                newLayer.setNoDataValue(getNoDataValue());
1597
                if(getDataStore().getNoDataValue().isDefined())
1598
                        newLayer.setNoDataTransparent(true);
1599
                newLayer.enableOpen();
1600

    
1601
                return newLayer;
1602
        }
1603

    
1604
        public FLayer getFileLayer() throws RasterDriverException {
1605
                try {
1606
                        return cloneLayer();
1607
                } catch (Exception e) {
1608
                }
1609
                return null;
1610
        }
1611

    
1612
        public void addFile(File file) throws InvalidSourceException {
1613
                getDataStore().addFile(file);
1614
        }
1615

    
1616
        public void removeFile(File file) {
1617
                getDataStore().removeFile(file);
1618
        }
1619

    
1620
        /*****************************************************/
1621

    
1622
        public void disableStopped() {
1623
                if(state != null)
1624
                        state.disableStopped();
1625
        }
1626

    
1627
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1628

    
1629
        public void enableClosed() throws NotAvailableStateException {
1630
                if(state != null)
1631
                        state.enableClosed();
1632
        }
1633

    
1634
        public void enableOpen() throws NotAvailableStateException {
1635
                if(state != null){
1636
                        state.enableOpen();
1637
                }
1638
        }
1639

    
1640
        public void enableStopped() {
1641
                if(state != null) {
1642
                        state.enableStopped();
1643
                }
1644
        }
1645

    
1646
        public boolean isAwake() {
1647
                return (state != null) && state.isAwake();
1648
        }
1649

    
1650
        public boolean isClosed() {
1651
                return (state != null) && state.isClosed();
1652
        }
1653

    
1654
        public boolean isOpen() {
1655
                return (state != null) && state.isOpen();
1656
        }
1657

    
1658
        public boolean isStopped() {
1659
                return (state != null) && (state.isStopped());
1660
        }
1661

    
1662

    
1663
        @SuppressWarnings("rawtypes")
1664
        public Set getMetadataChildren() {
1665
                return null;
1666
        }
1667

    
1668
        public Object getMetadataID() {
1669
                return getName();
1670
        }
1671

    
1672
        public String getMetadataName() {
1673
                return null;
1674
        }
1675

    
1676
        public RasterDataStore getDataStore() {
1677
                if(dataStore != null) {
1678
                        RasterDataParameters params = (RasterDataParameters)dataStore.getParameters();
1679
                        if (getCoordTrans() != null && params.getReprojectionOption() == RasterDataParameters.ON_THE_FLY) {
1680
                                this.dataStore.setCoordTrans(getCoordTrans());
1681
                        }
1682
                }
1683
                return this.dataStore;
1684
        }
1685

    
1686
        public IProjection getProjection() {
1687
                if(getDataStore() == null)
1688
                        return null;
1689

    
1690
                RasterDataParameters p = (RasterDataParameters)getDataStore().getParameters();
1691
                if(p.getReprojectionOption() == RasterDataParameters.DONT_CHANGE_PROJECTION)
1692
                        return null;
1693
                return getDataStore().getProjection();
1694
        }
1695

    
1696
        public void setOpenRasterStore(DataStore dataStore) throws LoadLayerException {
1697
                if(dataStore instanceof CoverageStoreProviderServices) {
1698
                        try {
1699
                                this.dataStore = rManager.getProviderServices().open(
1700
                                                ((CoverageStoreProviderServices) dataStore).getProvider(),
1701
                                                dataStore.getParameters());
1702
                        } catch (NotSupportedExtensionException e) {
1703
                                throw new LoadLayerException("Extension not supported", e);
1704
                        } catch (RasterDriverException e) {
1705
                                throw new LoadLayerException("Error opening the DataStore", e);
1706
                        }
1707
                } else
1708
                        this.dataStore = (RasterDataStore) dataStore;
1709
                try {
1710
                        enableAwake();
1711
                } catch (NotAvailableStateException e) {
1712
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
1713
                }
1714
                if(getDataStore().getProjection() != null) {
1715
                        try {
1716
                                getDataStore().setProjection(getDataStore().getProjection(), false);
1717
                                super.setProjection(getDataStore().getProjection());
1718
                        } catch (RmfSerializerException e) {
1719
                                //persist is false
1720
                        }
1721
                }
1722
        }
1723

    
1724
        public void setDataStore(DataStore dataStore) throws LoadLayerException {
1725
                setOpenRasterStore(dataStore);
1726
                load();
1727
        }
1728

    
1729
        public boolean isRemote() {
1730
                return false;
1731
        }
1732

    
1733
        /**
1734
         * Returns true if exists a process reading data from this layer
1735
         * @return
1736
         */
1737
        public boolean isReadingData() {
1738
                return readingData != null;
1739
        }
1740

    
1741
        /**
1742
         * When a process is using information of this layer this variable will contain
1743
         * the thread ID.
1744
         * @param readingData
1745
         */
1746
        public synchronized void setReadingData(String readingData) {
1747
                this.readingData = readingData;
1748
        }
1749

    
1750
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel,
1751
                        boolean fast)
1752
                        throws LoadLayerException, DataException {
1753
                return null;
1754
        }
1755

    
1756
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel)
1757
                        throws LoadLayerException, DataException {
1758
                return null;
1759
        }
1760

    
1761
        @Override
1762
        protected void doDispose() throws BaseException {
1763
                if(render != null)
1764
                        render.dispose();
1765
                if(getDataStore() != null)
1766
                        getDataStore().dispose();
1767
                finalize();
1768
        }
1769

    
1770
        public int getZoomLevel() {
1771
                return zoomLevel;
1772
        }
1773

    
1774
        public void setZoomLevel(int zoomLevel) {
1775
                this.zoomLevel = zoomLevel;
1776
        }
1777

    
1778
        public boolean increaseZoomLevel() {
1779
                if(zoomLevel < (this.getDataStore().getZoomLevels() - 1)) {
1780
                        zoomLevel ++;
1781
                        recalcLevel = false;
1782
                        return true;
1783
                }
1784
                return false;
1785
        }
1786

    
1787
        public boolean decreaseZoomLevel() {
1788
                if(zoomLevel > 0) {
1789
                        zoomLevel --;
1790
                        recalcLevel = false;
1791
                        return true;
1792
                }
1793
                return false;
1794
        }
1795

    
1796
        public Envelope getCoordsInLevel(Point2D center, int level, int w, int h) throws CreateEnvelopeException {
1797
                Extent ex = getDataStore().getCoordsInLevel(center, level, w, h);
1798
                return geomManager.createEnvelope(ex.getULX(), ex.getULY(), ex.getLRX(), ex.getLRY(), SUBTYPES.GEOM2D);
1799
        }
1800

    
1801
        public boolean isEnabledMultiresolution() {
1802
                return getDataStore().isTiled();
1803
        }
1804

    
1805
        public void setTileServer(Class<?> tileServer) throws InitializeException {
1806
                getDataStore().setTileServer(tileServer);
1807
        }
1808

    
1809
        @Override
1810
        public void loadFromState(PersistentState state)
1811
                        throws PersistenceException {
1812
                try {
1813
                        super.loadFromState(state);
1814
                        this.dataStore = (RasterDataStore)state.get("rasterdatastore");
1815
                } catch (PersistenceRuntimeException e) {
1816
                        logger.debug("Unable to load store from persistence in layer: " + this.getName(), e);
1817
                        this.setAvailable(false);
1818
                        return;
1819
                }
1820
                this.lastLegend = (ILegend)state.get("legend");
1821
                this.colorTableLoadedFromProject = (ColorTable)state.get("colortable");
1822
                if(state.get("recalcLevel") != null){
1823
                        this.recalcLevel = state.getBoolean("recalcLevel");
1824
                }
1825
                if(state.get("zoomLevel") != null){
1826
                        this.zoomLevel = state.getInt("zoomLevel");
1827
                }
1828
                loadedFromProject = true;
1829
        }
1830

    
1831
        @Override
1832
        public void saveToState(PersistentState state) throws PersistenceException {
1833
                super.saveToState(state);
1834

    
1835
                state.set("rasterdatastore", getDataStore());
1836
                state.set("legend", lastLegend);
1837
                state.set("colortable", getRender().getColorTable());
1838
                state.set("zoomLevel", zoomLevel);
1839
                state.set("recalcLevel", recalcLevel);
1840
        }
1841

    
1842
        public static void registerPersistence() {
1843
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
1844
                DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
1845
                if( definition == null ) {
1846
                        definition = manager.addDefinition(
1847
                                        DefaultFLyrRaster.class,
1848
                                        PERSISTENT_NAME,
1849
                                        PERSISTENT_DESCRIPTION,
1850
                                        null,
1851
                                        null
1852
                        );
1853
                        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE, "FLyrDefault");
1854

    
1855
                        registerPersistence(definition);
1856
                }
1857
        }
1858

    
1859
        public static void registerPersistence(DynStruct definition) {
1860
                definition.addDynFieldObject("rasterdatastore").setClassOfValue(RasterDataStore.class).setMandatory(false);
1861
                definition.addDynFieldObject("legend").setClassOfValue(ILegend.class).setMandatory(false);
1862
                definition.addDynFieldObject("colortable").setClassOfValue(ColorTable.class).setMandatory(false);
1863
                definition.addDynFieldInt("zoomLevel").setMandatory(false);
1864
                definition.addDynFieldBoolean("recalcLevel").setMandatory(false);
1865
        }
1866

    
1867
        public GeometryType getGeometryType() throws ReadException {
1868
                try {
1869
                        return GeometryLocator.getGeometryManager().getGeometryType(TYPES.SURFACE, SUBTYPES.GEOM2D);
1870
                } catch (GeometryTypeNotSupportedException e) {
1871
                        throw new ReadException(getDataStore().getName(), e);
1872
                } catch (GeometryTypeNotValidException e) {
1873
                        throw new ReadException(getDataStore().getName(), e);
1874
                }
1875
        }
1876

    
1877
        public void setDataStore(DataStore dataStore, String domain) throws LoadLayerException {
1878
                setDataStore(dataStore);
1879
        }
1880

    
1881
        protected void finalize() {
1882
                layerChangeSupport             = null;
1883
                state                          = null;
1884
                lastLegend                     = null;
1885
                colorTableLoadedFromProject    = null;
1886
                strategy                       = null;
1887
                configuration                  = null;
1888
                fileUtil                       = null;
1889
                rasterUtil                     = null;
1890
                crsUtil                        = null;
1891
                mathUtil                       = null;
1892
                uri                            = null;
1893
                affineTransformList            = null;
1894
                readingData                    = null;
1895
                dataStore                      = null;
1896
                render                         = null;
1897
        }
1898

    
1899
}