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

History | View | Annotate | Download (73.9 KB)

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

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

    
39
import org.cresques.cts.IProjection;
40
import org.gvsig.compat.print.PrintAttributes;
41
import org.gvsig.fmap.crs.CRSFactory;
42
import org.gvsig.fmap.dal.DALLocator;
43
import org.gvsig.fmap.dal.DataManager;
44
import org.gvsig.fmap.dal.DataStore;
45
import org.gvsig.fmap.dal.DataStoreParameters;
46
import org.gvsig.fmap.dal.coverage.RasterLibrary;
47
import org.gvsig.fmap.dal.coverage.RasterLocator;
48
import org.gvsig.fmap.dal.coverage.RasterManager;
49
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
50
import org.gvsig.fmap.dal.coverage.datastruct.ColorItem;
51
import org.gvsig.fmap.dal.coverage.datastruct.ColorTableLibrary;
52
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
53
import org.gvsig.fmap.dal.coverage.datastruct.Params;
54
import org.gvsig.fmap.dal.coverage.datastruct.ViewPortData;
55
import org.gvsig.fmap.dal.coverage.exception.FileNotFoundInListException;
56
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
57
import org.gvsig.fmap.dal.coverage.exception.FilePaletteException;
58
import org.gvsig.fmap.dal.coverage.exception.FilterManagerException;
59
import org.gvsig.fmap.dal.coverage.exception.FilterTypeException;
60
import org.gvsig.fmap.dal.coverage.exception.GridException;
61
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
62
import org.gvsig.fmap.dal.coverage.exception.InvalidSourceException;
63
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
64
import org.gvsig.fmap.dal.coverage.exception.OperationNotSupportedException;
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.mapcontext.ViewPort;
106
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
107
import org.gvsig.fmap.mapcontext.exceptions.ReloadLayerException;
108
import org.gvsig.fmap.mapcontext.layers.FLayer;
109
import org.gvsig.fmap.mapcontext.layers.FLyrDefault;
110
import org.gvsig.fmap.mapcontext.layers.LayerChangeSupport;
111
import org.gvsig.fmap.mapcontext.layers.LayerListener;
112
import org.gvsig.fmap.mapcontext.layers.Tiling;
113
import org.gvsig.fmap.mapcontext.layers.operations.Classifiable;
114
import org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint;
115
import org.gvsig.fmap.mapcontext.layers.operations.SingleLayer;
116
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
117
import org.gvsig.fmap.mapcontext.rendering.legend.events.listeners.LegendListener;
118
import org.gvsig.raster.fmap.legend.ColorTableLegend;
119
import org.gvsig.raster.util.RasterNotLoadException;
120
import org.gvsig.tools.ToolsLocator;
121
import org.gvsig.tools.dynobject.DynClass;
122
import org.gvsig.tools.dynobject.DynObjectManager;
123
import org.gvsig.tools.dynobject.DynObjectSet;
124
import org.gvsig.tools.dynobject.DynStruct;
125
import org.gvsig.tools.exception.BaseException;
126
import org.gvsig.tools.persistence.PersistenceManager;
127
import org.gvsig.tools.persistence.PersistentState;
128
import org.gvsig.tools.persistence.exception.PersistenceException;
129
import org.gvsig.tools.task.Cancellable;
130
import org.gvsig.utils.XMLEntity;
131
import org.gvsig.utils.XMLException;
132
import org.slf4j.Logger;
133
import org.slf4j.LoggerFactory;
134

    
135
/**
136
 * Raster layer
137
 * 
138
 * @author Nacho Brodin (nachobrodin@gmail.com)
139
 */
