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

History | View | Annotate | Download (75.1 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
* 
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
* 
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
* 
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
19
* MA  02110-1301, USA.
20
* 
21
*/
22
package org.gvsig.raster.fmap.layers;
23

    
24
import java.awt.Dimension;
25
import java.awt.Graphics2D;
26
import java.awt.Point;
27
import java.awt.Rectangle;
28
import java.awt.geom.AffineTransform;
29
import java.awt.geom.NoninvertibleTransformException;
30
import java.awt.geom.Point2D;
31
import java.awt.geom.Rectangle2D;
32
import java.awt.image.BufferedImage;
33
import java.io.File;
34
import java.io.IOException;
35
import java.util.ArrayList;
36
import java.util.HashMap;
37
import java.util.List;
38
import java.util.Set;
39

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

    
138
/**
139
 * Raster layer
140
 * 
141
 * @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
        public static final String      PERSISTENT_NAME                = "FLyrRasterSE_Persistent";
147
    public static final String      PERSISTENT_DESCRIPTION         = "FLyrRasterSE Persistent";
148
    private RasterManager           rManager                       = RasterLocator.getManager();
149
        private boolean                 mustTileDraw                   = false;
150
        private boolean                 mustTilePrint                  = true;
151
        private int                     maxTileDrawWidth               = 200;
152
        private int                     maxTileDrawHeight              = 200;
153
        private int                     maxTilePrintWidth              = 1500;
154
        private int                     maxTilePrintHeight             = 1500;
155
        private boolean                 firstLoad                      = false;
156
        private boolean                 removeRasterFlag               = true;
157
        protected RasterDataStore       dataStore                      = null;
158
        protected Render                render                         = null;
159
        private int                     posX                           = 0;
160
        private int                     posY                           = 0;
161
        private double                  posXWC                         = 0;
162
        private int                     posYWC                         = 0;
163
        private int                     r                              = 0;
164
        private int                     g                              = 0;
165
        private int                     b                              = 0;
166
        private LayerChangeSupport      layerChangeSupport             = new LayerChangeSupport();
167
        private FLyrState               state                          = new FLyrState();
168
        protected ILegend               lastLegend                     = null;
169
        protected ColorTable            colorTableLoadedFromProject    = null;
170
        protected boolean               loadedFromProject              = false;
171
        private ArrayList<ROI>          rois                           = null;
172
        private RasterDrawStrategy      strategy                       = null;
173
        static private IConfiguration   configuration                  = new DefaultLayerConfiguration();
174
        protected int                   zoomLevel                      =  1;
175
        public boolean                  recalcLevel                    = true;
176
        
177
        private BufferedImage           image                          = null;
178
        private static GeometryManager  geomManager                          = GeometryLocator.getGeometryManager();
179
        private static final Logger     logger                         = LoggerFactory.getLogger(DefaultFLyrRaster.class);
180
        protected FileUtils             fileUtil                       = RasterLocator.getManager().getFileUtils();
181
        protected RasterUtils           rasterUtil                     = RasterLocator.getManager().getRasterUtils();
182
        protected CRSUtils              crsUtil                        = RasterLocator.getManager().getCRSUtils();
183
        protected MathUtils             mathUtil                       = RasterLocator.getManager().getMathUtils();
184
        private String                  uri                            = null;
185
        //private boolean                 noDataTransparent              = true;
186

    
187
        /**
188
         * Lista de transformaciones afines que son aplicadas. Esta lista es
189
         * simplemente un historico que no se utiliza. Es posible utilizarlo para
190
         * recuperar transformaciones anteriores.
191
         */
192
        private Historical              affineTransformList    = null;
193
        protected String                readingData            = null;
194
        //It is set to true if the method init has been called at least once
195
        protected boolean               layerInitialize        = false;
196

    
197
        public DefaultFLyrRaster() {
198
                affineTransformList = rManager.createHistoricalService();
199
        }
200
        
201
        public static void registerDynClass() {
202
                DynObjectManager manager = ToolsLocator.getDynObjectManager();
203
            DynClass dynClass = manager.add("RasterInfo", "Raster layer Info by point");
204
            dynClass.setNamespace("InfoByPoint");
205
            dynClass.addDynFieldString("File");
206
            dynClass.addDynFieldString("View Point");
207
            dynClass.addDynFieldString("Pixel Point");
208
            dynClass.addDynFieldString("RGB");
209
            dynClass.addDynFieldString("CMYK");
210
            dynClass.addDynFieldString("HSL");
211
            dynClass.addDynFieldString("Band Value");
212
            dynClass.addDynFieldString("World Point");
213
        }
214
        
215
        /**
216
         * Builds a new raster layer
217
         * @param fileName
218
         * @return
219
         * @throws RasterNotLoadException 
220
         * @throws LoadLayerException 
221
         */
222
        public static DefaultFLyrRaster createLayer(String layerName, File file) throws LoadLayerException {
223
                ProviderServices provServ = RasterLocator.getManager().getProviderServices();
224
                RasterDataParameters storeParameters = provServ.createParameters(file.getName());
225
                storeParameters.setURI(file.getPath());
226
                
227
                DataManager dataManager = DALLocator.getDataManager();
228
                DataStore dataStore = null;
229
                try {
230
                        dataStore = dataManager.createStore(storeParameters);
231
                } catch (ValidateDataParametersException e) {
232
                        throw new LoadLayerException("Error al cargar la capa.");
233
                } catch (InitializeException e) {
234
                        throw new LoadLayerException("Error al cargar la capa.");
235
                } catch (ProviderNotRegisteredException e) {
236
                        throw new LoadLayerException("Error al cargar la capa.");
237
                }
238
                
239
                DefaultFLyrRaster lyr = new DefaultFLyrRaster();
240
                lyr.setName(layerName);
241
                lyr.setDataStore(dataStore);
242
                return lyr;
243
        }
244

    
245
        /*
246
         * (non-Javadoc)
247
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setName(java.lang.String)
248
         */
249
        public void setName(String name) {
250
                super.setName(name);
251

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

    
262
        /*
263
         * (non-Javadoc)
264
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#wakeUp()
265
         */
266
        public void wakeUp(){
267
                try {
268
                        reload();
269
                } catch (ReloadLayerException e) {
270
                        // No se ha podido recuperar la capa con exito
271
                }
272
        }
273

    
274
        /*
275
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
276
         */
277
        public void load() throws LoadLayerException {
278
                if (isStopped() || getDataStore() == null)
279
                        return;
280

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

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

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

    
305
                try {
306
                        if(!dataStore.isOpen())
307
                                dataStore = rManager.open(params);
308
                } catch (NotSupportedExtensionException e) {
309
                        throw new LoadLayerException(this.getName());
310
                } catch (RasterDriverException e) {
311
                        throw new LoadLayerException(this.getName());
312
                }
313
                
314
                /*if (dataStore != null)
315
                        try {
316
                                this.init();
317
                        } catch (FilePaletteException e) {
318
                                throw new LoadLayerException("", e);
319
                        }*/
320
        }
321

    
322
        /**
323
         * Acciones de inicializaci?n despu?s de que la fuente de datos
324
         * de la capa est? asignada. El tipo de fuente de datos es variable
325
         * puede ser MultiRasterDataset, CompositeDataset u otras que existan e
326
         * implementen IRasterDatasource.
327
         * @throws FilePaletteException 
328
         */
329
        public void init() throws LoadLayerException, FilePaletteException {
330
                layerInitialize = true;
331
                
332
                if (dataStore == null)
333
                        throw new LoadLayerException("Formato no valido", new IOException());
334

    
335
                render = dataStore.getRender();
336
                render.addVisualPropertyListener(this);
337
                initFilters();
338

    
339
                //Inicializaci?n del historico de transformaciones
340
                affineTransformList.clear();
341
                affineTransformList.add(this.getAffineTransform());
342

    
343
                try {
344
                        if(!isOpen())
345
                                enableOpen();
346
                } catch (NotAvailableStateException e) {
347
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Awake=" + isAwake(), e);
348
                }
349
        }
350

    
351
        /*
352
         * (non-Javadoc)
353
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#readProjection()
354
         */
355
        public IProjection readProjection() throws RasterDriverException {
356
                try {
357
                        crsUtil.setCRSFactory(CRSFactory.cp);
358
                        if( dataStore == null )
359
                                return null;
360
                        return crsUtil.convertWktToIProjection(dataStore.getWktProjection());
361
                } catch (Exception e) {
362
                        throw new RasterDriverException("Problems converting from WKT to IProjection", e);
363
                } catch (Error e) {
364
                        e.printStackTrace();
365
                        return null;
366
                }
367
        }
368

    
369
        /**
370
         * Crea el objeto renderizador de raster
371
         * @return Rendering
372
         */
373
        public Render getRender() {
374
                if (render == null) {
375
                        render = dataStore.getRender();
376
                        render.addVisualPropertyListener(this);
377
                }
378
                return render;
379
        }
380
        
381
        /*
382
         * (non-Javadoc)
383
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getURI()
384
         */
385
        public String getURI() {
386
                return uri;
387
        }
388

    
389
        /*
390
         * (non-Javadoc)
391
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setNoDataTransparent(boolean)
392
         */
393
        public void setNoDataTransparent(boolean t) {
394
                if(dataStore.getNoDataValue().isDefined()) {
395
                        dataStore.getTransparency().setNoData(dataStore.getNoDataValue());
396
                }
397
                dataStore.getTransparency().activeNoData(t);
398
                dataStore.getTransparency().activeTransparency();
399
        }
400

    
401
        /**
402
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
403
         * @throws FilePaletteException 
404
         */
405
        protected void initFilters() throws FilePaletteException {
406
                if(getDataType() == null)
407
                        return;
408
                        
409
                RasterFilterList filterList = rManager.createEmptyFilterList(getDataType()[0]);
410
                if(loadedFromProject) {
411
                        filterList = getDataStore().getRender().getFilterList();
412
                }
413
                filterList.addEnvParam("IStatistics", dataStore.getStatistics());
414
                filterList.addEnvParam("MultiRasterDataset", dataStore);
415

    
416
                if(dataStore == null)
417
                        return;
418
                
419
                if(dataStore.getNoDataValue() != null) {
420
                        dataStore.getNoDataValue().load();
421
                        if(dataStore.getNoDataValue().isDefined())
422
                                setNoDataTransparent(true);
423
                }
424

    
425
                filterList.setInitDataType(getDataType()[0]);
426

    
427
                // Quitamos la leyenda
428
                lastLegend = null;
429

    
430
                try {
431
                        //Si en la carga del proyecto se carg? una tabla de color asignamos esta
432
                        if(colorTableLoadedFromProject != null) {
433
                                setLastLegend(colorTableLoadedFromProject);
434
                                RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
435
                                Params params = filterList.createEmptyFilterParams();
436
                                params.setParam("colorTable", colorTableLoadedFromProject);
437
                                colorTableManager.addFilter(params);
438
                        } else
439
                                //sino ponemos la tabla asociada al raster
440
                                if (dataStore.getColorTable() != null) {
441
                                        ColorTable table = dataStore.getColorTable();
442
                                        setLastLegend(table);
443
                                        RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
444
                                        Params params = filterList.createEmptyFilterParams();
445
                                        params.setParam("colorTable", table);
446
                                        colorTableManager.addFilter(params);
447
                                } else //sino hace lo que dice en las preferencias
448
                                        if(dataStore.needEnhanced() || 
449
                                                        (loadedFromProject && filterList.get("enhanced_stretch") != null)) 
450
                                                loadEnhancedOrColorTable(filterList);
451
                        colorTableLoadedFromProject = null;
452

    
453
                        getRender().setFilterList(filterList);
454
                        // Inicializo la transparencia para el render
455
                        if(!loadedFromProject) {
456
                                getRender().setLastTransparency(dataStore.getTransparency().cloneTransparency());
457
                        }
458
                        loadedFromProject = false;
459
                } catch (FilterTypeException e) {
460
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
461
                        logger.error("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
462
                } catch (FilterManagerException e) {
463
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
464
                        logger.error("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
465
                }
466
        }
467

    
468
        /**
469
         * Mira la configuracion para saber si debe cargar un realce o una tabla
470
         * de color por defecto
471
         * @param filterManager
472
         * @throws FilterTypeException
473
         * @throws FilePaletteException 
474
         */
475
        private void loadEnhancedOrColorTable(RasterFilterList filterList) throws FilterTypeException, FilterManagerException, FilePaletteException {
476
                String colorTableName = configuration.getValueString("loadlayer_usecolortable", (String) null);
477

    
478
                String palettesPath = System.getProperty("user.home") +
479
                File.separator +
480
                "gvSIG" + // PluginServices.getArguments()[0] +
481
                File.separator + "colortable";
482

    
483
                Statistics stats = dataStore.getStatistics();
484
                ColorTableLibrary colorTableLibrary = rManager.getDataStructFactory().getColorTableLibrary();
485

    
486
                if (colorTableName != null)
487
                        try {
488
                                stats.calculate(RasterLibrary.statisticsScale);
489
                                if (getDataStore().getBandCount() == 1) {
490
                                        ArrayList<String> fileList = colorTableLibrary.getPaletteFileList(palettesPath);
491
                                        for (int i = 0; i < fileList.size(); i++) {
492
                                                ArrayList<ColorItem> paletteItems = new ArrayList<ColorItem>();
493
                                                String paletteName = colorTableLibrary.loadPalette(palettesPath, (String) fileList.get(i), paletteItems);
494
                                                if (paletteName.equals(colorTableName)) {
495
                                                        if (paletteItems.size() <= 0)
496
                                                                continue;
497

    
498
                                                        ColorTable colorTable = colorTableLibrary.createColorTable();
499
                                                        colorTable.setName(paletteName);
500
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
501
                                                        colorTable.setInterpolated(true);
502

    
503
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
504

    
505
                                                        setLastLegend(colorTable);
506

    
507
                                                        RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
508
                                                        Params params = filterList.createEmptyFilterParams();
509
                                                        params.setParam("colorTable", colorTable);
510
                                                        colorTableManager.addFilter(params);
511
                                                        return;
512
                                                }
513
                                        }
514
                                }
515
                        } catch (FileNotOpenException e) {
516
                                // No podemos aplicar el filtro
517
                        } catch (RasterDriverException e) {
518
                                // No podemos aplicar el filtro
519
                        } catch (ProcessInterruptedException e) {
520
                                // El usuario ha cancelado el proceso
521
                        }
522

    
523
                        RasterFilterListManager enhancementManager = filterList.getManagerByID("EnhancementStretch");
524
                        Params params = filterList.createEmptyFilterParams();
525
                        params.setParam("stats", stats);
526
                        params.setParam("remove", new Boolean(false));
527
                        params.setParam("renderBands", getRender().getRenderBands());
528
                        params.setParam("stretchs", null);//coge el LinearStretchParams por defecto
529
                        params.setParam("rgb", new Boolean(true));
530
                        enhancementManager.addFilter(params);
531
        }
532

    
533
        /*
534
         * (non-Javadoc)
535
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isReproyectable()
536
         */
537
        public boolean isReproyectable() {
538
                if (dataStore == null)
539
                        return false;
540
                return dataStore.isReproyectable();
541
        }
542

    
543
        /**
544
         * @throws ReadException
545
         * @throws ReadDriverException
546
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
547
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
548
         *                 com.iver.utiles.swing.threads.Cancellable)
549
         */
550
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadException {
551
                this.image = image;
552
                TaskEventManager task = rManager.getRasterTask();
553
                task.setEvent(null);
554
                
555
                if(!layerInitialize) {
556
                        if (dataStore != null)
557
                                try {
558
                                        this.init();
559
                                } catch (FilePaletteException e) {
560
                                        throw new ReadException("Error in raster legend", e);
561
                                } catch (LoadLayerException e) {
562
                                        throw new ReadException("Error initializing the layer", e);
563
                                }
564
                }
565

    
566
                try {
567
                        if (!isOpen())
568
                                return;
569

    
570
                        enableStopped();
571
                        // callLegendChanged(null);
572
                        
573
                        //Solo el zoom normal recalcula el nivel dependiendo de la escala. El zoom por niveles asigna
574
                        //?l el nivel de zoom por lo que no habr? que recalcularlo.
575
                        if(recalcLevel) {
576
                                double pixelSize = vp.getEnvelope().getLength(0) / (double)vp.getImageWidth();
577
                                zoomLevel = dataStore.getNearestLevel(pixelSize);
578
                        }
579
                        recalcLevel = true;
580

    
581
                        strategy = new RasterDrawStrategy(getMapContext(), this);
582
                        strategy.stackStrategy();
583
                        HashMap<DefaultFLyrRaster, Boolean> tStr = strategy.getStrategy();
584
                        if (tStr != null &&
585
                                tStr.get(this) != null &&
586
                                ((Boolean) (tStr.get(this))).booleanValue() == false) {
587
                                disableStopped();
588
                                return;
589
                        }
590

    
591
                        if (isWithinScale(scale)) {
592
                                /*if (status != null && firstLoad) {
593
                                        if (mustTileDraw) {
594
                                                Point2D p = vp.getOffset();
595
                                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
596
                                                Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
597
                                                tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
598
                                                for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
599
                                                        // drawing part
600
                                                        try {
601
                                                                ViewPort vport = tiles.getTileViewPort(vp, tileNr);
602
//                                                                g.setClip(tiles.getClip(tileNr).x, tiles.getClip(tileNr).y, tiles.getClip(tileNr).width - 5, tiles.getClip(tileNr).height);
603
                                                                draw(image, g, vport, cancel);
604
                                                        } catch (InterruptedException e) {
605
                                                                System.out.println("Se ha cancelado el pintado");
606
                                                        } catch (InvalidSetViewException e) {
607
                                                                throw new ReadException("Error reading file.", e);
608
                                                        } catch (RasterDriverException e) {
609
                                                                throw new ReadException("Error reading file.", e);
610
                                                        }  catch (NoninvertibleTransformException e) {
611
                                                                throw new ReadException("Error in the transformation.", e);
612
                                                        }
613
                                        } else
614
                                                try {
615
                                                        draw(image, g, vp, cancel);
616
                                                } catch (InterruptedException e) {
617
                                                        System.out.println("Se ha cancelado el pintado");
618
                                                } catch (InvalidSetViewException e) {
619
                                                        throw new ReadException("Error reading file.", e);
620
                                                } catch (RasterDriverException e) {
621
                                                        throw new ReadException("Error reading file.", e);
622
                                                }
623
                                        try {
624
                                                status.applyStatus(this);
625
                                        } catch (NotSupportedExtensionException e) {
626
                                                throw new ReadException("Error in input file", e);
627
                                        } catch (FilterTypeException e) {
628
                                                throw new ReadException("Error setting filters from a project.", e);
629
                                        } catch (RasterDriverException e) {
630
                                                throw new ReadException("Error reading file.", e);
631
                                        } catch (FileNotFoundInListException e) {
632
                                                throw new ReadException("Error reading file.", e);
633
                                        } catch (OperationNotSupportedException e) {
634
                                                throw new ReadException("Error reading file.", e);
635
                                        } catch (FilterManagerException e) {
636
                                                throw new ReadException("Error reading file.", e);
637
                                        } catch (InvalidSourceException e) {
638
                                                throw new ReadException("Invalid file.", e);
639
                                        }
640
                                        firstLoad = false;
641
                                }*/
642

    
643
                                if (mustTileDraw) {
644
                                        Point2D p = vp.getOffset();
645
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
646
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
647
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
648
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
649
                                                // drawing part
650
                                                try {
651
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
652
                                                        draw(image, g, vport, cancel);
653
                                                } catch (InterruptedException e) {
654
                                                        System.out.println("Se ha cancelado el pintado");
655
                                                } catch (InvalidSetViewException e) {
656
                                                        throw new ReadException("Error reading file.", e);
657
                                                } catch (RasterDriverException e) {
658
                                                        throw new ReadException("Error reading file.", e);
659
                                                }  catch (NoninvertibleTransformException e) {
660
                                                        throw new ReadException("Error in the transformation.", e);
661
                                                }
662
                                } else
663
                                        try {
664
                                                draw(image, g, vp, cancel);
665
                                        } catch (InterruptedException e) {
666
                                                System.out.println("Se ha cancelado el pintado");
667
                                        } catch (InvalidSetViewException e) {
668
                                                throw new ReadException("Error reading file.", e);
669
                                        } catch (RasterDriverException e) {
670
                                                throw new ReadException("Error reading file.", e);
671
                                        }
672

    
673
                        }
674
                        
675
                        //callLegendChanged(null);
676
                } finally {
677
                        disableStopped();
678
                        task.setEvent(null);
679
                }
680
        }
681

    
682
        protected void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws RasterDriverException, InvalidSetViewException, InterruptedException {
683
                Envelope adjustedExtent = vp.getAdjustedExtent();
684
                if (adjustedExtent == null)
685
                        return;
686
                Extent e = rManager.getDataStructFactory().createExtent(adjustedExtent.getLowerCorner().getX(),
687
                                adjustedExtent.getUpperCorner().getY(), adjustedExtent
688
                                                .getUpperCorner().getX(),
689
                                adjustedExtent
690
                                                .getLowerCorner().getY());
691
                Dimension imgSz = vp.getImageSize();
692
                ViewPortData vp2 = rManager.createViewPortData(vp.getProjection(), e, imgSz );
693
                vp2.setMat(vp.getAffineTransform());
694
                //vp2.setTime(vp.getTime()); 
695
                
696
                try {
697
                        if(getDataStore().isTiled()) 
698
                                getRender().drawTiledService(g, vp2, vp.getImageSize());
699
                        else
700
                                getRender().draw(g, vp2);
701
                } catch (ProcessInterruptedException e1) {
702
                }
703
        }
704

    
705
        /**
706
         * Inserta la proyecci?n.
707
         *
708
         * @param proj Proyecci?n.
709
         */
710
        public void setProjection(IProjection proj) {
711
                super.setProjection(proj);
712
        }
713

    
714
        /*
715
         * (non-Javadoc)
716
         * @see org.gvsig.fmap.mapcontext.layers.FLayer#getFullEnvelope()
717
         */
718
        public Envelope getFullEnvelope() {
719
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
720
                //un extent aunque la capa no est? abierta
721
                if(/*!isOpen() || */dataStore == null || dataStore.getExtent() == null)
722
                        return null;
723

    
724
                Rectangle2D e = dataStore.getExtent().toRectangle2D();
725
                try {
726
                        return geomManager.createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
727
                                        .getMaxY(), SUBTYPES.GEOM2D);
728
                } catch (CreateEnvelopeException e1) {
729
                        logger.error("Error creating the envelope", e);
730
                        return null;
731
                }
732
        }
733

    
734
        /**
735
         * Obtiene el valor del pixel del Image en la posici?n x,y
736
         * @param x Posici?n x
737
         * @param y Posici?n y
738
         * @return valor de pixel
739
         */
740
        public int[] getPixel(int pxx, int pxy) {
741
                int[] argb = { -1, -1, -1, -1 };
742
                if (!isOpen() || (image == null))
743
                        return argb;
744
                if (pxx >= 0 && pxx < image.getWidth() && pxy >= 0 && pxy < image.getHeight()) {
745
                        int value = image.getRGB(pxx, pxy);
746
                        argb[0] = ((value & 0xff000000) >> 24);
747
                        argb[1] = ((value & 0x00ff0000) >> 16);
748
                        argb[2] = ((value & 0x0000ff00) >> 8);
749
                        argb[3] = (value & 0x000000ff);
750
                }
751
                return argb;
752
        }
753

    
754
        /*
755
         * (non-Javadoc)
756
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
757
         */
758
        public double getMaxX() {
759
                if(getFullEnvelope() != null)
760
                        return getFullEnvelope().getMaximum(0);
761
                return -1;
762
        }
763

    
764
        /*
765
         * (non-Javadoc)
766
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
767
         */
768
        public double getMaxY() {
769
                if(getFullEnvelope() != null)
770
                        return this.getFullEnvelope().getMaximum(1);
771
                return -1;
772
        }
773

    
774
        /*
775
         * (non-Javadoc)
776
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinX()
777
         */
778
        public double getMinX() {
779
                if(getFullEnvelope() != null)
780
                        return getFullEnvelope().getMinimum(0);
781
                return -1;
782
        }
783

    
784
        /*
785
         * (non-Javadoc)
786
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinY()
787
         */
788
        public double getMinY() {
789
                if(getFullEnvelope() != null)
790
                        return getFullEnvelope().getMinimum(1);
791
                return -1;
792
        }
793

    
794
        /* (non-Javadoc)
795
         * @deprecated. See String getInfo(Point p) throws DriverException
796
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
797
         */
798
        public String queryByPoint(Point p) {
799
                if (!isOpen())
800
                        return null;
801
                ColorConversion conv = rManager.getColorConversion();
802

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

    
805
                ArrayList<Object> attr = getAttributes();
806
                data += "  <raster\n";
807
                data += "    File=\"" + getFile() + "\"\n";
808
                for (int i = 0; i < attr.size(); i++) {
809
                        Object[] a = (Object[]) attr.get(i);
810

    
811
                        data += "    " + a[0].toString() + "=";
812
                        if (a[1].toString() instanceof String)
813
                                data += "\"" + a[1].toString() + "\"\n";
814
                        else
815
                                data += a[1].toString() + "\n";
816
                }
817
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
818
                data += "    Point_WC=\"" + mathUtil.format(posXWC, 3) + " , " + mathUtil.format(posYWC, 3) + "\"\n";
819
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
820
                double[] cmyk = conv.RGBtoCMYK(r & 0xff, g & 0xff, b & 0xff, 1D);
821
                data += "    CMYK=\"" + mathUtil.format(cmyk[0], 4) + ", " + mathUtil.format(cmyk[1], 4) + ", " + mathUtil.format(cmyk[2], 4) + "," + mathUtil.format(cmyk[3], 4) + "\"\n";
822
                double[] hsl = conv.RGBtoHSL(r & 0xff, g & 0xff, b & 0xff);
823
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
824
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
825
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
826
                data += "    HSL=\"" + mathUtil.format(hsl[0], 4) + ", " + mathUtil.format(hsl[1], 4) + ", " + mathUtil.format(hsl[2], 4) + "\"\n";
827
                data += "  />\n";
828

    
829
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
830
                return data;
831
        }
832

    
833
//        /*
834
//         * (non-Javadoc)
835
//         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo(java.awt.Point, double, com.iver.utiles.swing.threads.Cancellable)
836
//         */
837
//        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel)
838
//                        throws ReadException {
839
//                if (!isOpen()) {
840
//                        StringXMLItem[] item = new StringXMLItem[1];
841
//                        String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
842
//                        data += "  <raster\n" + "  Layer=\" Not available\"\n" + "  />\n";
843
//                        data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
844
//                        item[0] = new StringXMLItem(data, this);
845
//                        return item;
846
//                }
847
//
848
//                Point2D pReal = getMapContext().getViewPort().toMapPoint(p);
849
//                Point2D px = new Point2D.Double();
850
//                if(        pReal.getX() > this.getMinX() &&
851
//                        pReal.getX() < this.getMaxX() &&
852
//                        pReal.getY() > this.getMinY() &&
853
//                        pReal.getY() < this.getMaxY())
854
//                        try {
855
//                                px = transformPoint(0, pReal);
856
//                        } catch (NoninvertibleTransformException e) {
857
//                                throw new ReadException("Error in the transformation", e);
858
//                        }
859
//                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
860
//                ColorConversion conv = new ColorConversion();
861
//
862
//                StringXMLItem[] item = new StringXMLItem[1];
863
//                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
864
//
865
//                data += "  <raster\n";
866
//                data += "    View_Point=\"" + p.getX() + " , " + p.getY() + "\"\n";
867
//                data += "    World_Point=\"" + MathUtils.format(pReal.getX(), 3) + " , " + MathUtils.format(pReal.getY(), 3) + "\"\n";
868
//                if (px == null)
869
//                        data += "    Pixel_Point=\"Out\"\n";
870
//                else
871
//                        data += "    Pixel_Point=\"" + (int) px.getX() + " , " + (int) px.getY() + "\"\n";
872
//                data += "    RGB=\"" + rgb[1] + "  " + rgb[2] + "  " + rgb[3] + "\"\n";
873
//                double[] cmyk = conv.RGBtoCMYK(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff, 1D);
874
//                data += "    CMYK=\"" + MathUtils.format(cmyk[0], 4) + ", " + MathUtils.format(cmyk[1], 4) + ", " + MathUtils.format(cmyk[2], 4) + "," + MathUtils.format(cmyk[3], 4) + "\"\n";
875
//                double[] hsl = conv.RGBtoHSL(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff);
876
//                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
877
//                hsl[2] = (int) (hsl[2] * 255. + 0.5);
878
//                hsl[1] = (int) (hsl[1] * 255. + 0.5);
879
//                data += "    HSL=\"" + MathUtils.format(hsl[0], 4) + ", " + MathUtils.format(hsl[1], 4) + ", " + MathUtils.format(hsl[2], 4) + "\"\n";
880
//                data += "    Band_Value=\"";
881
//                try {
882
//                        if (px != null) {
883
//                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3)
884
//                                        for(int i = 0; i < getBandCount(); i++)
885
//                                                if(getDataSource().isInside(pReal)) {
886
//                                                        Point2D pxAux = transformPoint(i, pReal);
887
//                                                        data += ((Integer)getDataSource().getData((int)pxAux.getX(), (int)pxAux.getY(), i)).intValue() + "  ";
888
//                                                }
889
//                                if(getDataType()[0] == 4)
890
//                                        for(int i = 0; i < getBandCount(); i++)
891
//                                                if(getDataSource().isInside(pReal)) {
892
//                                                        Point2D pxAux = transformPoint(i, pReal);
893
//                                                        data += ((Float)getDataSource().getData((int)pxAux.getX(), (int)pxAux.getY(), i)).floatValue() + "  ";
894
//                                                }
895
//                                if(getDataType()[0] == 5)
896
//                                        for(int i = 0; i < getBandCount(); i++)
897
//                                                if(getDataSource().isInside(pReal)) {
898
//                                                        Point2D pxAux = transformPoint(i, pReal);
899
//                                                        data += ((Double)getDataSource().getData((int)pxAux.getX(), (int)pxAux.getY(), i)).doubleValue() + "  ";
900
//                                                }
901
//                        }
902
//                } catch (RasterDriverException ex) {
903
//                        throw new ReadException("Error en el acceso al dataset", ex);
904
//                } catch (InvalidSetViewException ex) {
905
//                        throw new ReadException(
906
//                                        "Error en la asignaci?n de la vista en getData", ex);
907
//                } catch (FileNotOpenException ex) {
908
//                        throw new ReadException("Fichero no abierto en el dataset", ex);
909
//                } catch (NoninvertibleTransformException ex) {
910
//                        throw new ReadException("Error in the transformation", ex);
911
//                }
912
//                data += "\"\n";
913
//                data += "  />\n";
914
//                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
915
//
916
//                item[0] = new StringXMLItem(data, this);
917
//                return item;
918
//        }
919

    
920
        /**
921
         * Filters a string for being suitable as XML Tag, erasing
922
         * all not alphabetic or numeric characters.
923
         * @param s
924
         * @return string normalized
925
         */
926
        private String normalizeAsXMLTag(String s) {
927
                return s.replaceAll("[^a-zA-Z0-9]", "");
928
        }
929

    
930
        /*
931
         * (non-Javadoc)
932
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAttributes()
933
         */
934
        public ArrayList<Object> getAttributes() {
935
                ArrayList<Object> attr = new ArrayList<Object>();
936
                if(!isOpen())
937
                        return attr;
938
                Object [][] a = {
939
                        {"Filename", dataStore.getName()},
940
                        {"Filesize", new Long(dataStore.getFileSize())},
941
                        {"Width", new Integer((int)dataStore.getWidth())},
942
                        {"Height", new Integer((int)dataStore.getHeight())},
943
                        {"Bands", new Integer(dataStore.getBandCount())}
944
                };
945
                for (int i = 0; i < a.length; i++)
946
                        attr.add(a[i]);
947
                return attr;
948
        }
949

    
950
        /**
951
         * Escribe en el proyecto la capa actual
952
         * @throws XMLException
953
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
954
         */
955
        public XMLEntity getXMLEntity() throws XMLException {
956
                if(isClosed() || isAwake())
957
                        return null;
958

    
959
//                XMLEntity xml = super.getXMLEntity();
960
//                if(getFile() != null)
961
//                        xml.putProperty("file", getFile());
962
//                xml.putProperty("driverName", "gvSIG Raster Driver");
963
//
964
//                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
965
//                if (status == null)
966
//                        status = new StatusLayerRaster();
967
//                status.getXMLEntity(xml, true, this);
968
//
969
//                return xml;
970
                return null;
971
        }
972

    
973
        /**
974
         * Recupera de disco los datos de la capa.
975
         */
976
        public void setXMLEntity(XMLEntity xml) throws XMLException {
977
//                for (int i = 0; i < xml.getPropertyCount(); i++) {
978
//                        String key = xml.getPropertyName(i);
979
//                        if(key.startsWith("raster.file")) {
980
//                                if(xml.getPropertyValue(i).startsWith(RasterLibrary.getTemporalPath()))
981
//                                        throw new XMLLayerException("Trying to load temporary layer", null);
982
//                        }
983
//                }
984
//                super.setXMLEntity(xml);
985
//
986
//                try {
987
//                        params = new File(xml.getStringProperty("file"));
988
//
989
//                        if(params != null && getName() != null && getName().compareTo("") != 0)
990
//                                try {
991
//                                        enableAwake();
992
//                                } catch (NotAvailableStateException e) {
993
//                                        RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
994
//                                }
995
//                        if(!super.getFLayerStatus().visible)
996
//                                enableStopped();
997
//
998
//                        // Para notificar al adapter-driver cual es la proyecci?n.
999
//                        setProjection(super.getProjection());
1000
//
1001
//                        //Inicializamos la clase a la que se usa por defecto para
1002
//                        //compatibilidad con proyectos antiguos
1003
//                        String claseStr = StatusLayerRaster.defaultClass;
1004
//                        if (xml.contains("raster.class"))
1005
//                                claseStr = xml.getStringProperty("raster.class");
1006
//
1007
//                        if (status != null)
1008
//                                status.setXMLEntity(xml, this);
1009
//                        else if (claseStr != null && !claseStr.equals(""))
1010
//                                try {
1011
//                                        // Class clase =
1012
//                                        // LayerFactory.getLayerClassForLayerClassName(claseStr);
1013
//                                        Class clase = this.getClass();
1014
//                                        Constructor constr = clase.getConstructor(null);
1015
//                                        status = (IStatusRaster) constr.newInstance(null);
1016
//                                        if (status != null) {
1017
//                                                ((StatusLayerRaster)status).setNameClass(claseStr);
1018
//                                                status.setXMLEntity(xml, this);
1019
//                                                filterArguments = status.getFilterArguments();
1020
//
1021
//                                                //Creamos la tabla de color
1022
//                                                ArrayList color = (ArrayList) filterArguments.clone();
1023
//                                                loadedFromProject = ColorTableListManager.createColorTableFromArray(color);
1024
//                                        }
1025
//                                        // } catch (ClassNotFoundException exc) {
1026
//                                        // throw new XMLLayerException("", exc);
1027
//                                } catch (InstantiationException exc) {
1028
//                                        throw new XMLLayerException("", exc);
1029
//                                } catch (IllegalAccessException exc) {
1030
//                                        throw new XMLLayerException("", exc);
1031
//                                } catch (NoSuchMethodException exc) {
1032
//                                        throw new XMLLayerException("", exc);
1033
//                                } catch (InvocationTargetException exc) {
1034
//                                        throw new XMLLayerException("", exc);
1035
//                                }
1036
//                        firstLoad = true;
1037
//                } catch (NotExistInXMLEntity e) {
1038
//
1039
//                }
1040
        }
1041

    
1042
        /* (non-Javadoc)
1043
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort, com.iver.cit.gvsig.fmap.operations.Cancellable)
1044
         */
1045
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
1046
                        double scale, PrintAttributes propeties) throws ReadException {
1047

    
1048
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
1049
                        return;
1050

    
1051
                if (!mustTilePrint)
1052
                        draw(null, g, viewPort, cancel,scale);
1053
                else {
1054
                        // Para no pedir imagenes demasiado grandes, vamos
1055
                        // a hacer lo mismo que hace EcwFile: chunkear.
1056
                        // Llamamos a drawView con cuadraditos m?s peque?os
1057
                        // del BufferedImage ni caso, cuando se imprime viene con null
1058
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1059
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1060

    
1061
                        //Si es la primera lectura salvamos los valores de m?ximo y m?nimo para la aplicaci?n
1062
                        //de realce si la imagen es de 16 bits.
1063

    
1064
                        //RasterStats stats = getSource().getFilterStack().getStats();
1065
                        //if(stats != null)
1066
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
1067

    
1068

    
1069
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
1070
                                // Parte que dibuja
1071
                                try {
1072
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1073
                                        draw(null, g, vp, cancel, scale);
1074
                                } catch (NoninvertibleTransformException e) {
1075
                                        throw new ReadException("Error en la transformaci?n.", e);
1076
                                }
1077
                }
1078
        }
1079

    
1080
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
1081
                        double scale) throws ReadException {
1082
                if(!isOpen())
1083
                        return;
1084

    
1085
                // Para no pedir imagenes demasiado grandes, vamos
1086
                // a hacer lo mismo que hace EcwFile: chunkear.
1087
                // Llamamos a drawView con cuadraditos m?s peque?os
1088
                // del BufferedImage ni caso, cuando se imprime viene con null
1089

    
1090
                int numW, numH;
1091
                int stepX, stepY;
1092
                int xProv, yProv;
1093
                int A = 1500;
1094
                int H = 1500;
1095
                int altoAux, anchoAux;
1096

    
1097
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
1098

    
1099
                // Vamos a hacerlo en trozos de AxH
1100
                Rectangle r = g.getClipBounds();
1101
                numW = (r.width) / A;
1102
                numH = (r.height) / H;
1103

    
1104
                double[] srcPts = new double[8];
1105
                double[] dstPts = new double[8];
1106

    
1107
                yProv = r.y;
1108
                for (stepY = 0; stepY < numH + 1; stepY++) {
1109
                        if ((yProv + H) > r.getMaxY())
1110
                                altoAux = (int) r.getMaxY() - yProv;
1111
                        else
1112
                                altoAux = H;
1113

    
1114
                        xProv = r.x;
1115
                        for (stepX = 0; stepX < numW + 1; stepX++) {
1116
                                if ((xProv + A) > r.getMaxX())
1117
                                        anchoAux = (int) r.getMaxX() - xProv;
1118
                                else
1119
                                        anchoAux = A;
1120

    
1121
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
1122

    
1123
                                // Parte que dibuja
1124
                                srcPts[0] = xProv;
1125
                                srcPts[1] = yProv;
1126
                                srcPts[2] = xProv + anchoAux + 1;
1127
                                srcPts[3] = yProv;
1128
                                srcPts[4] = xProv + anchoAux + 1;
1129
                                srcPts[5] = yProv + altoAux + 1;
1130
                                srcPts[6] = xProv;
1131
                                srcPts[7] = yProv + altoAux + 1;
1132

    
1133
                                try {
1134
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
1135
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
1136
                                        // Extent extent = new Extent(rectCuadricula);
1137

    
1138
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
1139
                                        ViewPort vp = (ViewPort)viewPort.clone();
1140
                                        vp.setImageSize(tam);
1141
                                        Envelope env = geomManager.createEnvelope(rectCuadricula
1142
                                                        .getMinX(), rectCuadricula.getMinY(),
1143
                                                        rectCuadricula.getMaxX(), rectCuadricula.getMaxY(),
1144
                                                        SUBTYPES.GEOM2D);
1145
                                        vp.setEnvelope(env);
1146
                                        vp.setAffineTransform(mat);
1147
                                        draw(null, g, vp, cancel, scale);
1148

    
1149
                                } catch (NoninvertibleTransformException e) {
1150
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
1151
                                } catch (ReadException e) {
1152
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
1153
                                } catch (CreateEnvelopeException e) {
1154
                                        logger.error("Error creating the envelope", e);
1155
                                } catch (CloneNotSupportedException e) {
1156
                                        logger.error("Error cloning the viewport", e);
1157
                                }
1158
                                // Fin parte que dibuja
1159
                                xProv = xProv + A;
1160
                        }
1161
                        yProv = yProv + H;
1162
                }
1163
        }
1164

    
1165
        /**
1166
         * Borra de la lista de listeners el que se pasa como par?metro.
1167
         *
1168
         * @param o LayerListener a borrar.
1169
         *
1170
         * @return True si ha sido correcto el borrado del Listener.
1171
         */
1172
        public boolean removeLayerListener(LayerListener o) {
1173
                if (this.isRemoveRasterFlag()) {
1174
                        try {
1175
                                enableClosed();
1176
                        } catch (NotAvailableStateException e1) {
1177
                                // No se ha podido cambiar el estado de la capa a cerrado
1178
                        }
1179
                }
1180

    
1181
                // Salva a RMF
1182
                if (dataStore != null)
1183
                        // Guardamos la GeoReferenciacion de cada dataset
1184
                        try {
1185
                                dataStore.saveGeoreferencingToRmf();
1186
                        } catch (RmfSerializerException e) {
1187
                                logger.error("error_salvando_rmf", this, e);
1188
                        }
1189

    
1190
                        if (this.isRemoveRasterFlag()) {
1191
                                image = null;
1192
                                if (dataStore != null) {
1193
                                        String[] files = getFileName().clone();
1194

    
1195
                                        try {
1196
                                                dataStore.close();
1197
                                        } catch (CloseException e) {
1198
                                        }
1199

    
1200
                                        dataStore = null;
1201
                                        render = null;
1202
                                        // System.gc();
1203
                                        this.setRemoveRasterFlag(true);
1204

    
1205
                                        for (int i = 0; i < files.length; i++) {
1206
                                                File file = new File(files[i]);
1207
                                                File dirTemp = fileUtil.getTemporalFile();
1208
                                                if(!file.exists())
1209
                                                        continue;
1210
                                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
1211
                                                        file.delete();
1212

    
1213
                                                        // Borramos todos los ficheros que puedan tener relacion con el fichero actual
1214
                                                        String basefile = file.getName();
1215
                                                        File basepath = file.getParentFile();
1216
                                                        int last = basefile.lastIndexOf(".");
1217
                                                        if (last != -1)
1218
                                                                basefile = basefile.substring(0, last + 1);
1219
                                                        File[] list = basepath.listFiles();
1220
                                                        for (int j = 0; j < list.length; j++)
1221
                                                                if (list[j].getName().startsWith(basefile))
1222
                                                                        list[j].delete();
1223
                                                }
1224
                                        }
1225
                                }
1226
                        }
1227
                        updateDrawVersion();
1228
                        return super.layerListeners.remove(o);
1229
        }
