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

History | View | Annotate | Download (60.7 KB)

1 2443 nbrodin
/* 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 4181 fdiaz
*
6 2443 nbrodin
* 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 4181 fdiaz
*
11 2443 nbrodin
* 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 4181 fdiaz
*
16 2443 nbrodin
* 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 4181 fdiaz
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 2443 nbrodin
* MA  02110-1301, USA.
20 4181 fdiaz
*
21 2443 nbrodin
*/
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 4181 fdiaz
import java.net.URI;
36 2443 nbrodin
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
import org.gvsig.compat.print.PrintAttributes;
43
import org.gvsig.fmap.crs.CRSFactory;
44
import org.gvsig.fmap.dal.DataStore;
45
import org.gvsig.fmap.dal.DataStoreParameters;
46
import org.gvsig.fmap.dal.coverage.RasterLibrary;
47
import org.gvsig.fmap.dal.coverage.RasterLocator;
48
import org.gvsig.fmap.dal.coverage.RasterManager;
49
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
50
import org.gvsig.fmap.dal.coverage.datastruct.ColorItem;
51
import org.gvsig.fmap.dal.coverage.datastruct.ColorTableLibrary;
52
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
53
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
54
import org.gvsig.fmap.dal.coverage.datastruct.Params;
55
import org.gvsig.fmap.dal.coverage.datastruct.ViewPortData;
56
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
57
import org.gvsig.fmap.dal.coverage.exception.FilePaletteException;
58
import org.gvsig.fmap.dal.coverage.exception.FilterManagerException;
59
import org.gvsig.fmap.dal.coverage.exception.FilterTypeException;
60
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
61
import org.gvsig.fmap.dal.coverage.exception.InvalidSourceException;
62
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
63
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
64
import org.gvsig.fmap.dal.coverage.exception.QueryException;
65
import org.gvsig.fmap.dal.coverage.exception.ROIException;
66
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
67
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
68
import org.gvsig.fmap.dal.coverage.grid.RasterFilter;
69
import org.gvsig.fmap.dal.coverage.grid.RasterFilterList;
70
import org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager;
71
import org.gvsig.fmap.dal.coverage.grid.render.Render;
72
import org.gvsig.fmap.dal.coverage.grid.render.VisualPropertyEvent;
73
import org.gvsig.fmap.dal.coverage.grid.render.VisualPropertyListener;
74
import org.gvsig.fmap.dal.coverage.process.TaskEventManager;
75
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
76
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
77
import org.gvsig.fmap.dal.coverage.store.parameter.RasterFileStoreParameters;
78
import org.gvsig.fmap.dal.coverage.store.parameter.TileDataParameters;
79
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
80
import org.gvsig.fmap.dal.coverage.store.props.ColorTable;
81
import org.gvsig.fmap.dal.coverage.store.props.Statistics;
82
import org.gvsig.fmap.dal.coverage.util.CRSUtils;
83
import org.gvsig.fmap.dal.coverage.util.ColorConversion;
84
import org.gvsig.fmap.dal.coverage.util.FileUtils;
85
import org.gvsig.fmap.dal.coverage.util.Historical;
86
import org.gvsig.fmap.dal.coverage.util.MathUtils;
87
import org.gvsig.fmap.dal.coverage.util.ProviderServices;
88
import org.gvsig.fmap.dal.coverage.util.RasterUtils;
89
import org.gvsig.fmap.dal.exception.CloseException;
90
import org.gvsig.fmap.dal.exception.DataException;
91
import org.gvsig.fmap.dal.exception.InitializeException;
92
import org.gvsig.fmap.dal.exception.ReadException;
93
import org.gvsig.fmap.dal.raster.spi.CoverageStoreProviderServices;
94
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
95
import org.gvsig.fmap.geom.Geometry.TYPES;
96
import org.gvsig.fmap.geom.GeometryLocator;
97
import org.gvsig.fmap.geom.GeometryManager;
98
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
99
import org.gvsig.fmap.geom.primitive.Envelope;
100
import org.gvsig.fmap.geom.type.GeometryType;
101
import org.gvsig.fmap.geom.type.GeometryTypeNotSupportedException;
102
import org.gvsig.fmap.geom.type.GeometryTypeNotValidException;
103
import org.gvsig.fmap.mapcontext.MapContextLocator;
104
import org.gvsig.fmap.mapcontext.MapContextManager;
105
import org.gvsig.fmap.mapcontext.ViewPort;
106
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
107
import org.gvsig.fmap.mapcontext.exceptions.ReloadLayerException;
108
import org.gvsig.fmap.mapcontext.layers.FLayer;
109
import org.gvsig.fmap.mapcontext.layers.FLyrDefault;
110
import org.gvsig.fmap.mapcontext.layers.LayerChangeSupport;
111
import org.gvsig.fmap.mapcontext.layers.LayerListener;
112
import org.gvsig.fmap.mapcontext.layers.Tiling;
113
import org.gvsig.fmap.mapcontext.layers.operations.Classifiable;
114
import org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint;
115
import org.gvsig.fmap.mapcontext.layers.operations.SingleLayer;
116
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
117
import org.gvsig.fmap.mapcontext.rendering.legend.events.listeners.LegendListener;
118
import org.gvsig.raster.fmap.legend.ColorTableLegend;
119
import org.gvsig.raster.roi.ROI;
120
import org.gvsig.raster.util.RasterNotLoadException;
121
import org.gvsig.tools.ToolsLocator;
122
import org.gvsig.tools.dynobject.DynClass;
123
import org.gvsig.tools.dynobject.DynObjectManager;
124
import org.gvsig.tools.dynobject.DynObjectSet;
125
import org.gvsig.tools.dynobject.DynStruct;
126
import org.gvsig.tools.exception.BaseException;
127
import org.gvsig.tools.persistence.PersistenceManager;
128
import org.gvsig.tools.persistence.PersistentState;
129
import org.gvsig.tools.persistence.exception.PersistenceException;
130
import org.gvsig.tools.persistence.exception.PersistenceRuntimeException;
131
import org.gvsig.tools.task.Cancellable;
132
import org.gvsig.tools.task.SimpleTaskStatus;
133
import org.gvsig.tools.task.TaskStatusManager;
134
import org.gvsig.tools.task.impl.BaseTaskStatus;
135
import org.slf4j.Logger;
136
import org.slf4j.LoggerFactory;
137
138
/**
139
 * Raster layer
140 4181 fdiaz
 *
141 2443 nbrodin
 * @author Nacho Brodin (nachobrodin@gmail.com)
142
 */
143
@SuppressWarnings("deprecation")
144
public class DefaultFLyrRaster extends FLyrDefault implements FLyrRaster, Multiresolution, InfoByPoint, Classifiable,
145
                IRasterLayerActions, ILayerState, VisualPropertyListener, SingleLayer {
146 5462 llmarques
147
    private static final Logger LOG = LoggerFactory.getLogger(DefaultFLyrRaster.class);
148
149 2443 nbrodin
        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 4181 fdiaz
        private URI                  uri                            = null;
179
180 2443 nbrodin
        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 4181 fdiaz
187 2443 nbrodin
        public class RasterTaskStatus extends BaseTaskStatus {
188
                Cancellable c = null;
189 4181 fdiaz
190 2443 nbrodin
                public RasterTaskStatus(String tittle, Cancellable c) {
191
                        super(tittle);
192
                        this.c = c;
193
                }
194 4181 fdiaz
195 2443 nbrodin
                public boolean isCancellationRequested() {
196
                        if(c != null)
197
                                return this.c.isCanceled();
198
                        return false;
199
                }
200 4181 fdiaz
201 2443 nbrodin
                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 2582 nbrodin
        private boolean                 layerInitialize        = false;
216 4181 fdiaz
217 2443 nbrodin
        public DefaultFLyrRaster() {
218
                affineTransformList = rManager.createHistoricalService();
219
        }
220 4181 fdiaz
221 2443 nbrodin
        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 4181 fdiaz
235 2443 nbrodin
        /**
236
         * Builds a new raster layer
237
         * @param fileName
238
         * @return
239 4181 fdiaz
         * @throws RasterNotLoadException
240
         * @throws LoadLayerException
241 2443 nbrodin
         */
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 4181 fdiaz
                storeParameters.setURI(file.toURI());
246
247 2443 nbrodin
                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 5136 fdiaz
                    enableAwake();
270
                } catch (ReloadLayerException | NotAvailableStateException e) {
271 2443 nbrodin
                        // No se ha podido recuperar la capa con exito
272
                }
273
        }