140
public class DefaultFLyrRaster extends FLyrDefault implements FLyrRaster, Multiresolution, InfoByPoint, Classifiable,
141
                IRasterLayerActions, ILayerState, VisualPropertyListener, SingleLayer {
142
        public static final String      PERSISTENT_NAME        = "FLyrRasterSE_Persistent";
143
    public static final String      PERSISTENT_DESCRIPTION = "FLyrRasterSE Persistent";
144
    private RasterManager           rManager               = RasterLocator.getManager();
145
        private boolean                 mustTileDraw           = false;
146
        private boolean                 mustTilePrint          = true;
147
        private int                     maxTileDrawWidth       = 200;
148
        private int                     maxTileDrawHeight      = 200;
149
        private int                     maxTilePrintWidth      = 1500;
150
        private int                     maxTilePrintHeight     = 1500;
151
        protected IStatusRaster         status                 = null;
152
        private boolean                 firstLoad              = false;
153
        private boolean                 removeRasterFlag       = true;
154
        protected RasterDataStore       dataStore              = null;
155
        protected Render                render                 = null;
156
        private int                     posX                   = 0;
157
        private int                     posY                   = 0;
158
        private double                  posXWC                 = 0;
159
        private int                     posYWC                 = 0;
160
        private int                     r                      = 0;
161
        private int                     g                      = 0;
162
        private int                     b                      = 0;
163
        private LayerChangeSupport      layerChangeSupport     = new LayerChangeSupport();
164
        private FLyrState               state                  = new FLyrState();
165
        protected ILegend               lastLegend             = null;
166
        protected ColorTable            loadedFromProject      = null;
167
        private ArrayList<ROI>          rois                   = null;
168
        private RasterDrawStrategy      strategy               = null;
169
        static private IConfiguration   configuration          = new DefaultLayerConfiguration();
170
        protected int                   zoomLevel              =  1;
171
        public boolean                  recalcLevel            = true;
172
        
173
        private BufferedImage           image                  = null;
174
        private static GeometryManager  geomManager                  = GeometryLocator.getGeometryManager();
175
        private static final Logger     logger                 = LoggerFactory.getLogger(DefaultFLyrRaster.class);
176
        protected FileUtils             fileUtil               = RasterLocator.getManager().getFileUtils();
177
        protected RasterUtils           rasterUtil             = RasterLocator.getManager().getRasterUtils();
178
        protected CRSUtils              crsUtil                = RasterLocator.getManager().getCRSUtils();
179
        protected MathUtils             mathUtil               = RasterLocator.getManager().getMathUtils();
180
        private String                  uri                    = null;
181
        
182
        /**
183
         * Tipo de valor no data asociado a la capa.
184
         * Sirve para diferenciar los estados seleccionados por el usuario. Siendo
185
         * estos 'Sin Valor NoData', 'NoData de Capa'(Por defecto) y 'Personalizado'
186
         */
187
        private int                     noDataType             = RasterLibrary.NODATATYPE_LAYER;
188

    
189
        /**
190
         * Lista de transformaciones afines que son aplicadas. Esta lista es
191
         * simplemente un historico que no se utiliza. Es posible utilizarlo para
192
         * recuperar transformaciones anteriores.
193
         */
194
        private Historical              affineTransformList    = null;
195
        protected String                readingData            = null;
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
        @SuppressWarnings("deprecation")
223
        public static DefaultFLyrRaster createLayer(String layerName, File file) throws LoadLayerException {
224
                ProviderServices provServ = RasterLocator.getManager().getProviderServices();
225
                RasterDataParameters storeParameters = provServ.createParameters(file.getName());
226
                storeParameters.setURI(file.getPath());
227
                
228
                DataManager dataManager = DALLocator.getDataManager();
229
                DataStore dataStore = null;
230
                try {
231
                        dataStore = dataManager.createStore(storeParameters);
232
                } catch (ValidateDataParametersException e) {
233
                        throw new LoadLayerException("Error al cargar la capa.");
234
                } catch (InitializeException e) {
235
                        throw new LoadLayerException("Error al cargar la capa.");
236
                } catch (ProviderNotRegisteredException e) {
237
                        throw new LoadLayerException("Error al cargar la capa.");
238
                }
239
                
240
                DefaultFLyrRaster lyr = new DefaultFLyrRaster();
241
                lyr.setName(layerName);
242
                lyr.setDataStore(dataStore);
243
                return lyr;
244
        }
245

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

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

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

    
275
        /**
276
         * Asignar el estado del raster
277
         * @param status
278
         */
279
        public void setStatus(IStatusRaster status){
280
                this.status = status;
281
        }
282

    
283
        /**
284
         * Obtiene el estado del raster
285
         * @return
286
         */
287
        public IStatusRaster getStatus(){
288
                return this.status;
289
        }
290

    
291
        /*
292
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
293
         */
294
        public void load() throws LoadLayerException {
295
                if (isStopped() || getDataStore() == null)
296
                        return;
297

    
298
                enableStopped(); // Paramos la capa mientras se hace un load
299

    
300
                int test = -1;
301
                DataStoreParameters params = getDataStore().getParameters();
302
                DataStoreParameters p = params;
303
                if (params != null) {
304
                        if(params instanceof TileDataParameters) {
305
                                uri = ((RasterDataParameters)params).getURI();
306
                                if(uri == null)
307
                                        p = (DataStoreParameters)((TileDataParameters)params).getDataParameters();
308
                        }
309
                        if(uri == null) {
310
                                if(params instanceof RasterDataParameters)
311
                                        uri = ((RasterDataParameters)p).getURI();
312
                        }
313
                        test = uri.indexOf("ecwp:");
314
                }
315

    
316
                if (test != -1) {
317
                        String urlECW = uri.substring(test + 6);
318
                        uri = "ecwp://" + urlECW;
319
                        System.err.println(test + " " + uri);
320
                }
321

    
322
                try {
323
                        if(!dataStore.isOpen())
324
                                dataStore = rManager.open(params);
325
                } catch (NotSupportedExtensionException e) {
326
                        throw new LoadLayerException(this.getName());
327
                } catch (RasterDriverException e) {
328
                        throw new LoadLayerException(this.getName());
329
                }
330
                
331
                if (dataStore != null)
332
                        try {
333
                                this.init();
334
                        } catch (FilePaletteException e) {
335
                                throw new LoadLayerException("", e);
336
                        }
337
        }
338

    
339
        /**
340
         * Acciones de inicializaci?n despu?s de que la fuente de datos
341
         * de la capa est? asignada. El tipo de fuente de datos es variable
342
         * puede ser MultiRasterDataset, CompositeDataset u otras que existan e
343
         * implementen IRasterDatasource.
344
         * @throws FilePaletteException 
345
         */
346
        public void init() throws LoadLayerException, FilePaletteException {
347
                if (dataStore == null)
348
                        throw new LoadLayerException("Formato no valido", new IOException());
349

    
350
                render = dataStore.getRender();
351
                render.addVisualPropertyListener(this);
352
                initFilters();
353

    
354
                //Inicializaci?n del historico de transformaciones
355
                affineTransformList.clear();
356
                affineTransformList.add(this.getAffineTransform());
357

    
358
                try {
359
                        enableOpen();
360
                } catch (NotAvailableStateException e) {
361
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Awake=" + isAwake(), e);
362
                }
363
        }
364

    
365
        /*
366
         * (non-Javadoc)
367
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#readProjection()
368
         */
369
        public IProjection readProjection() throws RasterDriverException {
370
                try {
371
                        crsUtil.setCRSFactory(CRSFactory.cp);
372
                        if( dataStore == null )
373
                                return null;
374
                        return crsUtil.convertWktToIProjection(dataStore.getWktProjection());
375
                } catch (Exception e) {
376
                        throw new RasterDriverException("Problems converting from WKT to IProjection", e);
377
                } catch (Error e) {
378
                        e.printStackTrace();
379
                        return null;
380
                }
381
        }
382

    
383
        /**
384
         * Crea el objeto renderizador de raster
385
         * @return Rendering
386
         */
387
        public Render getRender() {
388
                if (render == null) {
389
                        render = dataStore.getRender();
390
                        render.addVisualPropertyListener(this);
391
                }
392
                return render;
393
        }
394
        
395
        /*
396
         * (non-Javadoc)
397
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getURI()
398
         */
399
        public String getURI() {
400
                return uri;
401
        }
402

    
403
        /*
404
         * (non-Javadoc)
405
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#applyNoData()
406
         */
407
        public void applyNoData() {
408
                Boolean noDataEnabled = configuration.getValueBoolean("nodata_transparency_enabled", Boolean.FALSE);
409
                if (noDataEnabled.booleanValue() && dataStore.isNoDataEnabled()) {
410
                        noDataType = RasterLibrary.NODATATYPE_LAYER;
411
                        Double noDataValue = Double.valueOf(getNoDataValue());
412
                        dataStore.getTransparency().setNoData(noDataValue.doubleValue());
413
                } else {
414
                        dataStore.getTransparency().activeNoData(false);
415
                        noDataType = RasterLibrary.NODATATYPE_DISABLED;
416
                }
417
        }
418

    
419
        /**
420
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
421
         * @throws FilePaletteException 
422
         */
423
        protected void initFilters() throws FilePaletteException {
424
                if(getDataType() == null)
425
                        return;
426
                RasterFilterList filterList = rManager.createEmptyFilterList(getDataType()[0]);
427
                filterList.addEnvParam("IStatistics", dataStore.getStatistics());
428
                filterList.addEnvParam("MultiRasterDataset", dataStore);
429

    
430
                if(dataStore == null)
431
                        return;
432
                
433
                dataStore.resetNoDataValue();
434
                applyNoData();
435

    
436
                filterList.setInitDataType(getDataType()[0]);
437

    
438
                // Quitamos la leyenda
439
                lastLegend = null;
440

    
441
                try {
442
                        //Si en la carga del proyecto se carg? una tabla de color asignamos esta
443
                        if(loadedFromProject != null) {
444
                                setLastLegend(loadedFromProject);
445
                                RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
446
                                Params params = filterList.createEmptyFilterParams();
447
                                params.setParam("colorTable", loadedFromProject);
448
                                colorTableManager.addFilter(params);
449
                        } else
450
                                //sino ponemos la tabla asociada al raster
451
                                if (dataStore.getColorTable() != null) {
452
                                        ColorTable table = dataStore.getColorTable();
453
                                        setLastLegend(table);
454
                                        RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
455
                                        Params params = filterList.createEmptyFilterParams();
456
                                        params.setParam("colorTable", table);
457
                                        colorTableManager.addFilter(params);
458
                                } else //sino hace lo que dice en las preferencias
459
                                        if (!(getDataStore().getBandCount() >= 3 && getDataType()[0] == Buffer.TYPE_BYTE)) 
460
                                                loadEnhancedOrColorTable(filterList);
461
                        loadedFromProject = null;
462

    
463
                        getRender().setFilterList(filterList);
464
                        // Inicializo la transparencia para el render
465
                        getRender().setLastTransparency(dataStore.getTransparency().cloneTransparency());
466
                } catch (FilterTypeException e) {
467
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
468
                        logger.error("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
469
                } catch (FilterManagerException e) {
470
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
471
                        logger.error("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
472
                }
473
        }
474

    
475
        /**
476
         * Mira la configuracion para saber si debe cargar un realce o una tabla
477
         * de color por defecto
478
         * @param filterManager
479
         * @throws FilterTypeException
480
         * @throws FilePaletteException 
481
         */
482
        private void loadEnhancedOrColorTable(RasterFilterList filterList) throws FilterTypeException, FilterManagerException, FilePaletteException {
483
                String colorTableName = configuration.getValueString("loadlayer_usecolortable", (String) null);
484

    
485
                String palettesPath = System.getProperty("user.home") +
486
                File.separator +
487
                "gvSIG" + // PluginServices.getArguments()[0] +
488
                File.separator + "colortable";
489

    
490
                Statistics stats = dataStore.getStatistics();
491
                ColorTableLibrary colorTableLibrary = rManager.getDataStructFactory().getColorTableLibrary();
492

    
493
                if (colorTableName != null)
494
                        try {
495
                                stats.calculate();
496
                                if (getDataStore().getBandCount() == 1) {
497
                                        ArrayList<String> fileList = colorTableLibrary.getPaletteFileList(palettesPath);
498
                                        for (int i = 0; i < fileList.size(); i++) {
499
                                                ArrayList<ColorItem> paletteItems = new ArrayList<ColorItem>();
500
                                                String paletteName = colorTableLibrary.loadPalette(palettesPath, (String) fileList.get(i), paletteItems);
501
                                                if (paletteName.equals(colorTableName)) {
502
                                                        if (paletteItems.size() <= 0)
503
                                                                continue;
504

    
505
                                                        ColorTable colorTable = colorTableLibrary.createColorTable();
506
                                                        colorTable.setName(paletteName);
507
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
508
                                                        colorTable.setInterpolated(true);
509

    
510
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
511

    
512
                                                        setLastLegend(colorTable);
513

    
514
                                                        RasterFilterListManager colorTableManager = filterList.getManagerByID("ColorTable");
515
                                                        Params params = filterList.createEmptyFilterParams();
516
                                                        params.setParam("colorTable", colorTable);
517
                                                        colorTableManager.addFilter(params);
518
                                                        return;
519
                                                }
520
                                        }
521
                                }
522
                        } catch (FileNotOpenException e) {
523
                                // No podemos aplicar el filtro
524
                        } catch (RasterDriverException e) {
525
                                // No podemos aplicar el filtro
526
                        } catch (ProcessInterruptedException e) {
527
                                // El usuario ha cancelado el proceso
528
                        }
529

    
530
                        RasterFilterListManager enhancementManager = filterList.getManagerByID("EnhancementStretch");
531
                        Params params = filterList.createEmptyFilterParams();
532
                        params.setParam("stats", stats);
533
                        params.setParam("remove", new Boolean(false));
534
                        params.setParam("renderBands", getRender().getRenderBands());
535
                        params.setParam("stretchs", null);//coge el LinearStretchParams por defecto
536
                        params.setParam("rgb", new Boolean(true));
537
                        enhancementManager.addFilter(params);
538
        }
539

    
540
        /*
541
         * (non-Javadoc)
542
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isReproyectable()
543
         */
544
        public boolean isReproyectable() {
545
                if (dataStore == null)
546
                        return false;
547
                return dataStore.isReproyectable();
548
        }
549

    
550
        /**
551
         * @throws ReadException
552
         * @throws ReadDriverException
553
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
554
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
555
         *                 com.iver.utiles.swing.threads.Cancellable)
556
         */
557
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadException {
558
                this.image = image;
559
                TaskEventManager task = rManager.getRasterTask();
560
                task.setEvent(null);
561

    
562
                try {
563
                        if (!isOpen())
564
                                return;
565

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

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

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

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

    
669
                        }
670
                        
671
                        //callLegendChanged(null);
672
                } finally {
673
                        disableStopped();
674
                        task.setEvent(null);
675
                }
676
        }
677

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

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

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

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

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

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

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

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

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

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

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

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

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

    
826
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
827
                return data;
828
        }
829

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

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

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

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

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

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

    
1039
        /* (non-Javadoc)
1040
         * @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)
1041
         */
1042
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
1043
                        double scale, PrintAttributes propeties) throws ReadException {
1044

    
1045
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
1046
                        return;
1047

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

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

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

    
1065

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

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

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

    
1087
                int numW, numH;
1088
                int stepX, stepY;
1089
                int xProv, yProv;
1090
                int A = 1500;
1091
                int H = 1500;
1092
                int altoAux, anchoAux;
1093

    
1094
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
1095

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

    
1101
                double[] srcPts = new double[8];
1102
                double[] dstPts = new double[8];
1103

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

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

    
1118
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
1119

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

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

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

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

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

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

    
1187
                        if (this.isRemoveRasterFlag()) {
1188
                                image = null;
1189
                                if (dataStore != null) {
1190
                                        String[] files = getFileName().clone();
1191

    
1192
                                        try {
1193
                                                dataStore.close();
1194
                                        } catch (CloseException e) {
1195
                                        }
1196

    
1197
                                        dataStore = null;
1198
                                        render = null;
1199
                                        // System.gc();
1200
                                        this.setRemoveRasterFlag(true);
1201

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

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

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

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

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

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

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

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

    
1277
        /*
1278
         * (non-Javadoc)
1279
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getNoDataValue()
1280
         */
1281
        public double getNoDataValue() {
1282
                if (dataStore == null)
1283
                        return RasterLibrary.defaultNoDataValue;
1284
                return dataStore.getNoDataValue();
1285
        }
1286

    
1287
        /**
1288
         * Asigna el valor no data asociado a la capa
1289
         * @param nd
1290
         */
1291
        public void setNoDataValue(double nd) {
1292
                if (dataStore != null)
1293
                        dataStore.setNoDataValue(nd);
1294
        }
1295

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

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

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

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

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

    
1333
                return dataStore.getFileSizeByProvider();
1334
        }
1335

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

    
1343
                return dataStore.getURIByProvider();
1344
        }
1345

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

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

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

    
1380
        /*
1381
         * (non-Javadoc)
1382
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
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
         * (non-Javadoc)
1668
         * @see org.gvsig.raster.hierarchy.IRasterRendering#existsAlphaBand()
1669
         */
1670
        public boolean existsAlphaBand() {
1671
                if(dataStore.getColorInterpretation() != null)
1672
                        return dataStore.getColorInterpretation().isAlphaBand();
1673
                else
1674
                        return false;
1675
        }
1676

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

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

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

    
1704
                return null;
1705
        }