1230

    
1231
        /*
1232
         * (non-Javadoc)
1233
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRemoveRasterFlag()
1234
         */
1235
        public boolean isRemoveRasterFlag() {
1236
                return removeRasterFlag;
1237
        }
1238

    
1239
        /*
1240
         * (non-Javadoc)
1241
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setRemoveRasterFlag(boolean)
1242
         */
1243
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1244
                this.removeRasterFlag = removeRasterFlag;
1245
        }
1246

    
1247
        /*
1248
         * (non-Javadoc)
1249
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1250
         */
1251
        public String getTocImageIcon() {
1252
                return "map-ok-ico";
1253
        }
1254

    
1255
        /*
1256
         * (non-Javadoc)
1257
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getTileSize()
1258
         */
1259
        public int[] getTileSize() {
1260
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1261
                return size;
1262
        }
1263

    
1264
        /*
1265
         * (non-Javadoc)
1266
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isTiled()
1267
         */
1268
        public boolean isTiled() {
1269
                return mustTileDraw;
1270
        }
1271

    
1272
        /*
1273
         * (non-Javadoc)
1274
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isGeoreferenced()
1275
         */
1276
        public boolean isGeoreferenced() {
1277
                return dataStore.isGeoreferenced();
1278
        }
1279

    
1280
        /*
1281
         * (non-Javadoc)
1282
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getNoDataValue()
1283
         */