274
275
        public void load() throws LoadLayerException {
276
                if (isStopped() || getDataStore() == null)
277
                        return;
278
279
                enableStopped(); // Paramos la capa mientras se hace un load
280
281 4181 fdiaz
                boolean test = false;
282 2443 nbrodin
                DataStoreParameters params = getDataStore().getParameters();
283
                DataStoreParameters p = params;
284
                if (params != null) {
285
                        if(params instanceof TileDataParameters) {
286
                                uri = ((RasterDataParameters)params).getURI();
287
                                if(uri == null)
288
                                        p = (DataStoreParameters)((TileDataParameters)params).getDataParameters();
289
                        }
290
                        if(uri == null) {
291
                                if(params instanceof RasterDataParameters)
292
                                        uri = ((RasterDataParameters)p).getURI();
293
                        }
294
                }
295
296
                try {
297
                        if(!getDataStore().isOpen())
298
                                dataStore = rManager.getProviderServices().open(params);
299
                        else
300
                                dataStore.reload();
301
                } catch (NotSupportedExtensionException e) {
302
                        throw new LoadLayerException(this.getName());
303
                } catch (RasterDriverException e) {
304
                        throw new LoadLayerException(this.getName());
305
                }
306
        }
307 4181 fdiaz
308 2582 nbrodin
        public void setLayerInitialized(boolean initialized) {
309
                layerInitialize = initialized;
310
        }
311 2443 nbrodin
312
        /**
313
         * Acciones de inicializaci?n despu?s de que la fuente de datos
314 4181 fdiaz
         * de la capa est? asignada.
315
         * @throws FilePaletteException
316 2443 nbrodin
         */
317
        public void init() throws LoadLayerException, FilePaletteException {
318
                layerInitialize = true;
319 4181 fdiaz
320 2443 nbrodin
                if (getDataStore() == null)
321
                        throw new LoadLayerException("Formato no valido", new IOException());
322
323
                render = getDataStore().getRender();
324
                render.addVisualPropertyListener(this);
325
                initFilters();
326
327
                //Inicializaci?n del historico de transformaciones
328
                affineTransformList.clear();
329
                affineTransformList.add(this.getAffineTransform());
330
331
                try {
332
                        if(!isOpen())
333
                                enableOpen();
334
                } catch (NotAvailableStateException e) {
335
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Awake=" + isAwake(), e);
336
                }
337
        }
338
339
        public IProjection readProjection() throws RasterDriverException {
340
                try {
341
                        crsUtil.setCRSFactory(CRSFactory.cp);
342
                        if( getDataStore() == null )
343
                                return null;
344
                        return crsUtil.convertWktToIProjection(getDataStore().getWktProjection());
345
                } catch (Exception e) {
346
                        throw new RasterDriverException("Problems converting from WKT to IProjection", e);
347
                } catch (Error e) {
348
                        e.printStackTrace();
349
                        return null;
350
                }
351
        }
352
353
        /**
354
         * Crea el objeto renderizador de raster
355
         * @return Rendering
356
         */
357
        public Render getRender() {
358
                if (render == null) {
359
                        if(getDataStore() != null) {
360
                                render = getDataStore().getRender();
361
                                render.addVisualPropertyListener(this);
362
                        }
363
                }
364
                return render;
365
        }
366 4181 fdiaz
367
        public URI getURI() {
368 2443 nbrodin
                return uri;
369
        }
370
371
        public void setNoDataTransparent(boolean t) {
372
                getNoDataValue().setNoDataTransparent(t);
373
                if(getRender().getRenderingTransparency() != null) {
374
                        getRender().getRenderingTransparency().setNoData(getDataStore().getNoDataValue());
375
                        getRender().getRenderingTransparency().activeTransparency();
376
                }
377
        }
378
379
        /**
380
         * Initializes the filter list to render this raster layer
381 4181 fdiaz
         * @throws FilePaletteException
382 2443 nbrodin
         */