1706

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1859
                super.setVisible(visibility);
1860
        }
1861

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

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

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

    
1896
        /*
1897
         * (non-Javadoc)
1898
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getLastRenderBuffer()
1899
         */
1900
        public Buffer getLastRenderBuffer() {
1901
                return getRender().getLastRenderBuffer();
1902
        }
1903

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

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

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

    
1932
        /*
1933
         * (non-Javadoc)
1934
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getNoDataType()
1935
         */
1936
        public int getNoDataType() {
1937
                return noDataType;
1938
        }
1939

    
1940
        /*
1941
         * (non-Javadoc)
1942
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#setNoDataType(int)
1943
         */
1944
        public void setNoDataType(int noDataType) {
1945
                this.noDataType = noDataType;
1946
                if (dataStore != null)
1947
                        dataStore.setNoDataEnabled(noDataType != RasterLibrary.NODATATYPE_DISABLED);
1948
        }
1949

    
1950
        /**
1951
         * @return the configuration
1952
         */
1953
        static public IConfiguration getConfiguration() {
1954
                return configuration;
1955
        }
1956

    
1957
        /**
1958
         * @param configuration the configuration to set
1959
         */
1960
        static public void setConfiguration(IConfiguration configuration) {
1961
                DefaultFLyrRaster.configuration = configuration;
1962
        }