1284
        public NoData getNoDataValue() {
1285
                return dataStore.getNoDataValue();
1286
        }
1287

    
1288
        /**
1289
         * Sets the nodata value for this layer
1290
         * @param nd
1291
         */
1292
        public void setNoDataValue(NoData nd) {
1293
                if (dataStore != null)
1294
                        dataStore.setNoDataValue(nd);
1295
        }
1296

    
1297
        /*
1298
         * (non-Javadoc)
1299
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getPxHeight()
1300
         */
1301
        public double getPxHeight() {
1302
                return dataStore.getHeight();
1303
        }
1304

    
1305
        /*
1306
         * (non-Javadoc)
1307
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getPxWidth()
1308
         */
1309
        public double getPxWidth() {
1310
                return dataStore.getWidth();
1311
        }
1312

    
1313
        /**
1314
         * Gets the height in world coordinates of this raster layer
1315
         */
1316
        public double getWCHeight() {
1317
                return getFullEnvelope().getMaximum(1);
1318
        }
1319

    
1320
        /**
1321
         * Gets the width in world coordinates of this raster layer
1322
         */
1323
        public double getWCWidth() {
1324
                return getFullEnvelope().getMaximum(0);
1325
        }
1326

    
1327
        /**
1328
         * Gets the size of all files of this raster layer
1329
         */