383
        protected void initFilters() throws FilePaletteException {
384
                if(getDataType() == null)
385
                        return;
386 4181 fdiaz
387 2443 nbrodin
                RasterFilterList filterList = rManager.createEmptyFilterList(getDataType()[0]);
388
                if(loadedFromProject) {
389
                        filterList = getDataStore().getRender().getFilterList();
390
                }
391
392
                if(getDataStore() == null)
393
                        return;
394 4181 fdiaz
395 2443 nbrodin
                if(getDataStore().getNoDataValue() != null) {
396
                        getDataStore().getNoDataValue().load();
397
                }
398
399
                filterList.setInitDataType(getDataType()[0]);
400
401
                // Quitamos la leyenda
402
                lastLegend = null;
403
404
                try {
405
                        //Si en la carga del proyecto se carg? una tabla de color asignamos esta
406
                        if(colorTableLoadedFromProject != null) {
407
                                setLastLegend(colorTableLoadedFromProject);
408
                                RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
409
                                Params params = filterList.createEmptyFilterParams();
410
                                params.setParam("colorTable", colorTableLoadedFromProject);
411
                                colorTableManager.addFilter(params);
412
                        } else
413
                                //sino ponemos la tabla asociada al raster
414
                                if (getDataStore().getColorTable() != null) {
415
                                        ColorTable table = getDataStore().getColorTable();
416
                                        setLastLegend(table);
417
                                        RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
418
                                        Params params = filterList.createEmptyFilterParams();
419
                                        params.setParam("colorTable", table);
420
                                        colorTableManager.addFilter(params);
421
                                } else //sino hace lo que dice en las preferencias
422 4181 fdiaz
                                        if(getDataStore().needEnhanced() ||
423
                                                        (loadedFromProject && filterList.get("enhanced_stretch") != null))
424 2443 nbrodin
                                                loadEnhancedOrColorTable(filterList);
425
                        colorTableLoadedFromProject = null;
426
427
                        getRender().setFilterList(filterList);
428
                        // Inicializo la transparencia para el render
429
                        /*if(!loadedFromProject) {
430
                                getRender().setLastTransparency(getDataStore().getTransparency().cloneTransparency());
431
                        }*/
432
                        loadedFromProject = false;
433
                } catch (FilterTypeException e) {
434
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
435
                        logger.error("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
436
                } catch (FilterManagerException e) {
437
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
438
                        logger.error("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
439
                }
440
        }
441
442
        /**
443
         * Mira la configuracion para saber si debe cargar un realce o una tabla
444
         * de color por defecto
445
         * @param filterManager
446
         * @throws FilterTypeException
447 4181 fdiaz
         * @throws FilePaletteException
448 2443 nbrodin
         */
449
        private void loadEnhancedOrColorTable(RasterFilterList filterList) throws FilterTypeException, FilterManagerException, FilePaletteException {
450
                String colorTableName = null;
451
                if(configuration != null)
452
                        colorTableName = configuration.getValueString("loadlayer_usecolortable", (String) null);
453
454
                String palettesPath = System.getProperty("user.home") +
455
                File.separator +
456
                "gvSIG" + // PluginServices.getArguments()[0] +
457
                File.separator + "colortable";
458
459
                Statistics stats = getDataStore().getStatistics();
460
                ColorTableLibrary colorTableLibrary = rManager.getDataStructFactory().getColorTableLibrary();
461
462
                if (colorTableName != null)
463
                        try {
464
                                stats.calculate(RasterLibrary.statisticsScale);
465
                                if (getDataStore().getBandCount() == 1) {
466
                                        ArrayList<String> fileList = colorTableLibrary.getPaletteFileList(palettesPath);
467
                                        for (int i = 0; i < fileList.size(); i++) {
468
                                                ArrayList<ColorItem> paletteItems = new ArrayList<ColorItem>();
469
                                                String paletteName = colorTableLibrary.loadPalette(palettesPath, (String) fileList.get(i), paletteItems);
470
                                                if (paletteName.equals(colorTableName)) {
471
                                                        if (paletteItems.size() <= 0)
472
                                                                continue;
473
474
                                                        ColorTable colorTable = colorTableLibrary.createColorTable();
475
                                                        colorTable.setName(paletteName);
476
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
477
                                                        colorTable.setInterpolated(true);
478
479
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
480
481
                                                        setLastLegend(colorTable);
482
483
                                                        RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
484
                                                        Params params = filterList.createEmptyFilterParams();
485
                                                        params.setParam("colorTable", colorTable);
486
                                                        colorTableManager.addFilter(params);
487
                                                        return;
488
                                                }
489
                                        }
490
                                }
491
                        } catch (FileNotOpenException e) {
492
                                // No podemos aplicar el filtro
493
                        } catch (RasterDriverException e) {
494
                                // No podemos aplicar el filtro
495
                        } catch (ProcessInterruptedException e) {
496
                                // El usuario ha cancelado el proceso
497
                        }
498
499
                        RasterFilterListManager enhancementManager = filterList.getManagerByID("EnhancementStretch");
500
                        RasterFilter f = filterList.getByName("enhanced_stretch");
501
                        if(f == null) {
502
                                Params params = filterList.createEmptyFilterParams();
503
                                params.setParam("stats", stats);
504
                                params.setParam("remove", new Boolean(false));
505
                                params.setParam("renderBands", getRender().getRenderColorInterpretation().buildRenderBands());
506
                                params.setParam("stretchs", null);//coge el LinearStretchParams por defecto
507
                                params.setParam("rgb", new Boolean(true));
508
                                enhancementManager.addFilter(params);
509
                        }
510
        }
511
512
        public boolean isReproyectable() {
513
                if (getDataStore() == null)
514
                        return false;
515
                return getDataStore().isReproyectable();
516
        }
517
518
        /**
519
         * @throws ReadException
520
         * @throws ReadDriverException
521
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
522
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
523
         *                 com.iver.utiles.swing.threads.Cancellable)
524
         */
525
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadException {
526
                TaskEventManager task = rManager.getRasterTask();
527
                task.setEvent(null);
528 5462 llmarques
529 2443 nbrodin
                if(!layerInitialize) {
530
                        if (getDataStore() != null)
531
                                try {
532
                                        this.init();
533
                                } catch (FilePaletteException e) {
534
                                        throw new ReadException("Error in raster legend", e);
535
                                } catch (LoadLayerException e) {
536
                                        throw new ReadException("Error initializing the layer", e);
537
                                }
538
                }
539
540
                try {
541
                        if (!isOpen())
542
                                return;
543
544
                        enableStopped();
545
                        // callLegendChanged(null);
546 4181 fdiaz
547 2443 nbrodin
                        //Solo el zoom normal recalcula el nivel dependiendo de la escala. El zoom por niveles asigna
548
                        //?l el nivel de zoom por lo que no habr? que recalcularlo.
549
                        if(recalcLevel) {
550
                                double pixelSize = vp.getEnvelope().getLength(0) / (double)vp.getImageWidth();
551
                                zoomLevel = getDataStore().getNearestLevel(pixelSize);
552
                        }
553
                        recalcLevel = true;
554
555
                        strategy = new RasterDrawStrategy(getMapContext(), this);
556
                        strategy.stackStrategy();
557
                        HashMap<DefaultFLyrRaster, Boolean> tStr = strategy.getStrategy();
558
                        if (tStr != null &&
559
                                tStr.get(this) != null &&
560
                                ((Boolean) (tStr.get(this))).booleanValue() == false) {
561
                                disableStopped();
562
                                return;
563
                        }
564
565
                        if (isWithinScale(scale)) {
566 4181 fdiaz
567 2443 nbrodin
                                if (mustTileDraw) {
568
                                        Point2D p = vp.getOffset();
569
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
570
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
571
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
572
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
573
                                                // drawing part
574
                                                try {
575
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
576
                                                        draw(image, g, vport, cancel);
577 5462 llmarques
                        } catch (QueryException | ProcessInterruptedException | NoninvertibleTransformException e) {
578
                            throw new ReadException(getDataStore().getFullName(), e);
579
                        }
580 2443 nbrodin
                                } else
581
                                        try {
582
                                                draw(image, g, vp, cancel);
583 5462 llmarques
                                        } catch (QueryException | ProcessInterruptedException e) {
584
                                                throw new ReadException(getDataStore().getFullName(), e);
585 4181 fdiaz
                                        }
586 2443 nbrodin
                        }
587 4181 fdiaz
588 2443 nbrodin
                        //callLegendChanged(null);
589
                } finally {
590
                        disableStopped();
591
                        task.setEvent(null);
592
                }
593
        }
594
595 5462 llmarques
    protected void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel)
596
        throws QueryException, ProcessInterruptedException {
597 2443 nbrodin
                Envelope adjustedExtent = vp.getAdjustedExtent();
598
                if (adjustedExtent == null)
599
                        return;
600
                Extent e = rManager.getDataStructFactory().createExtent(adjustedExtent.getLowerCorner().getX(),
601
                                adjustedExtent.getUpperCorner().getY(), adjustedExtent
602
                                                .getUpperCorner().getX(),
603
                                adjustedExtent
604
                                                .getLowerCorner().getY());
605
                Dimension imgSz = vp.getImageSize();
606
                ViewPortData vp2 = rManager.getDataStructFactory().createViewPortData(vp.getProjection(), e, imgSz );
607
                vp2.setMat(vp.getAffineTransform());
608 2840 cmartinez
                vp2.setDPI((int)vp.getDPI());
609 4181 fdiaz
                //vp2.setTime(vp.getTime());
610
611 2443 nbrodin
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
612
                SimpleTaskStatus taskStatus = new RasterTaskStatus("Drawing " + getName() + "...", cancel);
613
                manager.add(taskStatus);
614
                taskStatus.setAutoremove(true);
615 4181 fdiaz
616 2443 nbrodin
                try {
617
                        if(getDataStore().isTiled()) {
618 5462 llmarques
                                getRender().drawTiledService(g, vp2, vp.getImageSize(), this.getCoordTrans(), taskStatus);
619 2443 nbrodin
                        } else {
620 5462 llmarques
                                getRender().draw(g, vp2, this.getCoordTrans(), taskStatus);
621 2443 nbrodin
                        }
622
                } finally {
623
                        taskStatus.terminate();
624 5462 llmarques
                        taskStatus.remove();
625 2443 nbrodin
                }
626
        }
627
628
        /**
629
         * Inserta la proyecci?n.
630
         *
631
         * @param proj Proyecci?n.
632
         */
633
        public void setProjection(IProjection proj) {
634
                try {
635
                        getDataStore().setProjection(proj, true);
636
                        super.setProjection(proj);
637
                } catch (RmfSerializerException e) {
638
                        logger.error("Error saving the projection", e);
639
                }
640
        }
641 4181 fdiaz
642 2443 nbrodin
        public void setProjection(IProjection proj, boolean persist) {
643
                try {
644
                        getDataStore().setProjection(proj, persist);
645
                        super.setProjection(proj);
646
                } catch (RmfSerializerException e) {
647
                        logger.error("Error saving the projection", e);
648
                }
649
        }
650
651
        public Envelope getFullEnvelope() {
652
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
653
                //un extent aunque la capa no est? abierta
654
                if(/*!isOpen() || */getDataStore() == null || getDataStore().getExtent() == null)
655
                        return null;
656
657
                Rectangle2D e = getDataStore().getExtent().toRectangle2D();
658
                try {
659 5462 llmarques
                        Envelope env = geomManager.createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
660 2443 nbrodin
                                        .getMaxY(), SUBTYPES.GEOM2D);
661 5462 llmarques
662
                        if(this.getCoordTrans() != null){
663
                            return env.convert(getCoordTrans());
664 2443 nbrodin
                        }
665 5462 llmarques
                        return env;
666 2443 nbrodin
                } catch (CreateEnvelopeException e1) {
667
                        logger.error("Error creating the envelope", e);
668
                        return null;
669
                }
670
        }
671 4181 fdiaz
672 2443 nbrodin
        /**
673
         * Obtiene el valor del pixel del Image en la posici?n x,y
674
         * @param x Posici?n x
675
         * @param y Posici?n y
676
         * @return valor de pixel
677
         */
678
//        public int[] getPixel(int pxx, int pxy) {
679
//                int[] argb = { -1, -1, -1, -1 };
680
//                if (!isOpen() || (image == null))
681
//                        return argb;
682
//                if (pxx >= 0 && pxx < image.getWidth() && pxy >= 0 && pxy < image.getHeight()) {
683
//                        int value = image.getRGB(pxx, pxy);
684
//                        argb[0] = ((value & 0xff000000) >> 24);
685
//                        argb[1] = ((value & 0x00ff0000) >> 16);
686
//                        argb[2] = ((value & 0x0000ff00) >> 8);
687
//                        argb[3] = (value & 0x000000ff);
688
//                }
689
//                return argb;
690
//        }
691
692
        public double getMaxX() {
693
                if(getFullEnvelope() != null)
694
                        return getFullEnvelope().getMaximum(0);
695
                return -1;
696
        }
697
698
        public double getMaxY() {
699
                if(getFullEnvelope() != null)
700
                        return this.getFullEnvelope().getMaximum(1);
701
                return -1;
702
        }
703
704
        public double getMinX() {
705
                if(getFullEnvelope() != null)
706
                        return getFullEnvelope().getMinimum(0);
707
                return -1;
708
        }
709
710
        public double getMinY() {
711
                if(getFullEnvelope() != null)
712
                        return getFullEnvelope().getMinimum(1);
713
                return -1;
714
        }
715
716
        public String queryByPoint(Point p) {
717
                if (!isOpen())
718
                        return null;
719
                ColorConversion conv = rManager.getColorConversion();
720
721
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
722
723
                ArrayList<Object> attr = getAttributes();
724
                data += "  <raster\n";
725
                data += "    File=\"" + getFile() + "\"\n";
726
                for (int i = 0; i < attr.size(); i++) {
727
                        Object[] a = (Object[]) attr.get(i);
728
729
                        data += "    " + a[0].toString() + "=";
730
                        if (a[1].toString() instanceof String)
731
                                data += "\"" + a[1].toString() + "\"\n";
732
                        else
733
                                data += a[1].toString() + "\n";
734
                }
735
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
736
                data += "    Point_WC=\"" + mathUtil.format(posXWC, 3) + " , " + mathUtil.format(posYWC, 3) + "\"\n";
737
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
738
                double[] cmyk = conv.RGBtoCMYK(r & 0xff, g & 0xff, b & 0xff, 1D);
739
                data += "    CMYK=\"" + mathUtil.format(cmyk[0], 4) + ", " + mathUtil.format(cmyk[1], 4) + ", " + mathUtil.format(cmyk[2], 4) + "," + mathUtil.format(cmyk[3], 4) + "\"\n";
740
                double[] hsl = conv.RGBtoHSL(r & 0xff, g & 0xff, b & 0xff);
741
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
742
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
743
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
744
                data += "    HSL=\"" + mathUtil.format(hsl[0], 4) + ", " + mathUtil.format(hsl[1], 4) + ", " + mathUtil.format(hsl[2], 4) + "\"\n";
745
                data += "  />\n";
746
747
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
748
                return data;
749
        }