1963

    
1964
        /*
1965
         * (non-Javadoc)
1966
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#reload()
1967
         */
1968
        public void reload() throws ReloadLayerException {
1969
                try {
1970
                        super.reload();
1971
                        if (getMapContext() == null)
1972
                                return;
1973
                        if (isStopped())
1974
                                disableStopped();
1975
                        load();
1976
                        getMapContext().invalidate();
1977
                } catch (LoadLayerException e) {
1978
                        setAvailable(false);
1979
                        throw new ReloadLayerException(getName(), e);
1980
                }
1981
        }
1982

    
1983
        /**
1984
         * Devuelve si la capa tiene soporte para poder generar overviews
1985
         * @return
1986
         */
1987
        public boolean overviewsSupport() {
1988
                if ((dataStore != null) && (dataStore.overviewsSupport()))
1989
                        return true;
1990

    
1991
                return false;
1992
        }
1993

    
1994
        /**
1995
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1996
         * en escala de grises
1997
         * @return
1998
         */
1999
        public boolean isRenderingAsGray() {
2000
                int[] renderBands = getRender().getRenderBands();
2001
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
2002
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
2003
                        return true;
2004
                return false;
2005
        }
2006

    
2007
        /*
2008
         * (non-Javadoc)
2009
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
2010
         */