1330
        public long[] getFileSize() {
1331
                if (dataStore == null)
1332
                        return null;
1333

    
1334
                return dataStore.getFileSizeByProvider();
1335
        }
1336

    
1337
        /**
1338
         * Gets the list of file names
1339
         */
1340
        public String[] getFileName() {
1341
                if (dataStore == null)
1342
                        return null;
1343

    
1344
                return dataStore.getURIByProvider();
1345
        }
1346

    
1347
        /**
1348
         * Returns the number of files in this raster layer
1349
         */
1350
        public int getFileCount() {
1351
                return dataStore.getProviderCount();
1352
        }
1353

    
1354
        /*
1355
         * (non-Javadoc)
1356
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileFormat()
1357
         */
1358
        public String getFileFormat() {
1359
                if(dataStore.getSourceType() == RasterDataStore.FILE) {
1360
                        String fName = dataStore.getName();
1361
                        int index = fName.lastIndexOf(".") + 1;
1362
                        String ext = null;
1363
                        if (index > 0)
1364
                                ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1365
                        return ext;
1366
                }
1367
                if(dataStore.getSourceType() == RasterDataStore.POSTGIS) {
1368
                        return "POSTGIS";
1369
                }
1370
                return null;
1371
        }
1372

    
1373
        /*
1374
         * (non-Javadoc)
1375
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1376
         */