750
751
        /**
752
         * Filters a string for being suitable as XML Tag, erasing
753
         * all not alphabetic or numeric characters.
754
         * @param s
755
         * @return string normalized
756
         */
757
        private String normalizeAsXMLTag(String s) {
758
                return s.replaceAll("[^a-zA-Z0-9]", "");
759
        }
760
761
        public ArrayList<Object> getAttributes() {
762
                ArrayList<Object> attr = new ArrayList<Object>();
763
                if(!isOpen())
764
                        return attr;
765
                Object [][] a = {
766
                        {"Filename", getDataStore().getName()},
767
                        {"Filesize", new Long(getDataStore().getFileSize())},
768
                        {"Width", new Integer((int)getDataStore().getWidth())},
769
                        {"Height", new Integer((int)getDataStore().getHeight())},
770
                        {"Bands", new Integer(getDataStore().getBandCount())}
771
                };
772
                for (int i = 0; i < a.length; i++)
773
                        attr.add(a[i]);
774
                return attr;
775
        }
776
777
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
778
                        double scale, PrintAttributes propeties) throws ReadException {
779
780
                if (/*!isOpen() ||*/ !isVisible() || !isWithinScale(scale))
781
                        return;
782 4181 fdiaz
783 2443 nbrodin
                TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
784
                SimpleTaskStatus taskStatus = new RasterTaskStatus("Printing raster " + getName() + "...", cancel);
785
                manager.add(taskStatus);
786
                taskStatus.setAutoremove(true);
787
788
                if (!mustTilePrint)
789
                        draw(null, g, viewPort, cancel,scale);
790
                else {
791
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
792
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
793
                        taskStatus.setRangeOfValues(0, tiles.getNumTiles());
794
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
795
                                // Parte que dibuja
796
                                try {
797
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
798
                                        draw(null, g, vp, cancel, scale);
799
                                        taskStatus.setCurValue(tileNr);
800
                                } catch (NoninvertibleTransformException e) {
801
                                        throw new ReadException("Error en la transformaci?n.", e);
802
                                } finally {
803
                                        taskStatus.terminate();
804
                                }
805
                        }
806
                }
807 4181 fdiaz
808 2443 nbrodin
                taskStatus.terminate();
809
        }
810
811
        /*public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
812
                        double scale) throws ReadException {
813
                if(!isOpen())
814
                        return;
815

816
                // Para no pedir imagenes demasiado grandes, vamos
817
                // a hacer lo mismo que hace EcwFile: chunkear.
818
                // Llamamos a drawView con cuadraditos m?s peque?os
819
                // del BufferedImage ni caso, cuando se imprime viene con null
820

821
                int numW, numH;
822
                int stepX, stepY;
823
                int xProv, yProv;
824
                int A = 1500;
825
                int H = 1500;
826
                int altoAux, anchoAux;
827

828
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
829

830
                // Vamos a hacerlo en trozos de AxH
831
                Rectangle r = g.getClipBounds();
832
                numW = (r.width) / A;
833
                numH = (r.height) / H;
834

835
                double[] srcPts = new double[8];
836
                double[] dstPts = new double[8];
837

838
                yProv = r.y;
839
                for (stepY = 0; stepY < numH + 1; stepY++) {
840
                        if ((yProv + H) > r.getMaxY())
841
                                altoAux = (int) r.getMaxY() - yProv;
842
                        else
843
                                altoAux = H;
844

845
                        xProv = r.x;
846
                        for (stepX = 0; stepX < numW + 1; stepX++) {
847
                                if ((xProv + A) > r.getMaxX())
848
                                        anchoAux = (int) r.getMaxX() - xProv;
849
                                else
850
                                        anchoAux = A;
851

852
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
853

854
                                // Parte que dibuja
855
                                srcPts[0] = xProv;
856
                                srcPts[1] = yProv;
857
                                srcPts[2] = xProv + anchoAux + 1;
858
                                srcPts[3] = yProv;
859
                                srcPts[4] = xProv + anchoAux + 1;
860
                                srcPts[5] = yProv + altoAux + 1;
861
                                srcPts[6] = xProv;
862
                                srcPts[7] = yProv + altoAux + 1;
863

864
                                try {
865
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
866
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
867
                                        // Extent extent = new Extent(rectCuadricula);
868

869
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
870
                                        ViewPort vp = (ViewPort)viewPort.clone();
871
                                        vp.setImageSize(tam);
872
                                        Envelope env = geomManager.createEnvelope(rectCuadricula
873
                                                        .getMinX(), rectCuadricula.getMinY(),
874
                                                        rectCuadricula.getMaxX(), rectCuadricula.getMaxY(),
875
                                                        SUBTYPES.GEOM2D);
876
                                        vp.setEnvelope(env);
877
                                        vp.setAffineTransform(mat);
878
                                        draw(null, g, vp, cancel, scale);
879

880
                                } catch (NoninvertibleTransformException e) {
881
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
882
                                } catch (ReadException e) {
883
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
884
                                } catch (CreateEnvelopeException e) {
885
                                        logger.error("Error creating the envelope", e);
886
                                } catch (CloneNotSupportedException e) {
887
                                        logger.error("Error cloning the viewport", e);
888
                                }
889
                                // Fin parte que dibuja
890
                                xProv = xProv + A;
891
                        }
892
                        yProv = yProv + H;
893
                }
894
        }*/
895
896
        /**
897
         * Borra de la lista de listeners el que se pasa como par?metro.
898
         *
899
         * @param o LayerListener a borrar.
900
         *
901
         * @return True si ha sido correcto el borrado del Listener.
902
         */
903 4183 fdiaz
    public boolean removeLayerListener(LayerListener o) {
904
        if (this.isRemoveRasterFlag()) {
905
            try {
906
                enableClosed();
907
            } catch (NotAvailableStateException e1) {
908
                // No se ha podido cambiar el estado de la capa a cerrado
909
            }
910
        }
911 2443 nbrodin
912 4183 fdiaz
        // Salva a RMF
913
        if (getDataStore() != null)
914
            // Guardamos la GeoReferenciacion de cada dataset
915
            try {
916
                getDataStore().saveGeoreferencingToRmf();
917
            } catch (Exception e) {
918
                logger.info("error_salvando_rmf", e);
919
            }
920 2443 nbrodin
921 4183 fdiaz
        if (this.isRemoveRasterFlag()) {
922
            if (getDataStore() != null) {
923
                URI[] uris = getUris().clone();
924 2443 nbrodin
925 4183 fdiaz
                try {
926
                    getDataStore().close();
927
                } catch (CloseException e) {
928
                }
929 2443 nbrodin
930 4183 fdiaz
                dataStore = null;
931
                if (render != null)
932
                    render.dispose();
933
                render = null;
934
                // System.gc();
935
                this.setRemoveRasterFlag(true);
936 2443 nbrodin
937 4183 fdiaz
                for (int i = 0; i < uris.length; i++) {
938
                    if ("FILE".equalsIgnoreCase(uris[i].getScheme())) {
939 4181 fdiaz
                        File file = new File(uris[i]);
940 4183 fdiaz
                        File dirTemp = fileUtil.getTemporalFile();
941
                        if (!file.exists())
942
                            continue;
943
                        if (dirTemp.compareTo(file.getParentFile()) == 0) {
944
                            file.delete();
945 2443 nbrodin
946 4183 fdiaz
                            // Borramos todos los ficheros que puedan tener
947
                            // relacion con el fichero actual
948
                            String basefile = file.getName();
949
                            File basepath = file.getParentFile();
950
                            int last = basefile.lastIndexOf(".");
951
                            if (last != -1)
952
                                basefile = basefile.substring(0, last + 1);
953
                            File[] list = basepath.listFiles();
954
                            for (int j = 0; j < list.length; j++)
955
                                if (list[j].getName().startsWith(basefile))
956
                                    list[j].delete();
957
                        }
958
                    }
959
                }
960
            }
961
        }
962
        updateDrawVersion();
963
        return super.layerListeners.remove(o);
964
    }
965 2443 nbrodin
966
        public boolean isRemoveRasterFlag() {
967
                return removeRasterFlag;
968
        }