2011
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
2012
                updateDrawVersion();
2013
        }
2014

    
2015
        /*
2016
         * (non-Javadoc)
2017
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#adjustWorldRequest(java.awt.geom.Point2D)
2018
         */
2019
        public Point2D adjustWorldRequest(Point2D req) {
2020
                Envelope ext = null;
2021

    
2022
                ext = getFullEnvelope();
2023
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
2024
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
2025
                return req;
2026
        }
2027

    
2028
        /*
2029
         * (non-Javadoc)
2030
         * @see org.gvsig.fmap.mapcontext.layers.FLyrDefault#cloneLayer()
2031
         */
2032
        public FLayer cloneLayer() throws Exception {
2033
                RasterDataStore  ds = dataStore.cloneDataStore();
2034
                DefaultFLyrRaster newLayer = new DefaultFLyrRaster();
2035
                newLayer.setName(getName());
2036
                newLayer.setOpenRasterStore(ds);
2037
                newLayer.firstLoad = firstLoad;
2038
                
2039
                ArrayList<RasterFilter> filters = getRender().getFilterList().getStatusCloned();
2040

    
2041
                //Hacemos una copia de las bandas a renderizar
2042
                if(getRender().getRenderBands() != null) {
2043
                        int[] rb = new int[getRender().getRenderBands().length];
2044
                        for (int i = 0; i < rb.length; i++)
2045
                                rb[i] = getRender().getRenderBands()[i];
2046
                        newLayer.getRender().setRenderBands(rb);
2047
                }
2048

    
2049
                //Asignamos el entorno
2050
                if(newLayer.getRender().getFilterList() == null)
2051
                        newLayer.getRender().setFilterList(RasterLocator.getManager().createEmptyFilterList(getRender().getFilterList().getInitDataType()));
2052
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
2053
                newLayer.getRender().getFilterList().setStatus(filters);
2054

    
2055
                // Asignamos los valores noData del original
2056
                newLayer.setNoDataValue(getNoDataValue());
2057
                newLayer.setNoDataType(getNoDataType());
2058
                newLayer.applyNoData();
2059
                newLayer.enableOpen();
2060
                
2061
                return newLayer;
2062
        }