1377
        public int[] getDataType() {
1378
                return dataStore.getDataType();
1379
        }
1380

    
1381
        /**
1382
         * Sets the filter list
1383
         */
1384
        public void setRenderFilterList(RasterFilterList filterList) {
1385
                getRender().setFilterList(filterList);
1386
        }
1387
        
1388
        /*
1389
         * (non-Javadoc)
1390
         * @see org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint#getInfo(java.awt.Point, double, org.gvsig.tools.task.Cancellable, boolean)
1391
         */
1392
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel,
1393
                        boolean fast) throws LoadLayerException, DataException {
1394
                DynObjectSetRasterInfo info = new DynObjectSetRasterInfo();
1395
                
1396
                if (!isOpen()) {
1397
                        info.addField("Layer not open", normalizeAsXMLTag(getName()), 0);
1398
                        return info;
1399
                }
1400
                
1401
                Point2D pReal = getMapContext().getViewPort().toMapPoint(p);
1402
                Point2D px = new Point2D.Double();
1403
                if(        pReal.getX() > this.getMinX() &&
1404
                        pReal.getX() < this.getMaxX() &&
1405
                        pReal.getY() > this.getMinY() &&
1406
                        pReal.getY() < this.getMaxY()) {
1407
                        px = transformPoint(pReal);
1408
                }
1409
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
1410
                ColorConversion conv = rManager.getColorConversion();
1411
                info.addField("File", normalizeAsXMLTag(getName()), 0);
1412
                info.addField("View Point", "[" + p.getX() + " , " + p.getY() + "]", 1);
1413
                info.addField("World Point", "[" + mathUtil.format(pReal.getX(), 3) + " , " + mathUtil.format(pReal.getY(), 3) + "]", 2);
1414
                if (px == null)
1415
                        info.addField("Pixel Point", "Out", 3);
1416
                else
1417
                        info.addField("Pixel Point", "[" + (int) px.getX() + ",  " + (int) px.getY() + "]", 3);
1418
                info.addField("RGB", "[" + rgb[1] + ",  " + rgb[2] + ",  " + rgb[3] + "]", 4);
1419
                double[] cmyk = conv.RGBtoCMYK(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff, 1D);
1420
                info.addField("CMYK", "[" + mathUtil.format(cmyk[0], 4) + ",  " + mathUtil.format(cmyk[1], 4) + ",  " + mathUtil.format(cmyk[2], 4) + ",  " + mathUtil.format(cmyk[3], 4) + "]", 5);
1421
                double[] hsl = conv.RGBtoHSL(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff);
1422
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
1423
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
1424
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
1425
                info.addField("HSL", "[" + mathUtil.format(hsl[0], 4) + ",  " + mathUtil.format(hsl[1], 4) + ",  " + mathUtil.format(hsl[2], 4) + "]", 6);
1426
                String data = "[";
1427
                try {
1428
                        if (px != null) {
1429
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3) {
1430
                                        for(int i = 0; i < dataStore.getBandCount(); i++) {
1431
                                                if(dataStore.isInside(pReal)) {
1432
                                                        Point2D pxAux = transformPoint(pReal);
1433
                                                        int val = ((Integer)dataStore.getData((int)pxAux.getX(), 
1434
                                                                        (int)pxAux.getY(), i)).intValue();
1435
                                                        if(getDataType()[0] == Buffer.TYPE_BYTE)
1436
                                                                data += (val & 0x000000ff) + ",  ";
1437
                                                        else
1438
                                                                data += val + ",  ";
1439
                                                }
1440
                                        }
1441
                                }
1442
                                if(getDataType()[0] == 4) {
1443
                                        for(int i = 0; i < dataStore.getBandCount(); i++) {
1444
                                                if(dataStore.isInside(pReal)) {
1445
                                                        Point2D pxAux = transformPoint(pReal);
1446
                                                        data += ((Float)dataStore.getData((int)pxAux.getX(), 
1447
                                                                        (int)pxAux.getY(), i)).floatValue() + ",  ";
1448
                                                }
1449
                                        }
1450
                                }
1451
                                if(getDataType()[0] == 5) {
1452
                                        for(int i = 0; i < dataStore.getBandCount(); i++) {
1453
                                                if(dataStore.isInside(pReal)) {
1454
                                                        Point2D pxAux = transformPoint(pReal);
1455
                                                        data += ((Double)dataStore.getData((int)pxAux.getX(), 
1456
                                                                        (int)pxAux.getY(), i)).doubleValue() + ",  ";
1457
                                                }
1458
                                        }
1459
                                }
1460
                        }
1461
                        data +=  "]";
1462
                        info.addField("Band Value", data, 7);
1463
                } catch (RasterDriverException ex) {
1464
                        throw new LoadLayerException("Error en el acceso al dataset", ex);
1465
                } catch (InvalidSetViewException ex) {
1466
                        throw new LoadLayerException("Error en la asignaci?n de la vista en getData", ex);
1467
                } catch (FileNotOpenException ex) {
1468
                        throw new LoadLayerException("Fichero no abierto en el dataset", ex);
1469
                }