969
970
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
971
                this.removeRasterFlag = removeRasterFlag;
972
        }
973
974
        public String getTocImageIcon() {
975
                return "map-ok-ico";
976
        }
977
978
        public int[] getTileSize() {
979
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
980
                return size;
981
        }
982
983
        public boolean isTiled() {
984
                return mustTileDraw;
985
        }
986
987
        public boolean isGeoreferenced() {
988
                return getDataStore().isGeoreferenced();
989
        }
990
991
        public NoData getNoDataValue() {
992
                return getDataStore().getNoDataValue();
993
        }
994
995
        /**
996
         * Sets the nodata value for this layer
997
         * @param nd
998
         */
999
        public void setNoDataValue(NoData nd) {
1000
                if (getDataStore() != null)
1001
                        getDataStore().setNoDataValue(nd);
1002
        }
1003
1004
        /**
1005
         * Gets the height in world coordinates of this raster layer
1006
         */
1007
        public double getWCHeight() {
1008
                return getFullEnvelope().getMaximum(1);
1009
        }
1010
1011
        /**
1012
         * Gets the width in world coordinates of this raster layer
1013
         */
1014
        public double getWCWidth() {
1015
                return getFullEnvelope().getMaximum(0);
1016
        }
1017
1018
        /**
1019
         * Gets the size of all files of this raster layer
1020
         */
1021
        public long[] getFileSize() {
1022
                if (getDataStore() == null)
1023
                        return null;
1024
1025
                return getDataStore().getFileSizeByProvider();
1026
        }
1027
1028 4181 fdiaz
           /**
1029
     * Gets the list of URIs
1030
     */
1031
    public URI[] getUris() {
1032
        if (getDataStore() == null)
1033
            return null;
1034 2443 nbrodin
1035 4181 fdiaz
        return getDataStore().getURIByProvider();
1036
    }
1037 2443 nbrodin
1038
        /**
1039
         * Returns the number of files in this raster layer
1040
         */
1041
        public int getFileCount() {
1042
                return getDataStore().getProviderCount();
1043
        }
1044
1045
        /*
1046
         * (non-Javadoc)
1047
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileFormat()
1048
         */
1049
        public String getFileFormat() {
1050
                if(getDataStore().getSourceType() == RasterDataStore.FILE) {
1051
                        String fName = getDataStore().getName();
1052
                        int index = fName.lastIndexOf(".") + 1;
1053
                        String ext = null;
1054
                        if (index > 0)
1055
                                ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1056
                        return ext;
1057
                }
1058
                if(getDataStore().getSourceType() == RasterDataStore.POSTGIS) {
1059
                        return "POSTGIS";
1060
                }
1061
                return null;
1062
        }
1063
1064
        public int[] getDataType() {
1065
                return getDataStore().getDataType();
1066
        }
1067
1068
        /**
1069
         * Sets the filter list
1070
         */
1071
        public void setRenderFilterList(RasterFilterList filterList) {
1072
                getRender().setFilterList(filterList);
1073
        }
1074 4181 fdiaz
1075 2443 nbrodin
        public DynObjectSet getInfo(org.gvsig.fmap.geom.primitive.Point p, double tolerance) throws LoadLayerException, DataException {
1076
                DynObjectSetRasterInfo info = new DynObjectSetRasterInfo();
1077 4181 fdiaz
1078 2443 nbrodin
                if (!isOpen()) {
1079
                        info.addField("Layer not open", normalizeAsXMLTag(getName()), 0);
1080
                        return info;
1081
                }
1082 4181 fdiaz
1083 2443 nbrodin
                Point2D pReal = new Point2D.Double(p.getX(), p.getY());
1084
                Point2D px = new Point2D.Double();
1085
                if(        pReal.getX() > this.getMinX() &&
1086
                        pReal.getX() < this.getMaxX() &&
1087
                        pReal.getY() > this.getMinY() &&
1088
                        pReal.getY() < this.getMaxY()) {
1089
                        px = transformPoint(pReal);
1090
                }
1091
                //int[] rgb = getPixel((int) p.getX(), (int) p.getY());
1092
                //ColorConversion conv = rManager.getColorConversion();
1093 4181 fdiaz
1094 2443 nbrodin
                info.addField("File", normalizeAsXMLTag(getName()), 0);
1095
                info.addField("View Point", "[" + p.getX() + " , " + p.getY() + "]", 1);
1096
                info.addField("World Point", "[" + mathUtil.format(pReal.getX(), 3) + " , " + mathUtil.format(pReal.getY(), 3) + "]", 2);
1097
                if (px == null)
1098
                        info.addField("Pixel Point", "Out", 3);
1099
                else
1100
                        info.addField("Pixel Point", "[" + (int) px.getX() + ",  " + (int) px.getY() + "]", 3);
1101 4181 fdiaz
1102 2443 nbrodin
                //La informaci?n RGB no puede obtener de la capa
1103 4181 fdiaz
1104 2443 nbrodin
                /*info.addField("RGB", "[" + rgb[1] + ",  " + rgb[2] + ",  " + rgb[3] + "]", 4);
1105
                double[] cmyk = conv.RGBtoCMYK(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff, 1D);
1106
                info.addField("CMYK", "[" + mathUtil.format(cmyk[0], 4) + ",  " + mathUtil.format(cmyk[1], 4) + ",  " + mathUtil.format(cmyk[2], 4) + ",  " + mathUtil.format(cmyk[3], 4) + "]", 5);
1107
                double[] hsl = conv.RGBtoHSL(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff);
1108
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
1109
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
1110
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
1111
                info.addField("HSL", "[" + mathUtil.format(hsl[0], 4) + ",  " + mathUtil.format(hsl[1], 4) + ",  " + mathUtil.format(hsl[2], 4) + "]", 6);*/
1112 4181 fdiaz
1113 2443 nbrodin
                String data = "[";
1114
                try {
1115
                        if (px != null) {
1116
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3) {
1117
                                        for(int i = 0; i < getDataStore().getBandCount(); i++) {
1118
                                                if(getDataStore().isInside(pReal)) {
1119
                                                        Point2D pxAux = transformPoint(pReal);
1120 4181 fdiaz
                                                        int val = ((Integer)getDataStore().getData((int)pxAux.getX(),
1121 2443 nbrodin
                                                                        (int)pxAux.getY(), i)).intValue();
1122
                                                        if(getDataType()[0] == Buffer.TYPE_BYTE)
1123
                                                                data += (val & 0x000000ff) + ",  ";
1124
                                                        else
1125
                                                                data += val + ",  ";
1126
                                                }
1127
                                        }
1128
                                }
1129
                                if(getDataType()[0] == 4) {
1130
                                        for(int i = 0; i < getDataStore().getBandCount(); i++) {
1131
                                                if(getDataStore().isInside(pReal)) {
1132
                                                        Point2D pxAux = transformPoint(pReal);
1133 4181 fdiaz
                                                        data += ((Float)getDataStore().getData((int)pxAux.getX(),
1134 2443 nbrodin
                                                                        (int)pxAux.getY(), i)).floatValue() + ",  ";
1135
                                                }
1136
                                        }
1137
                                }
1138
                                if(getDataType()[0] == 5) {
1139
                                        for(int i = 0; i < getDataStore().getBandCount(); i++) {
1140
                                                if(getDataStore().isInside(pReal)) {
1141
                                                        Point2D pxAux = transformPoint(pReal);
1142 4181 fdiaz
                                                        data += ((Double)getDataStore().getData((int)pxAux.getX(),
1143 2443 nbrodin
                                                                        (int)pxAux.getY(), i)).doubleValue() + ",  ";
1144
                                                }
1145
                                        }
1146
                                }
1147
                        }
1148
                        data +=  "]";
1149
                        info.addField("Band Value", data, 7);
1150
                } catch (RasterDriverException ex) {
1151
                        throw new LoadLayerException("Error en el acceso al dataset", ex);
1152
                } catch (InvalidSetViewException ex) {
1153
                        throw new LoadLayerException("Error en la asignaci?n de la vista en getData", ex);
1154
                } catch (FileNotOpenException ex) {
1155
                        throw new LoadLayerException("Fichero no abierto en el dataset", ex);
1156
                }
1157
                return info;
1158
        }
1159 4181 fdiaz
1160 2443 nbrodin
        /**
1161
         * Transforma un punto real a coordenadas pixel
1162 4181 fdiaz
         *
1163 2443 nbrodin
         * @param numberBand
1164
         * @param pReal
1165
         * @return
1166 4181 fdiaz
         * @throws LoadLayerException
1167 2443 nbrodin
         * @throws ReadDriverException
1168
         */
1169
        private Point2D transformPoint(Point2D pReal) throws LoadLayerException {
1170
                AffineTransform at = getDataStore().getAffineTransform();
1171
                Point2D px = new Point2D.Double();
1172
                //px = new Point2D.Double(pReal.getX(), pReal.getY());
1173
                try {
1174
                        at.inverseTransform(pReal, px);
1175
                        return px;
1176
                } catch (NoninvertibleTransformException e) {
1177
                        throw new LoadLayerException("Error en la transformaci?n del punto", e);
1178
                }
1179
        }