2063
        
2064
        /*
2065
         * (non-Javadoc)
2066
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getFileLayer()
2067
         */
2068
        public FLayer getFileLayer() throws RasterDriverException {
2069
                try {
2070
                        return cloneLayer();
2071
                } catch (Exception e) {
2072
                }
2073
                return null;
2074
        }
2075
        
2076
        /*
2077
         * (non-Javadoc)
2078
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#addFile(java.lang.String)
2079
         */
2080
        public void addFile(String file) throws InvalidSourceException {
2081
                getDataStore().addFile(file);
2082
        }
2083
        
2084
        /*
2085
         * (non-Javadoc)
2086
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#removeFile(java.lang.String)
2087
         */
2088
        public void removeFile(String file) {
2089
                getDataStore().removeFile(file);
2090
        }
2091

    
2092
        /*****************************************************/
2093

    
2094
        public void disableStopped() {state.disableStopped();}
2095

    
2096
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
2097

    
2098
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
2099

    
2100
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
2101

    
2102
        public void enableStopped() {state.enableStopped();}
2103

    
2104
        public boolean isAwake() {return state.isAwake();}
2105

    
2106
        public boolean isClosed() {return state.isClosed();}
2107

    
2108
        public boolean isOpen() {return state.isOpen();}
2109

    
2110
        public boolean isStopped() {return state.isStopped();}