1470
                return info;
1471
        }
1472
        
1473
        /**
1474
         * Transforma un punto real a coordenadas pixel
1475
         * 
1476
         * @param numberBand
1477
         * @param pReal
1478
         * @return
1479
         * @throws LoadLayerException 
1480
         * @throws ReadDriverException
1481
         */
1482
        private Point2D transformPoint(Point2D pReal) throws LoadLayerException {
1483
                AffineTransform at = dataStore.getAffineTransform();
1484
                Point2D px = new Point2D.Double();
1485
                //px = new Point2D.Double(pReal.getX(), pReal.getY());
1486
                try {
1487
                        at.inverseTransform(pReal, px);
1488
                        return px;
1489
                } catch (NoninvertibleTransformException e) {
1490
                        throw new LoadLayerException("Error en la transformaci?n del punto", e);
1491
                }
1492
        }
1493
        
1494
        /*
1495
         * (non-Javadoc)
1496
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1497
         */
1498
        public Object getInfo(String key) {
1499
                if (key.equals("DriverName"))
1500
                        return "gvSIG Raster Driver";
1501
                return null;
1502
        }
1503

    
1504
        /*
1505
         * (non-Javadoc)
1506
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getBandCountFromDataset()
1507
         */
1508
        public int[] getBandCountFromDataset() {
1509
                return dataStore.getBandCountByProvider();
1510
        }
1511

    
1512
        /*
1513
         * (non-Javadoc)
1514
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1515
         */
1516
        public String getColorInterpretation(int band, int dataset) {
1517
                if (this.dataStore.getColorInterpretation().get(band) == null)
1518
                        return "Undefined";
1519
                return this.dataStore.getColorInterpretation().get(band);
1520
        }
1521

    
1522
        /*
1523
         * (non-Javadoc)
1524
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getWktProjection()
1525
         */
1526
        public String getWktProjection() throws RasterDriverException {
1527
                return dataStore.getWktProjection();
1528
        }
1529

    
1530
        /*
1531
         * (non-Javadoc)
1532
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRGB()
1533
         */
1534
        public boolean isRGB() {
1535
                if ((dataStore == null) || (render == null))
1536
                        return false;
1537

    
1538
                if (dataStore.getDataType()[0] != Buffer.TYPE_BYTE)
1539
                        return false;
1540

    
1541
                boolean R = false;
1542
                boolean G = false;
1543
                boolean B = false;
1544

    
1545
                int[] renderBands = render.getRenderBands();
1546
                for (int i = 0; i < renderBands.length; i++)
1547
                        if (renderBands[i] >= 0)
1548
                                switch (i) {
1549
                                        case 0:
1550
                                                R = true;
1551
                                                break;
1552
                                        case 1:
1553
                                                G = true;
1554
                                                break;
1555
                                        case 2:
1556
                                                B = true;
1557
                                                break;
1558
                                }
1559

    
1560
                if (R && G && B)
1561
                        return true;
1562

    
1563
                return false;
1564
        }
1565

    
1566
        /**
1567
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1568
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1569
         * cacheado o no dependiendo del tama?o de esta.
1570
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1571
         * @return Grid.
1572
         * @throws InterruptedException
1573
         */
1574
        public Grid getFullGrid(boolean interpolated) throws GridException, InterruptedException {
1575
                RasterQuery query = rManager.createQuery();
1576
                query.setAllDrawableBands();
1577
                Buffer bf = null;
1578
                try {
1579
                        query.setAreaOfInterest();
1580
                        bf = dataStore.query(query);
1581
                } catch (RasterDriverException e) {
1582
                        throw new GridException("Error reading buffer");
1583
                } catch (ProcessInterruptedException e) {
1584
                        throw new InterruptedException("Carga interrumpida");
1585
                } catch (InvalidSetViewException e) {
1586
                        throw new GridException("Error reading buffer");
1587
                }
1588
                return rManager.createGrid(bf, dataStore, interpolated);
1589
        }
1590

    
1591
        /*
1592
         * (non-Javadoc)
1593
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getReadOnlyFullGrid(boolean)
1594
         */
1595
        public Grid getReadOnlyFullGrid(boolean interpolated) throws GridException, InterruptedException {
1596
                RasterQuery query = rManager.createQuery();
1597
                query.setReadOnly(true);
1598
                query.setAllDrawableBands();
1599
                Buffer bf = null;
1600
                try {
1601
                        query.setAreaOfInterest();
1602
                        bf = dataStore.query(query);
1603
                } catch (RasterDriverException e) {
1604
                        throw new GridException("Error reading buffer");
1605
                } catch (ProcessInterruptedException e) {
1606
                        throw new InterruptedException("Carga interrumpida");
1607
                } catch (InvalidSetViewException e) {
1608
                        throw new GridException("Error reading buffer");
1609
                }
1610
                return rManager.createGrid(bf, dataStore, interpolated);
1611
        }
1612

    
1613
        /**
1614
         * Obtiene el tama?o de celda de la fuente de datos
1615
         * @return double con el tama?o de celda
1616
         */
1617
        public double getCellSize() {
1618
                return (dataStore != null) ? dataStore.getCellSize() : 1;
1619
        }
1620

    
1621
        /*
1622
         * (non-Javadoc)
1623
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFullRasterExtent()
1624
         */
1625
        public Extent getFullRasterExtent() {
1626
                return this.dataStore.getExtent();
1627
        }
1628

    
1629

    
1630
        /**
1631
         * Devuelve el fichero asociado a la capa o null si no tiene.
1632
         * @return Fichero.
1633
         */
1634
        public File getFile() {
1635
                if(getDataStore().getParameters() instanceof RasterFileStoreParameters)
1636
                        return ((RasterFileStoreParameters)getDataStore().getParameters()).getFile();
1637
                return new File("");
1638
        }
1639

    
1640
        /**
1641
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1642
         * @param file Fichero a consultar
1643
         * @return true si es aceptado y false si no lo es.
1644
         */
1645
        public boolean isFileAccepted(File file) {
1646
                return dataStore.isFileSupported(file.getName());
1647
        }
1648
        
1649
        /**
1650
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1651
         * @param file Fichero a consultar
1652
         * @return true si es aceptado y false si no lo es.
1653
         */
1654
        public static boolean isFileSupported(File file) {
1655
                return RasterLocator.getManager().isExtensionSupported(file.getName());
1656
        }
1657

    
1658
        /*
1659
         * (non-Javadoc)
1660
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#existColorTable()
1661
         */
1662
        public boolean existColorTable() {
1663
                return getRender().existColorTable();
1664
        }
1665

    
1666
        /**
1667
         * Returns true if the data store has an alpha band
1668
         */
1669
        public boolean existsAlphaBand() {
1670
                if(dataStore.getColorInterpretation() != null)
1671
                        return dataStore.getColorInterpretation().hasAlphaBand();
1672
                else
1673
                        return false;
1674
        }
1675

    
1676
        /*
1677
         * (non-Javadoc)
1678
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAlphaBandNumber()
1679
         */
1680
        public int getAlphaBandNumber() {
1681
                if(dataStore.getColorInterpretation() != null)
1682
                        return dataStore.getColorInterpretation().getBand(ColorInterpretation.ALPHA_BAND);
1683
                return -1;
1684
        }
1685

    
1686
        /**
1687
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1688
         * capa busque una leyenda valida.
1689
         * @param ct
1690
         */
1691
        public void setLastLegend(ColorTable ct) {
1692
                lastLegend = ColorTableLegend.createLegend(ct);
1693
        }
1694

    
1695
        /**
1696
         * Devuelve la Leyenda de la capa.
1697
         * @return Leyenda.
1698
         */
1699
        public ILegend getLegend() {
1700
                if (lastLegend != null)
1701
                        return lastLegend;
1702

    
1703
                return null;
1704
        }
1705

    
1706
        /*
1707
         * (non-Javadoc)
1708
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1709
         */
1710
        public void addLegendListener(LegendListener listener) {
1711
                layerChangeSupport.addLayerListener(listener);
1712
        }
1713

    
1714
        /*
1715
         *  (non-Javadoc)
1716
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1717
         */
1718
        public int getShapeType() {
1719
                return TYPES.SURFACE;
1720
        }
1721

    
1722
        /*
1723
         * (non-Javadoc)
1724
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1725
         */
1726
        public void removeLegendListener(LegendListener listener) {
1727
                layerChangeSupport.removeLayerListener(listener);
1728
        }
1729

    
1730
        /*
1731
         * (non-Javadoc)
1732
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isInside(java.awt.geom.Point2D)
1733
         */
1734
        public boolean isInside(Point2D p) {
1735
                 return dataStore.isInside(p);
1736
        }
1737

    
1738
        /*
1739
         * (non-Javadoc)
1740
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAffineTransform()
1741
         */
1742
        public AffineTransform getAffineTransform() {
1743
                return dataStore.getAffineTransform();
1744
        }
1745

    
1746
        /*
1747
         * (non-Javadoc)
1748
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setAffineTransform(java.awt.geom.AffineTransform)
1749
         */