1180 4181 fdiaz
1181 2443 nbrodin
        public Object getInfo(String key) {
1182
                if (key.equals("DriverName"))
1183
                        return "gvSIG Raster Driver";
1184
                return null;
1185
        }
1186
1187
        public int[] getBandCountFromDataset() {
1188
                return getDataStore().getBandCountByProvider();
1189
        }
1190
1191
        public String getColorInterpretation(int band, int dataset) {
1192
                if (this.getDataStore().getColorInterpretation().get(band) == null)
1193
                        return "Undefined";
1194
                return this.getDataStore().getColorInterpretation().get(band);
1195
        }
1196
1197
        public String getWktProjection() throws RasterDriverException {
1198
                return getDataStore().getWktProjection();
1199
        }
1200
1201
        public boolean isRGB() {
1202
                if ((getDataStore() == null) || (render == null))
1203
                        return false;
1204
1205
                if (getDataStore().getDataType()[0] != Buffer.TYPE_BYTE)
1206
                        return false;
1207
1208
                boolean R = false;
1209
                boolean G = false;
1210
                boolean B = false;
1211
1212
                int[] renderBands = render.getRenderColorInterpretation().buildRenderBands();
1213
                for (int i = 0; i < renderBands.length; i++)
1214
                        if (renderBands[i] >= 0)
1215
                                switch (i) {
1216
                                        case 0:
1217
                                                R = true;
1218
                                                break;
1219
                                        case 1:
1220
                                                G = true;
1221
                                                break;
1222
                                        case 2:
1223
                                                B = true;
1224
                                                break;
1225
                                }
1226
1227
                if (R && G && B)
1228
                        return true;
1229
1230
                return false;
1231
        }
1232
1233
        /**
1234
         * Obtiene el tama?o de celda de la fuente de datos
1235
         * @return double con el tama?o de celda
1236
         */
1237
        public double getCellSize() {
1238
                return (getDataStore() != null) ? getDataStore().getCellSize() : 1;
1239
        }
1240
1241
        public Extent getFullRasterExtent() {
1242
                return this.getDataStore().getExtent();
1243
        }
1244
1245
1246
        /**
1247
         * Devuelve el fichero asociado a la capa o null si no tiene.
1248
         * @return Fichero.
1249
         */
1250
        public File getFile() {
1251
                if(getDataStore().getParameters() instanceof RasterFileStoreParameters)
1252
                        return ((RasterFileStoreParameters)getDataStore().getParameters()).getFile();
1253
                return new File("");
1254
        }
1255
1256
        /**
1257
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1258
         * @param file Fichero a consultar
1259
         * @return true si es aceptado y false si no lo es.
1260
         */
1261
        public boolean isFileAccepted(File file) {
1262
                return getDataStore().isFileSupported(file.getName());
1263
        }
1264 4181 fdiaz
1265 2443 nbrodin
        /**
1266
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1267
         * @param file Fichero a consultar
1268
         * @return true si es aceptado y false si no lo es.
1269
         */
1270
        public static boolean isFileSupported(File file) {
1271
                return RasterLocator.getManager().getProviderServices().isExtensionSupported(file.getName());
1272
        }
1273
1274
        public boolean existColorTable() {
1275
                return getRender().existColorTable();
1276
        }
1277
1278
        /**
1279
         * Returns true if the data store has an alpha band
1280
         */
1281
        public boolean existsAlphaBand() {
1282
                if(getDataStore().getColorInterpretation() != null)
1283
                        return getDataStore().getColorInterpretation().hasAlphaBand();
1284
                else
1285
                        return false;
1286
        }
1287
1288
        public int getAlphaBandNumber() {
1289
                if(getDataStore().getColorInterpretation() != null)
1290
                        return getDataStore().getColorInterpretation().getBand(ColorInterpretation.ALPHA_BAND);
1291
                return -1;
1292
        }
1293
1294
        /**
1295
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1296
         * capa busque una leyenda valida.
1297
         * @param ct
1298
         */
1299
        public void setLastLegend(ColorTable ct) {
1300
                lastLegend = ColorTableLegend.createLegend(ct);
1301
        }
1302
1303
        /**
1304
         * Devuelve la Leyenda de la capa.
1305
         * @return Leyenda.
1306
         */
1307
        public ILegend getLegend() {
1308
                if (lastLegend != null)
1309
                        return lastLegend;
1310
1311
                return null;
1312
        }
1313
1314
        public void addLegendListener(LegendListener listener) {
1315 3191 jbadia
                if(layerChangeSupport != null){
1316
                        layerChangeSupport.addLayerListener(listener);
1317
                }
1318 2443 nbrodin
        }
1319
1320
        public int getShapeType() {
1321
                return TYPES.SURFACE;
1322
        }
1323
1324
        public void removeLegendListener(LegendListener listener) {
1325
                if(layerChangeSupport != null)
1326
                        layerChangeSupport.removeLayerListener(listener);
1327
        }
1328
1329
        public boolean isInside(Point2D p) {
1330
                 return getDataStore().isInside(p);
1331
        }
1332
1333
        public AffineTransform getAffineTransform() {
1334 5462 llmarques
1335
            AffineTransform storeTransformation = this.getDataStore().getAffineTransform();
1336
1337
            // If layer is projected on the fly transform affine transform
1338
                if(this.getCoordTrans() != null){
1339
                    Envelope fullEnvelope = this.getFullEnvelope();
1340
1341
            double newCellSizeX =
1342
                (fullEnvelope.getMaximum(0) - fullEnvelope.getMinimum(0))
1343
                    / getDataStore().getWidth();
1344
            double newCellSizeY =
1345
                (fullEnvelope.getMaximum(1) - fullEnvelope.getMinimum(1))
1346
                    / getDataStore().getHeight();
1347
1348
            AffineTransform layerTransformation =
1349
                new AffineTransform(newCellSizeX, storeTransformation.getShearY(),
1350
                    storeTransformation.getShearX(), -newCellSizeY, fullEnvelope.getMinimum(0),
1351
                    fullEnvelope.getMaximum(1));
1352
            return layerTransformation;
1353
                }
1354
1355
                return storeTransformation;
1356 2443 nbrodin
        }
1357
1358
        public void setAffineTransform(AffineTransform transf) {
1359
                if(transf == null)
1360
                        return;
1361
                affineTransformList.add(transf);
1362
                getDataStore().setAffineTransform(transf);
1363
                updateDrawVersion();
1364
        }
1365
1366
        public void setAffineTransformWithoutHistorical(AffineTransform transf) {
1367
                getDataStore().setAffineTransform(transf);
1368
                updateDrawVersion();
1369
        }
1370
1371
        public Historical getAffineTransformHistorical() {
1372
                return this.affineTransformList;
1373
        }
1374
1375
        public void saveGeoToRmf() throws RmfSerializerException {
1376
                if (!isOpen())
1377
                        return;
1378
1379
                getDataStore().saveGeoreferencingToRmf();
1380 4181 fdiaz
1381 2443 nbrodin
                affineTransformList.clear();
1382
                affineTransformList.add(this.getAffineTransform());
1383
        }
1384
1385
        public boolean isActionEnabled(int action) {
1386
                switch (action) {
1387
                        case IRasterLayerActions.BANDS_FILE_LIST:
1388
                                if (existColorTable() || getDataStore().isMosaic())
1389
                                        return false;
1390
                                break;
1391
                        case IRasterLayerActions.BANDS_RGB:
1392
                                if (existColorTable())
1393
                                        return false;
1394
                                break;
1395
                        case IRasterLayerActions.REPROJECT:
1396
                                if (!isReproyectable())
1397
                                        return false;
1398
                                break;
1399
                        case IRasterLayerActions.CREATEOVERVIEWS:
1400
                                return overviewsSupport();
1401
                        case IRasterLayerActions.OPACITY:
1402
                        case IRasterLayerActions.TRANSPARENCY:
1403
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1404
                        case IRasterLayerActions.ENHANCED:
1405
                        case IRasterLayerActions.PANSHARPENING:
1406
                        case IRasterLayerActions.SELECT_LAYER:
1407
                        case IRasterLayerActions.SAVE_COLORINTERP:
1408
                                return true;
1409
                        case IRasterLayerActions.REMOTE_ACTIONS:
1410
                                return false;
1411
                        case IRasterLayerActions.TAILTRIM:
1412
                        case IRasterLayerActions.GEOLOCATION:
1413 3191 jbadia
                                if(getDataStore() == null){
1414
                                        return false;
1415
                                }
1416 2443 nbrodin
                                return !(getDataStore().isTiled());
1417
                }
1418
                return true;
1419
        }