2111

    
2112

    
2113
        @SuppressWarnings("unchecked")
2114
        public Set getMetadataChildren() {
2115
                return null;
2116
        }
2117

    
2118
        public Object getMetadataID() {
2119
                return getName();
2120
        }
2121

    
2122
        public String getMetadataName() {
2123
                return null;
2124
        }
2125

    
2126
        /*
2127
         * (non-Javadoc)
2128
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#getDataStore()
2129
         */
2130
        public RasterDataStore getDataStore() {
2131
                return this.dataStore;
2132
        }
2133

    
2134
        public void setOpenRasterStore(DataStore dataStore) throws LoadLayerException {
2135
                if(dataStore instanceof CoverageStoreProviderServices) {
2136
                        try {
2137
                                this.dataStore = rManager.open(((CoverageStoreProviderServices) dataStore).getProvider(), dataStore.getParameters());
2138
                        } catch (NotSupportedExtensionException e) {
2139
                                throw new LoadLayerException("Extension not supported", e);
2140
                        } catch (RasterDriverException e) {
2141
                                throw new LoadLayerException("Error opening the DataStore", e);
2142
                        }
2143
                } else
2144
                        this.dataStore = (RasterDataStore) dataStore;
2145
                try {
2146
                        enableAwake();
2147
                } catch (NotAvailableStateException e) {
2148
                        throw new LoadLayerException("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
2149
                }
2150
                setProjection(this.dataStore.getProjection());
2151
        }
2152
        
2153
        /*
2154
         * (non-Javadoc)
2155
         * @see org.gvsig.fmap.mapcontext.layers.operations.SingleLayer#setDataStore(org.gvsig.fmap.dal.DataStore)
2156
         */
2157
        public void setDataStore(DataStore dataStore) throws LoadLayerException {
2158
                setOpenRasterStore(dataStore);
2159
                load();
2160
        }
2161
        
2162
        /*
2163
         * (non-Javadoc)
2164
         * @see org.gvsig.raster.fmap.layers.FLyrRaster#isRemote()
2165
         */
2166
        public boolean isRemote() {
2167
                return false;
2168
        }
2169
        
2170
        /**
2171
         * Returns true if exists a process reading data from this layer
2172
         * @return
2173
         */
2174
        public boolean isReadingData() {
2175
                return readingData != null;
2176
        }
2177

    
2178
        /**
2179
         * When a process is using information of this layer this variable will contain
2180
         * the thread ID.
2181
         * @param readingData
2182
         */
2183
        public synchronized void setReadingData(String readingData) {
2184
                this.readingData = readingData;
2185
        }
2186
        
2187
        public DynObjectSet getInfo(org.gvsig.fmap.geom.primitive.Point p, double tolerance)
2188
                        throws LoadLayerException, DataException {
2189
                return null;
2190
        }
2191

    
2192
        public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel)
2193
                        throws LoadLayerException, DataException {
2194
                return null;
2195
        }
2196

    
2197
        @Override
2198
        protected void doDispose() throws BaseException {
2199
                // Nothing to do
2200
        }