1750
        public void setAffineTransform(AffineTransform transf) {
1751
                if(transf == null)
1752
                        return;
1753
                affineTransformList.add(transf);
1754
                dataStore.setAffineTransform(transf);
1755
                updateDrawVersion();
1756
        }
1757

    
1758
        /*
1759
         * (non-Javadoc)
1760
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setAffineTransformWithoutHistorical(java.awt.geom.AffineTransform)
1761
         */
1762
        public void setAffineTransformWithoutHistorical(AffineTransform transf) {
1763
                dataStore.setAffineTransform(transf);
1764
                updateDrawVersion();
1765
        }
1766

    
1767
        /*
1768
         * (non-Javadoc)
1769
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getAffineTransformHistorical()
1770
         */
1771
        public Historical getAffineTransformHistorical() {
1772
                return this.affineTransformList;
1773
        }
1774

    
1775
        /*
1776
         * (non-Javadoc)
1777
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#saveGeoToRmf()
1778
         */
1779
        public void saveGeoToRmf() throws RmfSerializerException {
1780
                if (!isOpen())
1781
                        return;
1782

    
1783
                dataStore.saveGeoreferencingToRmf();
1784
                
1785
                affineTransformList.clear();
1786
                affineTransformList.add(this.getAffineTransform());
1787
        }
1788

    
1789
        /*
1790
         * (non-Javadoc)
1791
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1792
         */
1793
        public boolean isActionEnabled(int action) {
1794
                switch (action) {
1795
                        case IRasterLayerActions.BANDS_FILE_LIST:
1796
                                if (existColorTable() || getDataStore().isMosaic() || getDataStore().isTiled())
1797
                                        return false;
1798
                                break;
1799
                        case IRasterLayerActions.BANDS_RGB:
1800
                                if (existColorTable())
1801
                                        return false;
1802
                                break;
1803
                        case IRasterLayerActions.REPROJECT:
1804
                                if (!isReproyectable())
1805
                                        return false;
1806
                                break;
1807
                        case IRasterLayerActions.CREATEOVERVIEWS:
1808
                                return overviewsSupport();
1809
                        case IRasterLayerActions.OPACITY:
1810
                        case IRasterLayerActions.TRANSPARENCY:
1811
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1812
                        case IRasterLayerActions.ENHANCED:
1813
                        case IRasterLayerActions.PANSHARPENING:
1814
                        case IRasterLayerActions.SELECT_LAYER:
1815
                        case IRasterLayerActions.SAVE_COLORINTERP:
1816
                                return true;
1817
                        case IRasterLayerActions.REMOTE_ACTIONS:
1818
                                return false;
1819
                        case IRasterLayerActions.TAILTRIM:
1820
                        case IRasterLayerActions.GEOLOCATION:
1821
                                return !(dataStore.isTiled());
1822
                }
1823
                return true;
1824
        }
1825

    
1826
        /*
1827
         * (non-Javadoc)
1828
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1829
         */
1830
        public void setVisible(boolean visibility) {
1831
                if(visibility)
1832
                        state.disableStopped();
1833
                else
1834
                        enableStopped();
1835

    
1836
                if(isAwake() || isClosed())
1837
                        try {
1838
                                this.load();
1839
                        } catch (LoadLayerException e) {
1840
                                e.printStackTrace();
1841
                        }
1842

    
1843
                /*
1844
                 * Cuando se modifica la visibilidad de una capa raster se hace un updateDrawVersion de todas las
1845
                 * capas raster de ese MapContext. Esto es porque la estrategia utilizada por RasterDrawStrategy hace
1846
                 * que se cacheen en blanco las capas raster que est?n ocultas debajo de otras. Al hacer invisibles las
1847
                 * de arriba la cache que estaba en blanco hace que no se pinte nada. Para evitar esto las marcamos todas
1848
                 * como que han sido modificadas para que se vuelvan a leer.
1849
                 */
1850
                if(getMapContext() != null) {
1851
                        ArrayList<FLayer> listLayers = new ArrayList<FLayer>();
1852
                        listLayers = RasterDrawStrategy.getLayerList(getMapContext().getLayers(), listLayers);
1853
                        for (int i = 0; i < listLayers.size(); i++)
1854
                                if(listLayers.get(i) instanceof DefaultFLyrRaster)
1855
                                        ((DefaultFLyrRaster)listLayers.get(i)).updateDrawVersion();
1856
                }
1857

    
1858
                super.setVisible(visibility);
1859
        }
1860

    
1861
        /**
1862
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1863
         * @return valor de transparencia
1864
         */
1865
        public int getTransparency() {
1866
                try {
1867
                        return getRender().getLastTransparency().getOpacity();
1868
                } catch (NullPointerException e) {
1869
                        return super.getTransparency();
1870
                }
1871
        }
1872

    
1873
        /**
1874
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1875
         * o no.
1876
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1877
         */
1878
        public boolean isTransparent() {
1879
                return getRender().getLastTransparency().isTransparencyActive();
1880
        }
1881

    
1882
        /**
1883
         * Asigna la transparencia de la siguiente renderizaci?n
1884
         * @param valor de transparencia
1885
         */
1886
        public void setTransparency(int trans) {
1887
                super.setTransparency(trans);
1888
                try {
1889
                        getRender().getLastTransparency().setOpacity(trans);
1890
                } catch (NullPointerException e) {
1891
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1892
                }
1893
        }
1894

    
1895
        /**
1896
         * Gets the last buffer which was rendered
1897
         */
1898
        public Buffer getLastRenderBuffer() {
1899
                return getRender().getLastRenderBuffer();
1900
        }
1901

    
1902
        /**
1903
         *
1904
         * @return ROIs asociadas a la capa raster.
1905
         */
1906
        public ArrayList<ROI> getRois() {
1907
                return rois;
1908
        }
1909

    
1910
        /**
1911
         * Establece las ROI asociadas a la capa raster.
1912
         *
1913
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1914
         */
1915
        public void setRois(ArrayList<ROI> rois) {
1916
                this.rois = rois;
1917
        }
1918

    
1919
        /**
1920
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1921
         * devolver? null.
1922
         * @return TreeMap con la lista de capas a dibujar
1923
         */
1924
        public HashMap<DefaultFLyrRaster, Boolean> getRasterStrategy() {
1925
                if(strategy != null)
1926
                        return strategy.getStrategy();
1927
                return null;
1928
        }
1929

    
1930
        /**
1931
         * @return the configuration
1932
         */
1933
        static public IConfiguration getConfiguration() {
1934
                return configuration;
1935
        }
1936

    
1937
        /**
1938
         * @param configuration the configuration to set
1939
         */
1940
        static public void setConfiguration(IConfiguration configuration) {
1941
                DefaultFLyrRaster.configuration = configuration;
1942
        }
1943

    
1944
        /*
1945
         * (non-Javadoc)
1946
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#reload()
1947
         */
1948
        public void reload() throws ReloadLayerException {
1949
                try {
1950
                        super.reload();
1951
                        if (getMapContext() == null)
1952
                                return;
1953
                        if (isStopped())
1954
                                disableStopped();
1955
                        load();
1956
                        getMapContext().invalidate();
1957
                } catch (LoadLayerException e) {
1958
                        setAvailable(false);
1959
                        throw new ReloadLayerException(getName(), e);
1960
                }
1961
        }
1962

    
1963
        /**
1964
         * Devuelve si la capa tiene soporte para poder generar overviews
1965
         * @return
1966
         */
1967
        public boolean overviewsSupport() {
1968
                if ((dataStore != null) && (dataStore.overviewsSupport()))
1969
                        return true;
1970

    
1971
                return false;
1972
        }
1973

    
1974
        /**
1975
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1976
         * en escala de grises
1977
         * @return
1978
         */
1979
        public boolean isRenderingAsGray() {
1980
                int[] renderBands = getRender().getRenderBands();
1981
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1982
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1983
                        return true;
1984
                return false;
1985
        }
1986

    
1987
        /*
1988
         * (non-Javadoc)
1989
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
1990
         */
1991
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1992
                updateDrawVersion();
1993
        }
1994

    
1995
        /*
1996
         * (non-Javadoc)
1997
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#adjustWorldRequest(java.awt.geom.Point2D)
1998
         */
1999
        public Point2D adjustWorldRequest(Point2D req) {
2000
                Envelope ext = null;
2001

    
2002
                ext = getFullEnvelope();
2003
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
2004
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
2005
                return req;
2006
        }
2007

    
2008
        /*
2009
         * (non-Javadoc)
2010
         * @see org.gvsig.fmap.mapcontext.layers.FLyrDefault#cloneLayer()
2011
         */
2012
        public FLayer cloneLayer() throws Exception {
2013
                RasterDataStore  ds = dataStore.cloneDataStore();
2014
                DefaultFLyrRaster newLayer = new DefaultFLyrRaster();
2015
                newLayer.setName(getName());
2016
                newLayer.setOpenRasterStore(ds);
2017
                newLayer.firstLoad = firstLoad;
2018
                
2019
                ArrayList<RasterFilter> filters = getRender().getFilterList().getStatusCloned();
2020

    
2021
                //Hacemos una copia de las bandas a renderizar
2022
                if(getRender().getRenderBands() != null) {
2023
                        int[] rb = new int[getRender().getRenderBands().length];
2024
                        for (int i = 0; i < rb.length; i++)
2025
                                rb[i] = getRender().getRenderBands()[i];
2026
                        newLayer.getRender().setRenderBands(rb);
2027
                }
2028

    
2029
                //Asignamos el entorno
2030
                if(newLayer.getRender().getFilterList() == null)
2031
                        newLayer.getRender().setFilterList(RasterLocator.getManager().createEmptyFilterList(getRender().getFilterList().getInitDataType()));
2032
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
2033
                newLayer.getRender().getFilterList().setStatus(filters);
2034

    
2035
                // Asignamos los valores noData del original
2036
                newLayer.setNoDataValue(getNoDataValue());
2037
                if(dataStore.getNoDataValue().isDefined())
2038
                        newLayer.setNoDataTransparent(true);
2039
                newLayer.enableOpen();
2040
                
2041
                return newLayer;
2042
        }
2043
        
2044
        /*
2045
         * (non-Javadoc)
2046
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileLayer()
2047
         */