1420
1421
        public void setVisible(boolean visibility) {
1422 3191 jbadia
                        if((state != null) && visibility)
1423
                                state.disableStopped();
1424
                        else
1425
                                enableStopped();
1426 4181 fdiaz
1427 3191 jbadia
                        if(isAwake() || isClosed())
1428
                                try {
1429
                                        this.load();
1430
                                } catch (LoadLayerException e) {
1431
                                        e.printStackTrace();
1432
                                }
1433 4181 fdiaz
1434 3191 jbadia
                        /*
1435
                         * Cuando se modifica la visibilidad de una capa raster se hace un updateDrawVersion de todas las
1436
                         * capas raster de ese MapContext. Esto es porque la estrategia utilizada por RasterDrawStrategy hace
1437
                         * que se cacheen en blanco las capas raster que est?n ocultas debajo de otras. Al hacer invisibles las
1438
                         * de arriba la cache que estaba en blanco hace que no se pinte nada. Para evitar esto las marcamos todas
1439
                         * como que han sido modificadas para que se vuelvan a leer.
1440
                         */
1441
                        if(getMapContext() != null) {
1442
                                ArrayList<FLayer> listLayers = new ArrayList<FLayer>();
1443
                                listLayers = RasterDrawStrategy.getLayerList(getMapContext().getLayers(), listLayers);
1444
                                for (int i = 0; i < listLayers.size(); i++)
1445
                                        if(listLayers.get(i) instanceof DefaultFLyrRaster)
1446
                                                ((DefaultFLyrRaster)listLayers.get(i)).updateDrawVersion();
1447 2443 nbrodin
                        }
1448 4181 fdiaz
1449 3191 jbadia
                        super.setVisible(visibility);
1450 2443 nbrodin
        }
1451
1452
        /**
1453
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1454
         * @return valor de transparencia
1455
         */
1456
        public int getTransparency() {
1457
                try {
1458
                        return getRender().getRenderingTransparency().getOpacity();
1459
                } catch (NullPointerException e) {
1460
                        return super.getTransparency();
1461
                }
1462
        }
1463
1464
        /**
1465
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1466
         * o no.
1467
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1468
         */
1469
        public boolean isTransparent() {
1470
                return getRender().getRenderingTransparency().isTransparencyActive();
1471
        }
1472
1473
        /**
1474
         * Asigna la transparencia de la siguiente renderizaci?n
1475
         * @param valor de transparencia
1476
         */
1477
        public void setTransparency(int trans) {
1478
                super.setTransparency(trans);
1479
                try {
1480
                        getRender().getRenderingTransparency().setOpacity(trans);
1481
                } catch (NullPointerException e) {
1482
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1483
                }
1484
        }
1485
1486
        public List<ROI> getRois() throws ROIException {
1487
                return getDataStore().getRois(getMapContext().getProjection());
1488
        }
1489
1490
        public void setRois(List<ROI> rois) {
1491
                getDataStore().setRois(rois);
1492
        }
1493 4181 fdiaz
1494 2443 nbrodin
        public void setROIsFiles(List<File> file) throws RmfSerializerException {
1495
                getDataStore().saveROIFileListToRmf(file);
1496
        }
1497 4181 fdiaz
1498 2443 nbrodin
        public List<File> getROIsFiles() throws RmfSerializerException {
1499
                return getDataStore().getROIFileListFromRmf();
1500
        }
1501
1502
        /**
1503
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1504
         * devolver? null.
1505
         * @return TreeMap con la lista de capas a dibujar
1506
         */
1507
        public HashMap<DefaultFLyrRaster, Boolean> getRasterStrategy() {
1508
                if(strategy != null)
1509
                        return strategy.getStrategy();
1510
                return null;
1511
        }
1512
1513
        /**
1514
         * @return the configuration
1515
         */
1516
        static public IConfiguration getConfiguration() {
1517
                return configuration;
1518
        }
1519
1520
        /**
1521
         * @param configuration the configuration to set
1522
         */
1523
        static public void setConfiguration(IConfiguration configuration) {
1524
                DefaultFLyrRaster.configuration = configuration;
1525
        }
1526
1527
        public void reload() throws ReloadLayerException {
1528
                try {
1529
                        super.reload();
1530
                        load();
1531
                        if (isStopped())
1532
                                disableStopped();
1533
                        if (getMapContext() != null)
1534
                                getMapContext().invalidate();
1535
                } catch (LoadLayerException e) {
1536
                        setAvailable(false);
1537
                        throw new ReloadLayerException(getName(), e);
1538
                }
1539
        }
1540
1541
        /**
1542
         * Devuelve si la capa tiene soporte para poder generar overviews
1543
         * @return
1544
         */
1545
        public boolean overviewsSupport() {
1546
                if ((getDataStore() != null) && (getDataStore().overviewsSupport()))
1547
                        return true;
1548
1549
                return false;
1550
        }
1551
1552
        /**
1553
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1554
         * en escala de grises
1555
         * @return
1556
         */
1557
        public boolean isRenderingAsGray() {
1558
                int[] renderBands = getRender().getRenderColorInterpretation().buildRenderBands();
1559
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1560
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1561
                        return true;
1562
                return false;
1563
        }
1564
1565
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1566
                updateDrawVersion();
1567
        }
1568
1569
        public Point2D adjustWorldRequest(Point2D req) {
1570
                Envelope ext = null;
1571
1572
                ext = getFullEnvelope();
1573
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
1574
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
1575
                return req;
1576
        }
1577
1578
        public FLayer cloneLayer() throws Exception {
1579
                RasterDataStore  ds = getDataStore().cloneDataStore();
1580
                DefaultFLyrRaster newLayer = new DefaultFLyrRaster();
1581
                newLayer.setName(getName());
1582
                newLayer.setOpenRasterStore(ds);
1583
                newLayer.firstLoad = firstLoad;
1584 4181 fdiaz
1585 2443 nbrodin
                List<RasterFilter> filters = getRender().getFilterList().getStatusCloned();
1586
1587
                //Hacemos una copia de las bandas a renderizar
1588
                if(getRender().getRenderColorInterpretation() != null) {
1589
                        newLayer.getRender().setRenderColorInterpretation(getRender().getRenderColorInterpretation().cloneColorInterpretation());
1590
                }
1591
1592
                //Asignamos el entorno
1593
                if(newLayer.getRender().getFilterList() == null)
1594
                        newLayer.getRender().setFilterList(RasterLocator.getManager().createEmptyFilterList(getRender().getFilterList().getInitDataType()));
1595
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
1596
                newLayer.getRender().getFilterList().setStatus(filters);
1597
1598
                // Asignamos los valores noData del original
1599
                newLayer.setNoDataValue(getNoDataValue());
1600
                if(getDataStore().getNoDataValue().isDefined())
1601
                        newLayer.setNoDataTransparent(true);
1602
                newLayer.enableOpen();
1603 4181 fdiaz
1604 2443 nbrodin
                return newLayer;
1605
        }
1606 4181 fdiaz
1607 2443 nbrodin
        public FLayer getFileLayer() throws RasterDriverException {
1608
                try {
1609
                        return cloneLayer();
1610
                } catch (Exception e) {
1611
                }
1612
                return null;
1613
        }
1614 4181 fdiaz
1615
        public void addFile(File file) throws InvalidSourceException {
1616 2443 nbrodin
                getDataStore().addFile(file);
1617
        }
1618 4181 fdiaz
1619
        public void removeFile(File file) {
1620 2443 nbrodin
                getDataStore().removeFile(file);
1621
        }
1622
1623
        /*****************************************************/
1624
1625
        public void disableStopped() {
1626
                if(state != null)
1627
                        state.disableStopped();
1628
        }
1629
1630 5136 fdiaz
        public void enableAwake() throws NotAvailableStateException {
1631
        if(state != null) {
1632
            state.enableAwake();
1633
        }
1634
        }
1635 2443 nbrodin
1636
        public void enableClosed() throws NotAvailableStateException {
1637
                if(state != null)
1638
                        state.enableClosed();
1639
        }
1640
1641 3191 jbadia
        public void enableOpen() throws NotAvailableStateException {
1642
                if(state != null){
1643
                        state.enableOpen();
1644
                }
1645
        }
1646 2443 nbrodin
1647 3191 jbadia
        public void enableStopped() {
1648
                if(state != null) {
1649
                        state.enableStopped();
1650
                }
1651
        }
1652 2443 nbrodin
1653 3191 jbadia
        public boolean isAwake() {
1654
                return (state != null) && state.isAwake();
1655
        }
1656 2443 nbrodin
1657 3191 jbadia
        public boolean isClosed() {
1658
                return (state != null) && state.isClosed();
1659
        }
1660 2443 nbrodin
1661 3191 jbadia
        public boolean isOpen() {
1662
                return (state != null) && state.isOpen();
1663
        }
1664 2443 nbrodin
1665 3191 jbadia
        public boolean isStopped() {
1666
                return (state != null) && (state.isStopped());
1667
        }
1668 2443 nbrodin
1669
1670
        @SuppressWarnings("rawtypes")
1671
        public Set getMetadataChildren() {
1672
                return null;
1673
        }