2201

    
2202
        @Override
2203
        public void loadFromState(PersistentState state)
2204
                        throws PersistenceException {
2205
                super.loadFromState(state);
2206
                
2207
                String fileName = state.getString("file");
2208
                if (fileName != null){                        
2209
                        ProviderServices provServ = RasterLocator.getManager().getProviderServices();
2210
                        RasterDataParameters params = provServ.createParameters(fileName);
2211
                        params.setURI(fileName);
2212
                }
2213
                
2214
                status = (IStatusRaster)state.get("status");
2215
                status.setStateProperties(true, this);
2216
                
2217
                render = (Render)state.get("render");
2218
        }
2219

    
2220
        @Override
2221
        public void saveToState(PersistentState state) throws PersistenceException {
2222
                super.saveToState(state);
2223
                
2224
//                if(isClosed() || isAwake())
2225
//                        return;
2226
                
2227
                if(getFile() != null){
2228
                        state.set("file", getFile().toString());
2229
                }                
2230

    
2231
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
2232
                if (status == null)
2233
                        status = new StatusLayerRaster();
2234
                
2235
                state.set("render", render);                
2236
                
2237
                status.setStateProperties(true, this);
2238
                state.set("status", status);                                
2239
        }        
2240
        
2241
        public static void registerPersistent() {
2242
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
2243
                DynStruct definition = manager.getDefinition(PERSISTENT_NAME);
2244
                if( definition == null ) {
2245
                        definition = manager.addDefinition(
2246
                                        DefaultFLyrRaster.class,
2247
                                        PERSISTENT_NAME,
2248
                                        PERSISTENT_DESCRIPTION,
2249
                                        null, 
2250
                                        null
2251
                        );
2252
                        definition.addDynFieldString("file").setMandatory(false);
2253
                        definition.addDynFieldString("driverName").setMandatory(true);
2254
                        definition.addDynFieldString("render").setMandatory(false);
2255
                }
2256
        }
2257
        
2258
        /*
2259
         * (non-Javadoc)
2260
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#getZoomLevel()
2261
         */
2262
        public int getZoomLevel() {
2263
                return zoomLevel;
2264
        }
2265

    
2266
        /*
2267
         * (non-Javadoc)
2268
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#setZoomLevel(int)
2269
         */
2270
        public void setZoomLevel(int zoomLevel) {
2271
                this.zoomLevel = zoomLevel;
2272
        }
2273
        
2274
        /*
2275
         * (non-Javadoc)
2276
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#increaseZoomLevel()
2277
         */
2278
        public boolean increaseZoomLevel() {
2279
                if(zoomLevel < (this.dataStore.getZoomLevels() - 1)) { 
2280
                        zoomLevel ++;
2281
                        recalcLevel = false;
2282
                        return true;
2283
                }
2284
                return false;
2285
        }
2286
        
2287
        /*
2288
         * (non-Javadoc)
2289
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#decreaseZoomLevel()
2290
         */
2291
        public boolean decreaseZoomLevel() {
2292
                if(zoomLevel > 0) { 
2293
                        zoomLevel --;
2294
                        recalcLevel = false;
2295
                        return true;
2296
                }
2297
                return false;
2298
        }
2299
        
2300
        /*
2301
         * (non-Javadoc)
2302
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#getCoordsInLevel(java.awt.geom.Point2D, int, int, int)
2303
         */
2304
        public Envelope getCoordsInLevel(Point2D center, int level, int w, int h) throws CreateEnvelopeException {
2305
                Extent ex = getDataStore().getCoordsInLevel(center, level, w, h);
2306
                return geomManager.createEnvelope(ex.getULX(), ex.getULY(), ex.getLRX(), ex.getLRY(), SUBTYPES.GEOM2D);
2307
        }
2308
        
2309
        /*
2310
         * (non-Javadoc)
2311
         * @see org.gvsig.fmap.mapcontext.layers.Multiresolution#isEnabledMultiresolution()
2312
         */
2313
        public boolean isEnabledMultiresolution() {
2314
                return dataStore.isTiled();
2315
        }
2316
        
2317
        /*
2318
         * (non-Javadoc)
2319
         * @see org.gvsig.raster.fmap.layers.Multiresolution#setTileServer(java.lang.Class)
2320
         */
2321
        public void setTileServer(Class<?> tileServer) {
2322
                dataStore.setTileServer(tileServer);
2323
        }
2324
}