2048
        public FLayer getFileLayer() throws RasterDriverException {
2049
                try {
2050
                        return cloneLayer();
2051
                } catch (Exception e) {
2052
                }
2053
                return null;
2054
        }
2055
        
2056
        /*
2057
         * (non-Javadoc)
2058
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#addFile(java.lang.String)
2059
         */
2060
        public void addFile(String file) throws InvalidSourceException {
2061
                getDataStore().addFile(file);
2062
        }
2063
        
2064
        /*
2065
         * (non-Javadoc)
2066
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#removeFile(java.lang.String)
2067
         */
2068
        public void removeFile(String file) {
2069
                getDataStore().removeFile(file);
2070
        }
2071

    
2072
        /*****************************************************/
2073

    
2074
        public void disableStopped() {state.disableStopped();}
2075

    
2076
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
2077

    
2078
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
2079

    
2080
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
2081

    
2082
        public void enableStopped() {state.enableStopped();}
2083

    
2084
        public boolean isAwake() {return state.isAwake();}
2085

    
2086
        public boolean isClosed() {return state.isClosed();}
2087

    
2088
        public boolean isOpen() {return state.isOpen();}
2089

    
2090
        public boolean isStopped() {return state.isStopped();}
2091

    
2092

    
2093
        @SuppressWarnings("unchecked")
2094
        public Set getMetadataChildren() {
2095
                return null;
2096
        }
2097

    
2098
        public Object getMetadataID() {
2099
                return getName();
2100
        }
2101

    
2102
        public String getMetadataName() {
2103
                return null;
2104
        }
2105

    
2106
        /*
2107
         * (non-Javadoc)
2108
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getDataStore()
2109
         */
2110
        public RasterDataStore getDataStore() {
2111
                return this.dataStore;
2112
        }
2113

    
2114
        public void setOpenRasterStore(DataStore dataStore) throws LoadLayerException {
2115
                if(dataStore instanceof CoverageStoreProviderServices) {
2116
                        try {
2117
                                this.dataStore = rManager.open(((CoverageStoreProviderServices) dataStore).getProvider(), dataStore.getParameters());
2118
                        } catch (NotSupportedExtensionException e) {
2119
                                throw new LoadLayerException("Extension not supported", e);
2120
                        } catch (RasterDriverException e) {
2121
                                throw new LoadLayerException("Error opening the DataStore", e);
2122
                        }
2123
                } else
2124
                        this.dataStore = (RasterDataStore) dataStore;
2125
                try {
2126
                        enableAwake();
2127
                } catch (NotAvailableStateException e) {
2128
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
2129
                }
2130
                setProjection(this.dataStore.getProjection());
2131
        }
2132
        
2133
        /*
2134
         * (non-Javadoc)
2135
         * @see org.gvsig.fmap.mapcontext.layers.operations.SingleLayer#setDataStore(org.gvsig.fmap.dal.DataStore)
2136
         */
2137
        public void setDataStore(DataStore dataStore) throws LoadLayerException {
2138
                setOpenRasterStore(dataStore);
2139
                load();
2140
        }
2141
        
2142
        /*
2143
         * (non-Javadoc)
2144
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRemote()
2145
         */
2146
        public boolean isRemote() {
2147
                return false;
2148
        }
2149
        
2150
        /**
2151
         * Returns true if exists a process reading data from this layer
2152
         * @return
2153
         */
2154
        public boolean isReadingData() {
2155
                return readingData != null;
2156
        }
2157

    
2158
        /**
2159
         * When a process is using information of this layer this variable will contain
2160
         * the thread ID.
2161
         * @param readingData
2162
         */
2163
        public synchronized void setReadingData(String readingData) {
2164
                this.readingData = readingData;
2165
        }
2166
        
2167
        public DynObjectSet getInfo(org.gvsig.fmap.geom.primitive.Point p, double tolerance)
2168
                        throws LoadLayerException, DataException {
2169
                return null;
2170
        }
2171

    
2172
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel)
2173
                        throws LoadLayerException, DataException {
2174
                return null;
2175
        }
2176

    
2177
        @Override
2178
        protected void doDispose() throws BaseException {
2179
                // Nothing to do
2180
        }
2181

    
2182
        /*
2183
         * (non-Javadoc)
2184
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#getZoomLevel()
2185
         */
2186
        public int getZoomLevel() {
2187
                return zoomLevel;
2188
        }
2189

    
2190
        /*
2191
         * (non-Javadoc)
2192
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#setZoomLevel(int)
2193
         */
2194
        public void setZoomLevel(int zoomLevel) {
2195
                this.zoomLevel = zoomLevel;
2196
        }
2197
        
2198
        /*
2199
         * (non-Javadoc)
2200
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#increaseZoomLevel()
2201
         */
2202
        public boolean increaseZoomLevel() {
2203
                if(zoomLevel < (this.dataStore.getZoomLevels() - 1)) { 
2204
                        zoomLevel ++;
2205
                        recalcLevel = false;
2206
                        return true;
2207
                }
2208
                return false;
2209
        }
2210
        
2211
        /*
2212
         * (non-Javadoc)
2213
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#decreaseZoomLevel()
2214
         */
2215
        public boolean decreaseZoomLevel() {
2216
                if(zoomLevel > 0) { 
2217
                        zoomLevel --;
2218
                        recalcLevel = false;
2219
                        return true;
2220
                }
2221
                return false;
2222
        }
2223
        
2224
        /*
2225
         * (non-Javadoc)
2226
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#getCoordsInLevel(java.awt.geom.Point2D, int, int, int)
2227
         */
2228
        public Envelope getCoordsInLevel(Point2D center, int level, int w, int h) throws CreateEnvelopeException {
2229
                Extent ex = getDataStore().getCoordsInLevel(center, level, w, h);
2230
                return geomManager.createEnvelope(ex.getULX(), ex.getULY(), ex.getLRX(), ex.getLRY(), SUBTYPES.GEOM2D);
2231
        }
2232
        
2233
        /*
2234
         * (non-Javadoc)
2235
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#isEnabledMultiresolution()
2236
         */
2237
        public boolean isEnabledMultiresolution() {
2238
                return dataStore.isTiled();
2239
        }
2240
        
2241
        /*
2242
         * (non-Javadoc)
2243
         * @see org.gvsig.raster.fmap.layers.Multiresolution#setTileServer(java.lang.Class)
2244
         */
2245
        public void setTileServer(Class<?> tileServer) {
2246
                dataStore.setTileServer(tileServer);
2247
        }
2248
        
2249
        @SuppressWarnings("unchecked")
2250
        @Override
2251
        public void loadFromState(PersistentState state)
2252
                        throws PersistenceException {
2253
                super.loadFromState(state);
2254
                
2255
                //this.status = (IStatusRaster)state.get("status");
2256
                List<ROI> rois = state.getList("rois");
2257
                if(rois != null) {
2258
                        this.rois = new ArrayList<ROI>();
2259
                        this.rois.addAll(rois);
2260
                }
2261
                this.zoomLevel = state.getInt("zoomLevel");
2262
                this.recalcLevel = state.getBoolean("recalcLevel");
2263
                if(this.dataStore == null)
2264
                        this.dataStore = (RasterDataStore)state.get("rasterdatastore");
2265
                this.lastLegend = (ILegend)state.get("legend");
2266
                this.colorTableLoadedFromProject = (ColorTable)state.get("colortable");
2267
                this.zoomLevel = state.getInt("zoomLevel");
2268
                this.recalcLevel = state.getBoolean("recalcLevel");
2269
                loadedFromProject = true;
2270
        }
2271

    
2272
        @Override
2273
        public void saveToState(PersistentState state) throws PersistenceException {
2274
                super.saveToState(state);
2275
                
2276
                //state.set("status", status);
2277
                state.set("rasterdatastore", dataStore);        
2278
                state.set("legend", lastLegend);        
2279
                state.set("rois", rois);        
2280
                state.set("colortable", getRender().getColorTable());        
2281
                state.set("zoomLevel", zoomLevel);        
2282
                state.set("recalcLevel", recalcLevel);        
2283
        }        
2284
        
2285
        public static void registerPersistence() {
2286
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
2287
                DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
2288
                if( definition == null ) {
2289
                        if (manager.getDefinition(FLyrDefault.class) == null) {
2290
                                FLyrDefault.registerPersistent();
2291
                        }
2292
                        definition = manager.addDefinition(
2293
                                        DefaultFLyrRaster.class,
2294
                                        PERSISTENT_NAME,
2295
                                        PERSISTENT_DESCRIPTION,
2296
                                        null, 
2297
                                        null
2298
                        );
2299
                        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE, "FLyrDefault");
2300
                        
2301
                        registerPersistence(definition);
2302
                }
2303
        }
2304
        
2305
        public static void registerPersistence(DynStruct definition) {
2306
                //definition.addDynFieldObject("status").setClassOfValue(StatusLayerRaster.class).setMandatory(false);
2307
                definition.addDynFieldObject("rasterdatastore").setClassOfValue(RasterDataStore.class).setMandatory(true);
2308
                definition.addDynFieldObject("legend").setClassOfValue(ILegend.class).setMandatory(false);
2309
                definition.addDynFieldList("rois").setClassOfItems(ROI.class).setMandatory(false);
2310
                definition.addDynFieldObject("colortable").setClassOfValue(ColorTable.class).setMandatory(false);
2311
                definition.addDynFieldInt("zoomlevel").setMandatory(false);
2312
                definition.addDynFieldBoolean("recalcLevel").setMandatory(false);
2313
        }
2314

    
2315
        /*
2316
         * (non-Javadoc)
2317
         * @see org.gvsig.fmap.mapcontext.layers.operations.Classifiable#getGeometryType()
2318
         */
2319
        public GeometryType getGeometryType() throws ReadException {
2320
                try {
2321
                        return GeometryLocator.getGeometryManager().getGeometryType(TYPES.SURFACE, SUBTYPES.GEOM2D);
2322
                } catch (GeometryTypeNotSupportedException e) {
2323
                        throw new ReadException(getDataStore().getName(), e);
2324
                } catch (GeometryTypeNotValidException e) {
2325
                        throw new ReadException(getDataStore().getName(), e);
2326
                } 
2327
        }
2328

    
2329
}