1674
1675
        public Object getMetadataID() {
1676
                return getName();
1677
        }
1678
1679
        public String getMetadataName() {
1680
                return null;
1681
        }
1682
1683
        public RasterDataStore getDataStore() {
1684
                return this.dataStore;
1685
        }
1686 4181 fdiaz
1687 2443 nbrodin
        public IProjection getProjection() {
1688
                return getDataStore().getProjection();
1689
        }
1690
1691
        public void setOpenRasterStore(DataStore dataStore) throws LoadLayerException {
1692
                if(dataStore instanceof CoverageStoreProviderServices) {
1693
                        try {
1694
                                this.dataStore = rManager.getProviderServices().open(
1695 4181 fdiaz
                                                ((CoverageStoreProviderServices) dataStore).getProvider(),
1696 2443 nbrodin
                                                dataStore.getParameters());
1697
                        } catch (NotSupportedExtensionException e) {
1698
                                throw new LoadLayerException("Extension not supported", e);
1699
                        } catch (RasterDriverException e) {
1700
                                throw new LoadLayerException("Error opening the DataStore", e);
1701
                        }
1702
                } else
1703
                        this.dataStore = (RasterDataStore) dataStore;
1704
                try {
1705
                        enableAwake();
1706
                } catch (NotAvailableStateException e) {
1707
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
1708
                }
1709
                if(getDataStore().getProjection() != null) {
1710
                        try {
1711
                                getDataStore().setProjection(getDataStore().getProjection(), false);
1712
                                super.setProjection(getDataStore().getProjection());
1713
                        } catch (RmfSerializerException e) {
1714
                                //persist is false
1715
                        }
1716
                }
1717
        }
1718 4181 fdiaz
1719 2443 nbrodin
        public void setDataStore(DataStore dataStore) throws LoadLayerException {
1720
                setOpenRasterStore(dataStore);
1721
                load();
1722
        }
1723 4181 fdiaz
1724 2443 nbrodin
        public boolean isRemote() {
1725
                return false;
1726
        }
1727 4181 fdiaz
1728 2443 nbrodin
        /**
1729
         * Returns true if exists a process reading data from this layer
1730
         * @return
1731
         */
1732
        public boolean isReadingData() {
1733
                return readingData != null;
1734
        }
1735
1736
        /**
1737
         * When a process is using information of this layer this variable will contain
1738
         * the thread ID.
1739
         * @param readingData
1740
         */
1741
        public synchronized void setReadingData(String readingData) {
1742
                this.readingData = readingData;
1743
        }
1744 4181 fdiaz
1745 2443 nbrodin
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel,
1746
                        boolean fast)
1747
                        throws LoadLayerException, DataException {
1748
                return null;
1749
        }
1750
1751
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel)
1752
                        throws LoadLayerException, DataException {
1753
                return null;
1754
        }
1755
1756
        @Override
1757
        protected void doDispose() throws BaseException {
1758
                if(render != null)
1759
                        render.dispose();
1760
                if(getDataStore() != null)
1761
                        getDataStore().dispose();
1762
                finalize();
1763
        }
1764
1765
        public int getZoomLevel() {
1766
                return zoomLevel;
1767
        }
1768
1769
        public void setZoomLevel(int zoomLevel) {
1770
                this.zoomLevel = zoomLevel;
1771
        }
1772 4181 fdiaz
1773 2443 nbrodin
        public boolean increaseZoomLevel() {
1774 4181 fdiaz
                if(zoomLevel < (this.getDataStore().getZoomLevels() - 1)) {
1775 2443 nbrodin
                        zoomLevel ++;
1776
                        recalcLevel = false;
1777
                        return true;
1778
                }
1779
                return false;
1780
        }
1781 4181 fdiaz
1782 2443 nbrodin
        public boolean decreaseZoomLevel() {
1783 4181 fdiaz
                if(zoomLevel > 0) {
1784 2443 nbrodin
                        zoomLevel --;
1785
                        recalcLevel = false;
1786
                        return true;
1787
                }
1788
                return false;
1789
        }
1790 4181 fdiaz
1791 2443 nbrodin
        public Envelope getCoordsInLevel(Point2D center, int level, int w, int h) throws CreateEnvelopeException {
1792
                Extent ex = getDataStore().getCoordsInLevel(center, level, w, h);
1793
                return geomManager.createEnvelope(ex.getULX(), ex.getULY(), ex.getLRX(), ex.getLRY(), SUBTYPES.GEOM2D);
1794
        }
1795 4181 fdiaz
1796 2443 nbrodin
        public boolean isEnabledMultiresolution() {
1797
                return getDataStore().isTiled();
1798
        }
1799 4181 fdiaz
1800 2443 nbrodin
        public void setTileServer(Class<?> tileServer) throws InitializeException {
1801
                getDataStore().setTileServer(tileServer);
1802
        }
1803 4181 fdiaz
1804 2443 nbrodin
        @Override
1805
        public void loadFromState(PersistentState state)
1806
                        throws PersistenceException {
1807
                try {
1808
                        super.loadFromState(state);
1809
                        this.dataStore = (RasterDataStore)state.get("rasterdatastore");
1810
                } catch (PersistenceRuntimeException e) {
1811
                        logger.debug("Unable to load store from persistence in layer: " + this.getName(), e);
1812
                        this.setAvailable(false);
1813
                        return;
1814
                }
1815
                this.lastLegend = (ILegend)state.get("legend");
1816
                this.colorTableLoadedFromProject = (ColorTable)state.get("colortable");
1817 4172 jbadia
                if(state.get("recalcLevel") != null){
1818
                        this.recalcLevel = state.getBoolean("recalcLevel");
1819
                }
1820
                if(state.get("zoomLevel") != null){
1821
                        this.zoomLevel = state.getInt("zoomLevel");
1822
                }
1823 2443 nbrodin
                loadedFromProject = true;
1824
        }
1825
1826
        @Override
1827
        public void saveToState(PersistentState state) throws PersistenceException {
1828
                super.saveToState(state);
1829 4181 fdiaz
1830
                state.set("rasterdatastore", getDataStore());
1831
                state.set("legend", lastLegend);
1832
                state.set("colortable", getRender().getColorTable());
1833
                state.set("zoomLevel", zoomLevel);
1834
                state.set("recalcLevel", recalcLevel);
1835
        }
1836
1837 2443 nbrodin
        public static void registerPersistence() {
1838
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
1839
                DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
1840
                if( definition == null ) {
1841
                        definition = manager.addDefinition(
1842
                                        DefaultFLyrRaster.class,
1843
                                        PERSISTENT_NAME,
1844
                                        PERSISTENT_DESCRIPTION,
1845 4181 fdiaz
                                        null,
1846 2443 nbrodin
                                        null
1847
                        );
1848
                        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE, "FLyrDefault");
1849 4181 fdiaz
1850 2443 nbrodin
                        registerPersistence(definition);
1851
                }
1852
        }
1853 4181 fdiaz
1854 2443 nbrodin
        public static void registerPersistence(DynStruct definition) {
1855
                definition.addDynFieldObject("rasterdatastore").setClassOfValue(RasterDataStore.class).setMandatory(false);
1856
                definition.addDynFieldObject("legend").setClassOfValue(ILegend.class).setMandatory(false);
1857
                definition.addDynFieldObject("colortable").setClassOfValue(ColorTable.class).setMandatory(false);
1858 4172 jbadia
                definition.addDynFieldInt("zoomLevel").setMandatory(false);
1859 2443 nbrodin
                definition.addDynFieldBoolean("recalcLevel").setMandatory(false);
1860
        }
1861
1862
        public GeometryType getGeometryType() throws ReadException {
1863
                try {
1864
                        return GeometryLocator.getGeometryManager().getGeometryType(TYPES.SURFACE, SUBTYPES.GEOM2D);
1865
                } catch (GeometryTypeNotSupportedException e) {
1866
                        throw new ReadException(getDataStore().getName(), e);
1867
                } catch (GeometryTypeNotValidException e) {
1868
                        throw new ReadException(getDataStore().getName(), e);
1869 4181 fdiaz
                }
1870 2443 nbrodin
        }
1871 4181 fdiaz
1872 2443 nbrodin
        public void setDataStore(DataStore dataStore, String domain) throws LoadLayerException {
1873
                setDataStore(dataStore);
1874
        }
1875 4181 fdiaz
1876 2443 nbrodin
        protected void finalize() {
1877
                layerChangeSupport             = null;
1878
                state                          = null;
1879
                lastLegend                     = null;
1880
                colorTableLoadedFromProject    = null;
1881
                strategy                       = null;
1882
                configuration                  = null;
1883
                fileUtil                       = null;
1884
                rasterUtil                     = null;
1885
                crsUtil                        = null;
1886
                mathUtil                       = null;
1887
                uri                            = null;
1888
                affineTransformList            = null;
1889
                readingData                    = null;
1890
                dataStore                      = null;
1891
                render                         = null;
1892
        }
1893
1894
}