Statistics
| Revision:

root / trunk / extensions / extRasterTools-SE / src / org / gvsig / fmap / raster / layers / FLyrRasterSE.java @ 33261

History | View | Annotate | Download (65.8 KB)

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

    
41
import javax.print.attribute.PrintRequestAttributeSet;
42
import javax.swing.ImageIcon;
43

    
44
import org.cresques.cts.IProjection;
45
import org.gvsig.fmap.raster.legend.ColorTableLegend;
46
import org.gvsig.raster.FileNotFoundSolve;
47
import org.gvsig.raster.RasterLibrary;
48
import org.gvsig.raster.buffer.BufferFactory;
49
import org.gvsig.raster.dataset.CompositeDataset;
50
import org.gvsig.raster.dataset.FileNotOpenException;
51
import org.gvsig.raster.dataset.IBuffer;
52
import org.gvsig.raster.dataset.IRasterDataSource;
53
import org.gvsig.raster.dataset.InvalidSetViewException;
54
import org.gvsig.raster.dataset.MosaicNotValidException;
55
import org.gvsig.raster.dataset.MultiRasterDataset;
56
import org.gvsig.raster.dataset.NotSupportedExtensionException;
57
import org.gvsig.raster.dataset.RasterDataset;
58
import org.gvsig.raster.dataset.io.RasterDriverException;
59
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
60
import org.gvsig.raster.dataset.properties.DatasetMetadata;
61
import org.gvsig.raster.dataset.serializer.RmfSerializerException;
62
import org.gvsig.raster.datastruct.ColorTable;
63
import org.gvsig.raster.datastruct.Extent;
64
import org.gvsig.raster.datastruct.ViewPortData;
65
import org.gvsig.raster.datastruct.persistence.ColorTableLibraryPersistence;
66
import org.gvsig.raster.grid.Grid;
67
import org.gvsig.raster.grid.GridException;
68
import org.gvsig.raster.grid.GridPalette;
69
import org.gvsig.raster.grid.GridTransparency;
70
import org.gvsig.raster.grid.filter.FilterTypeException;
71
import org.gvsig.raster.grid.filter.RasterFilterList;
72
import org.gvsig.raster.grid.filter.RasterFilterListManager;
73
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
74
import org.gvsig.raster.grid.filter.enhancement.EnhancementStretchListManager;
75
import org.gvsig.raster.grid.filter.enhancement.LinearStretchParams;
76
import org.gvsig.raster.grid.render.Rendering;
77
import org.gvsig.raster.grid.render.VisualPropertyEvent;
78
import org.gvsig.raster.grid.render.VisualPropertyListener;
79
import org.gvsig.raster.hierarchy.IRasterDataset;
80
import org.gvsig.raster.hierarchy.IRasterOperations;
81
import org.gvsig.raster.hierarchy.IRasterProperties;
82
import org.gvsig.raster.hierarchy.IStatistics;
83
import org.gvsig.raster.process.RasterTask;
84
import org.gvsig.raster.process.RasterTaskQueue;
85
import org.gvsig.raster.projection.CRS;
86
import org.gvsig.raster.util.ColorConversion;
87
import org.gvsig.raster.util.Historical;
88
import org.gvsig.raster.util.MathUtils;
89
import org.gvsig.raster.util.RasterToolsUtil;
90
import org.gvsig.tools.file.PathGenerator;
91

    
92
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
93
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
94
import com.iver.cit.gvsig.exceptions.layers.ReloadLayerException;
95
import com.iver.cit.gvsig.fmap.ViewPort;
96
import com.iver.cit.gvsig.fmap.core.FShape;
97
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
98
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
99
import com.iver.cit.gvsig.fmap.layers.FLayer;
100
import com.iver.cit.gvsig.fmap.layers.FLyrDefault;
101
import com.iver.cit.gvsig.fmap.layers.LayerChangeSupport;
102
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
103
import com.iver.cit.gvsig.fmap.layers.LayerListener;
104
import com.iver.cit.gvsig.fmap.layers.Tiling;
105
import com.iver.cit.gvsig.fmap.layers.XMLException;
106
import com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable;
107
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
108
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
109
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
110
import com.iver.cit.gvsig.fmap.rendering.ILegend;
111
import com.iver.cit.gvsig.fmap.rendering.LegendListener;
112
import com.iver.utiles.FileUtils;
113
import com.iver.utiles.NotExistInXMLEntity;
114
import com.iver.utiles.XMLEntity;
115
import com.iver.utiles.swing.threads.Cancellable;
116
/**
117
 * Capa raster
118
 * @author Nacho Brodin (nachobrodin@gmail.com)
119
 */
120
public class FLyrRasterSE extends FLyrDefault implements IRasterProperties, IRasterDataset, InfoByPoint, Classifiable, IRasterOperations, IRasterLayerActions, ILayerState, VisualPropertyListener {
121
        private boolean               mustTileDraw        = false;
122
        private boolean               mustTilePrint       = true;
123
        private int                   maxTileDrawWidth    = 200;
124
        private int                   maxTileDrawHeight   = 200;
125
        private int                   maxTilePrintWidth   = 1500;
126
        private int                   maxTilePrintHeight  = 1500;
127
        protected IStatusRaster       status              = null;
128
        private boolean               firstLoad           = false;
129
        private boolean               removeRasterFlag    = true;
130
        private Object                params              = null;
131
        protected IRasterDataSource   dataset             = null;
132
        protected Rendering           render              = null;
133
        protected BufferFactory       bufferFactory       = null;
134
        private int                   posX                = 0;
135
        private int                   posY                = 0;
136
        private double                posXWC              = 0;
137
        private int                   posYWC              = 0;
138
        private int                   r                   = 0;
139
        private int                   g                   = 0;
140
        private int                   b                   = 0;
141
        private LayerChangeSupport    layerChangeSupport  = new LayerChangeSupport();
142
        private FLyrState             state               = new FLyrState();
143
        private ArrayList             filterArguments     = null;
144
        protected ILegend             lastLegend          = null;
145
        protected ColorTable          loadedFromProject   = null;
146
        private ArrayList             rois                = null;
147
        private RasterDrawStrategy    strategy            = null;
148
        static private IConfiguration configuration       = new DefaultLayerConfiguration();
149
        
150
        private BufferedImage         image               = null;
151
        private static Hashtable<Class, ISolveErrorListener> 
152
                                      solveListeners      = new Hashtable<Class, ISolveErrorListener>();
153

    
154
        /**
155
         * Tipo de valor no data asociado a la capa.
156
         * Sirve para diferenciar los estados seleccionados por el usuario. Siendo
157
         * estos 'Sin Valor NoData', 'NoData de Capa'(Por defecto) y 'Personalizado'
158
         */
159
        private int                   noDataType          = RasterLibrary.NODATATYPE_LAYER;
160

    
161
        /**
162
         * Lista de transformaciones afines que son aplicadas. Esta lista es
163
         * simplemente un historico que no se utiliza. Es posible utilizarlo para
164
         * recuperar transformaciones anteriores.
165
         */
166
        private Historical            affineTransformList   = new Historical();
167
        private boolean               loadingFromProject    = false;
168
        
169
        protected String              readingData           = null;
170

    
171
        private static PathGenerator pathGenerator=PathGenerator.getInstance();
172
        
173
        static {
174
                 RasterLibrary.wakeUp();
175
                 //TODO: Problema de dependencia entre appgvSIG y libFMap. La resoluci?n de errores en la ruta de las capas deber?a ser un mecanismo general.
176
                 FLyrRasterSE.addSolveErrorForLayer(NotSupportedExtensionException.class, new FileNotFoundSolve());
177
        }
178

    
179
        /**
180
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
181
         * @param layerName Nombre de la capa..
182
         * @param params Par?metros de carga del formato. El caso m?s simple es la ruta de la capa en disco.
183
         * @param d RasterDriver.
184
         * @param f Fichero.
185
         * @param proj Proyecci?n.
186
         * @return Nueva capa de tipo raster.
187
         * @throws DriverIOException
188
         */
189
        public static FLyrRasterSE createLayer(String layerName, Object params,
190
                        IProjection proj) throws LoadLayerException {
191
                FLyrRasterSE capa = new FLyrRasterSE();
192
                capa.setLoadParams(params);
193
                capa.setName(layerName);
194
                capa.setProjection(proj);
195
                capa.load();
196
                return capa;
197
        }
198

    
199
        private static FLyrRasterSE tryToSolveError(Exception e, FLayer layer) {
200
                ISolveErrorListener sel = solveListeners.get(e.getClass());
201
                if (sel != null) {
202
                        FLyrRasterSE solvedLayer = null;
203
                        solvedLayer = (FLyrRasterSE)sel.solve(layer, null);
204
                        if (solvedLayer != null && sel != null){
205
                                return solvedLayer;
206
                        }
207
                }
208
                layer.setAvailable(false);
209
                return (FLyrRasterSE)layer;
210
        }
211
        
212
        /**
213
         * A?ade un gestor de errores en la carga de la capa
214
         * @param exception
215
         * @param sel
216
         */
217
        public static void addSolveErrorForLayer(Class exception, ISolveErrorListener sel) {
218
                solveListeners.put(exception, sel);
219
        }
220
        
221
        /**
222
         * Asigna los par?metros para la carga de la capa
223
         * @param param Par?metros.
224
         */
225
        public void setLoadParams(Object param){
226
                this.params = param;
227

    
228
                //Si la capa tiene nombre acivamos el estado awake
229
                if(params != null && getName() != null) {
230
                        try {
231
                                enableAwake();
232
                        } catch (NotAvailableStateException e) {
233
                                RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
234
                        }
235
                }
236
        }
237

    
238
        /**
239
         * Obtiene los par?metros para la carga de la capa
240
         * @return param Par?metros.
241
         */
242
        public Object getLoadParams() {
243
                return params;
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(getLoadParams() != null && name != null) {
255
                        try {
256
                                if(isClosed())
257
                                        enableAwake();
258
                        } catch (NotAvailableStateException e) {
259
                                RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
260
                        }
261
                }
262
        }
263

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

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

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

    
294
        /*
295
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
296
         */
297
        public void load() throws LoadLayerException {
298
                if (isStopped())
299
                        return;
300

    
301
                enableStopped(); // Paramos la capa mientras se hace un load
302

    
303
                String fName = null;
304
                int test = -1;
305
                if (params != null && params instanceof File) {
306
                        fName = ((File) params).getAbsolutePath();
307
                        test = fName.indexOf("ecwp:");
308
                }
309

    
310
                if (test != -1) {
311
                        String urlECW = fName.substring(test + 6);
312
                        fName = "ecwp://" + urlECW;
313
                        System.err.println(test + " " + fName);
314
                }
315

    
316
                try {
317
                        if (params instanceof String[][]) {
318
                                String[][] files = (String[][]) params;
319
                                MultiRasterDataset[][] dt = new MultiRasterDataset[files.length][files[0].length];
320
                                for (int i = 0; i < files.length; i++)
321
                                        for (int j = 0; j < files[i].length; j++)
322
                                                dt[i][j] = MultiRasterDataset.open(getProjection(), files[i][j]);
323
                                dataset = new CompositeDataset(dt);
324
                        } else
325
                                if (params == null || params instanceof File) {
326
                                        if (fName != null)
327
                                                dataset = MultiRasterDataset.open(getProjection(), fName);
328
                                } else
329
                                        dataset = MultiRasterDataset.open(getProjection(), params);
330
                } catch (NotSupportedExtensionException e) {
331
                        if(test == -1 && loadingFromProject) { 
332
                                FLyrRasterSE lyr = tryToSolveError(e, this);
333
                                if(lyr != null)
334
                                        dataset = lyr.getDataSource();
335
                                else
336
                                        throw new LoadLayerException("Formato no valido", e);
337
                        } else
338
                                throw new LoadLayerException("Formato no valido", e);
339
                } catch (MosaicNotValidException e) {
340
                        throw new LoadLayerException("Error en el mosaico", e);
341
                } catch (Exception e) {
342
                        throw new LoadLayerException("No existe la capa.", e);
343
                }
344
                if (dataset != null)
345
                        this.init();
346
        }
347

    
348
        /**
349
         * Acciones de inicializaci?n despu?s de que la fuente de datos
350
         * de la capa est? asignada. El tipo de fuente de datos es variable
351
         * puede ser MultiRasterDataset, CompositeDataset u otras que existan e
352
         * implementen IRasterDatasource.
353
         */
354
        public void init() throws LoadLayerException {
355
                if (dataset == null)
356
                        throw new LoadLayerException("Formato no valido", new IOException());
357
                                
358
                bufferFactory = new BufferFactory(dataset);
359
                render = new Rendering(bufferFactory);
360
                render.addVisualPropertyListener(this);
361
                initFilters();
362

    
363
                //Inicializaci?n del historico de transformaciones
364
                affineTransformList.clear();
365
                affineTransformList.add(this.getAffineTransform());
366

    
367
                try {
368
                        enableOpen();
369
                } catch (NotAvailableStateException e) {
370
                        RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Awake=" + isAwake(), this, e);
371
                }
372
        }
373

    
374
        /**
375
         * Obtiene la proyecci?n del fichero.
376
         * @return IProjection
377
         */
378
        public IProjection readProjection() {
379
                try {
380
                        CRS.setCRSFactory(CRSFactory.cp);
381
                        if( dataset == null )
382
                                return null;
383
                        return CRS.convertWktToIProjection(dataset.getWktProjection());
384
                } catch (RasterDriverException e) {
385
                        RasterToolsUtil.messageBoxError("Problemas accediendo a getWktProjection. Driver no inicializado", this, e);
386
                }
387
                return null;
388
        }
389
        
390
        /**
391
         * Crea el objeto renderizador de raster
392
         * @return Rendering
393
         */
394
        public Rendering getRender() {
395
                if (render == null) {
396
                        render = new Rendering(bufferFactory);
397
                        render.addVisualPropertyListener(this);
398
                }
399
                return render;
400
        }
401
        
402
        /**
403
         * Aplica los filtros noData al layer
404
         * @param rasterSE
405
         * @param filterManager
406
         */
407
        public void applyNoData() {
408
                Boolean noDataEnabled = configuration.getValueBoolean("nodata_transparency_enabled", Boolean.FALSE);
409
                if (noDataEnabled.booleanValue() && getDataSource().isNoDataEnabled()) {
410
                        noDataType = RasterLibrary.NODATATYPE_LAYER;
411
                        Double noDataValue = Double.valueOf(getNoDataValue());
412
                        getDataSource().getTransparencyFilesStatus().setNoData(noDataValue.doubleValue());
413
                } else {
414
                        if(getDataSource() != null && getDataSource().getTransparencyFilesStatus() != null)
415
                                getDataSource().getTransparencyFilesStatus().activeNoData(false);
416
                        noDataType = RasterLibrary.NODATATYPE_DISABLED;
417
                }
418
        }
419

    
420
        /**
421
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
422
         */
423
        private void initFilters() {
424
                RasterFilterList filterList = new RasterFilterList();
425
                filterList.addEnvParam("IStatistics", getDataSource().getStatistics());
426
                filterList.addEnvParam("MultiRasterDataset", getDataSource());
427
                
428
                if(getDataSource() == null)
429
                        return;
430
                
431
                getDataSource().resetNoDataValue();
432
                applyNoData();
433
                GridTransparency gridTransparency = new GridTransparency(getDataSource().getTransparencyFilesStatus());
434

    
435
                filterList.setInitDataType(getDataType()[0]);
436
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
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
                                GridPalette p = new GridPalette(loadedFromProject);
445
                                setLastLegend(p);
446
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
447
                                ctm.addColorTableFilter(p);
448
                        } else {
449
                                //sino ponemos la tabla asociada al raster
450
                                if (this.getDataSource().getColorTables()[0] != null) {
451
                                        GridPalette p = new GridPalette(getDataSource().getColorTables()[0]);
452
                                        setLastLegend(p);
453
                                        ColorTableListManager ctm = new ColorTableListManager(filterManager);
454
                                        ctm.addColorTableFilter(p);
455
                                } else {
456
                                        //sino hace lo que dice en las preferencias
457
                                        if (getDataType()[0] != IBuffer.TYPE_BYTE) 
458
                                                loadEnhancedOrColorTable(filterManager);
459

    
460
                                }
461
                        }
462
                        loadedFromProject = null;
463

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

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

    
482
                String palettesPath = FileUtils.getAppHomeDir() + "colortable";
483

    
484
                IStatistics stats = getDataSource().getStatistics();
485

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

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

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

    
505
                                                        GridPalette p = new GridPalette(colorTable);
506
                                                        setLastLegend(p);
507

    
508
                                                        ColorTableListManager ctm = new ColorTableListManager(filterManager);
509
                                                        ctm.addColorTableFilter(p);
510
                                                        return;
511
                                                }
512
                                        }
513
                                }
514
                        } catch (FileNotOpenException e) {
515
                                // No podemos aplicar el filtro
516
                        } catch (RasterDriverException e) {
517
                                // No podemos aplicar el filtro
518
                        } catch (InterruptedException e) {
519
                                // El usuario ha cancelado el proceso
520
                        }
521
                }
522

    
523
                /*EnhancementListManager elm = new EnhancementListManager(filterManager);
524
                elm.addEnhancedFilter(false, stats, 0.0, getRender().getRenderBands());*/
525
                
526
                EnhancementStretchListManager elm = new EnhancementStretchListManager(filterManager);
527
                try {
528
                        elm.addEnhancedStretchFilter(LinearStretchParams.createStandardParam(getRenderBands(), 0.0, stats, false), 
529
                                                                                stats, 
530
                                                                                getRender().getRenderBands(), 
531
                                                                                false);
532
                } catch (FileNotOpenException e) {
533
                        //No podemos aplicar el filtro
534
                } catch (RasterDriverException e) {
535
                        //No podemos aplicar el filtro
536
                }
537
        }
538

    
539
        /**
540
         * Devuelve si es reproyectable o no la capa
541
         * @return
542
         */
543
        public boolean isReproyectable() {
544
                if (dataset == null)
545
                        return false;
546

    
547
                int nFiles = dataset.getDatasetCount();
548
                for (int i = 0; i < nFiles; i++)
549
                        if (!dataset.getDataset(i)[0].isReproyectable())
550
                                return false;
551
                return true;
552
        }
553
        
554
        /**
555
         * @throws ReadDriverException
556
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
557
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
558
         *                 com.iver.utiles.swing.threads.Cancellable)
559
         */
560
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadDriverException {
561
                this.image = image;
562
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
563
                
564
                task.setEvent(null);
565

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

    
570
                        enableStopped();
571
                        // callLegendChanged(null);
572

    
573
                        strategy = new RasterDrawStrategy(getMapContext(), this);
574
                        strategy.stackStrategy();
575
                        HashMap tStr = strategy.getStrategy();
576
                        if (tStr != null && 
577
                                tStr.get(this) != null && 
578
                                ((Boolean) (tStr.get(this))).booleanValue() == false) {
579
                                disableStopped();
580
                                return;
581
                        }
582

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

    
631
                                if (mustTileDraw) {
632
                                        Point2D p = vp.getOffset();
633
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
634
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
635
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
636
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
637
                                                // drawing part
638
                                                try {
639
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
640
                                                        draw(image, g, vport, cancel);
641
                                                } catch (RasterDriverException e) {
642
                                                        throw new ReadDriverException("", e);
643
                                                } catch (InvalidSetViewException e) {
644
                                                        throw new ReadDriverException("Error al asignar la vista en el draw.", e);
645
                                                } catch (InterruptedException e) {
646
                                                        System.out.println("Se ha cancelado el pintado");
647
//                                                        throw new ReadDriverException("Dibujado interrumpido.", e);
648
                                                } catch (NoninvertibleTransformException e) {
649
                                                        throw new ReadDriverException("Error en la transformaci?n", e);
650
                                                }
651
                                        }
652
                                } else {
653
                                        try {
654
                                                draw(image, g, vp, cancel);
655
                                        } catch (RasterDriverException e) {
656
                                                throw new ReadDriverException("", e);
657
                                        } catch (InvalidSetViewException e) {
658
                                                throw new ReadDriverException("Error al asignar la vista en el draw.", e);
659
                                        } catch (InterruptedException e) {
660
                                                System.out.println("Se ha cancelado el pintado");
661
//                                        throw new ReadDriverException("Dibujado interrumpido.", e);
662
                                        }
663
                                }
664

    
665
                        }
666
                        //callLegendChanged(null);
667
                } finally {
668
                        disableStopped();
669
                        //task.setEvent(null);
670
                }
671
                
672
                /*Runtime r = Runtime.getRuntime();
673
                System.err.println("********************FLyrRaster***************");
674
                System.err.println("Memoria Total: " + (r.totalMemory() / 1024) +"KB");
675
                System.err.println("Memoria Usada: " + ((r.totalMemory() - r.freeMemory()) / 1024) +"KB");
676
                System.err.println("Memoria Libre: " + (r.freeMemory() / 1024) +"KB");
677
                System.err.println("Memoria MaxMemory: " + (r.maxMemory() / 1024) +"KB");
678
                System.err.println("*********************************************");*/
679
        }
680

    
681
        private void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws RasterDriverException, InvalidSetViewException, InterruptedException {
682
                Rectangle2D adjustedExtent = vp.getAdjustedExtent();
683
                if (adjustedExtent == null) return;
684
                Extent e = new Extent(adjustedExtent);
685
                Dimension imgSz = vp.getImageSize();
686
                ViewPortData vp2 = new ViewPortData(vp.getProjection(), e, imgSz );
687
                vp2.setMat(vp.getAffineTransform());
688
                getRender().draw(g, vp2);
689
        }
690

    
691
        /**
692
         * Inserta la proyecci?n.
693
         *
694
         * @param proj Proyecci?n.
695
         */
696
        public void setProjection(IProjection proj) {
697
                super.setProjection(proj);
698
        }
699

    
700
        /*
701
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
702
         */
703
        public Rectangle2D getFullExtent() {
704
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
705
                //un extent aunque la capa no est? abierta
706
                if(/*!isOpen() || */dataset == null || dataset.getExtent() == null)
707
                        return null;
708
                return dataset.getExtent().toRectangle2D();
709
        }
710

    
711
        /**
712
         * Obtiene el valor del pixel del Image en la posici?n x,y
713
         * @param x Posici?n x
714
         * @param y Posici?n y
715
         * @return valor de pixel
716
         */
717
        public int[] getPixel(int pxx, int pxy) {
718
                int[] argb = { -1, -1, -1, -1 };
719
                if (!isOpen() || (image == null))
720
                        return argb;
721
                if (pxx >= 0 && pxx < image.getWidth() && pxy >= 0 && pxy < image.getHeight()) {
722
                        int value = image.getRGB(pxx, pxy);
723
                        argb[0] = ((value & 0xff000000) >> 24);
724
                        argb[1] = ((value & 0x00ff0000) >> 16);
725
                        argb[2] = ((value & 0x0000ff00) >> 8);
726
                        argb[3] = (value & 0x000000ff);
727
                }
728
                return argb;
729
        }
730

    
731
        /*
732
         * (non-Javadoc)
733
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
734
         */
735
        public double getMaxX() {
736
                if(getFullExtent() != null)
737
                        return getFullExtent().getMaxX();
738
                return -1;
739
        }
740

    
741
        /*
742
         * (non-Javadoc)
743
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
744
         */
745
        public double getMaxY() {
746
                if(getFullExtent() != null)
747
                        return this.getFullExtent().getMaxY();
748
                return -1;
749
        }
750

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

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

    
771
        /* (non-Javadoc)
772
         * @deprecated. See String getInfo(Point p) throws DriverException
773
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
774
         */
775
        public String queryByPoint(Point p) {
776
                if (!isOpen())
777
                        return null;
778
                ColorConversion conv = new ColorConversion();
779

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

    
782
                ArrayList attr = getAttributes();
783
                data += "  <raster\n";
784
                data += "    File=\"" + getFile() + "\"\n";
785
                for (int i = 0; i < attr.size(); i++) {
786
                        Object[] a = (Object[]) attr.get(i);
787

    
788
                        data += "    " + a[0].toString() + "=";
789
                        if (a[1].toString() instanceof String)
790
                                data += "\"" + a[1].toString() + "\"\n";
791
                        else
792
                                data += a[1].toString() + "\n";
793
                }
794
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
795
                data += "    Point_WC=\"" + MathUtils.format(posXWC, 3) + " , " + MathUtils.format(posYWC, 3) + "\"\n";
796
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
797
                double[] cmyk = conv.RGBtoCMYK(r & 0xff, g & 0xff, b & 0xff, 1D);
798
                data += "    CMYK=\"" + MathUtils.format(cmyk[0], 4) + ", " + MathUtils.format(cmyk[1], 4) + ", " + MathUtils.format(cmyk[2], 4) + "," + MathUtils.format(cmyk[3], 4) + "\"\n";
799
                double[] hsl = conv.RGBtoHSL(r & 0xff, g & 0xff, b & 0xff);
800
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
801
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
802
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
803
                data += "    HSL=\"" + MathUtils.format(hsl[0], 4) + ", " + MathUtils.format(hsl[1], 4) + ", " + MathUtils.format(hsl[2], 4) + "\"\n";
804
                data += "  />\n";
805

    
806
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
807
                return data;
808
        }
809

    
810
        /**
811
         * Transforma un punto real a coordenadas pixel indicando la banda que es usada para la
812
         * transformaci?n. Hay que tener en cuenta que es posible que todas las transformaciones no 
813
         * sean iguales en todas la bandas porque puede haber bandas de distinta resoluci?n.
814
         * 
815
         * @param numberBand
816
         * @param pReal
817
         * @return
818
         * @throws ReadDriverException
819
         */
820
        private Point2D transformPoint(int numberBand, Point2D pReal) throws ReadDriverException {
821
                AffineTransform at = this.getDataSource().getAffineTransform(numberBand);
822
                Point2D px = new Point2D.Double();
823
                //px = new Point2D.Double(pReal.getX(), pReal.getY());
824
                try {
825
                        at.inverseTransform(pReal, px);
826
                        return px;
827
                } catch (NoninvertibleTransformException e) {
828
                        throw new ReadDriverException("Error en la transformaci?n del punto", e);
829
                }
830
        }
831
        
832
        /*
833
         * (non-Javadoc)
834
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo(java.awt.Point, double, com.iver.utiles.swing.threads.Cancellable)
835
         */
836
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException {
837
                if (!isOpen()) {
838
                        StringXMLItem[] item = new StringXMLItem[1];
839
                        String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
840
                        data += "  <raster\n" + "  Layer=\" Not available\"\n" + "  />\n";
841
                        data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
842
                        item[0] = new StringXMLItem(data, this);
843
                        return item;
844
                }
845

    
846
                Point2D pReal = getMapContext().getViewPort().toMapPoint(p);
847
                Point2D px = new Point2D.Double();
848
                if(        pReal.getX() > this.getMinX() &&
849
                        pReal.getX() < this.getMaxX() &&
850
                        pReal.getY() > this.getMinY() &&
851
                        pReal.getY() < this.getMaxY()) {
852

    
853
                        px = transformPoint(0, pReal);
854
                }
855
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
856
                ColorConversion conv = new ColorConversion();
857

    
858
                StringXMLItem[] item = new StringXMLItem[1];
859
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
860

    
861
                data += "  <raster\n";
862
                data += "    View_Point=\"" + p.getX() + " , " + p.getY() + "\"\n";
863
                data += "    World_Point=\"" + MathUtils.format(pReal.getX(), 3) + " , " + MathUtils.format(pReal.getY(), 3) + "\"\n";
864
                if (px == null)
865
                        data += "    Pixel_Point=\"Out\"\n";
866
                else
867
                        data += "    Pixel_Point=\"" + (int) px.getX() + " , " + (int) px.getY() + "\"\n";
868
                if(getDataType()[0] != IBuffer.TYPE_BYTE)
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
                                                        int val = ((Integer)getDataSource().getData((int)pxAux.getX(), (int)pxAux.getY(), i)).intValue();
885
                                                        if(getDataType()[0] == IBuffer.TYPE_BYTE)
886
                                                                data += (val & 0x000000ff) + "  ";
887
                                                        else
888
                                                                data += val + "  ";
889
                                                }
890
                                        }
891
                                }
892
                                if(getDataType()[0] == 4){
893
                                        for(int i = 0; i < getBandCount(); i++) {
894
                                                if(getDataSource().isInside(pReal)) {
895
                                                        Point2D pxAux = transformPoint(i, pReal);
896
                                                        data += ((Float)getDataSource().getData((int)pxAux.getX(), (int)pxAux.getY(), i)).floatValue() + "  ";
897
                                                }
898
                                        }
899
                                }
900
                                if(getDataType()[0] == 5){
901
                                        for(int i = 0; i < getBandCount(); i++) {
902
                                                if(getDataSource().isInside(pReal)) {
903
                                                        Point2D pxAux = transformPoint(i, pReal);
904
                                                        data += ((Double)getDataSource().getData((int)pxAux.getX(), (int)pxAux.getY(), i)).doubleValue() + "  ";
905
                                                }
906
                                        }
907
                                }
908
                        }
909
                } catch (RasterDriverException ex) {
910
                        throw new ReadDriverException("Error en el acceso al dataset", ex);
911
                } catch (InvalidSetViewException ex) {
912
                        throw new ReadDriverException("Error en la asignaci?n de la vista en getData", ex);
913
                } catch (FileNotOpenException ex) {
914
                        throw new ReadDriverException("Fichero no abierto en el dataset", ex);
915
                } catch (InterruptedException e) {
916
                }
917
                data += "\"\n";
918
                data += "  />\n";
919
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
920

    
921
                item[0] = new StringXMLItem(data, this);
922
                return item;
923
        }
924

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

    
935
        /**
936
         * Obtiene atributos a partir de un georasterfile
937
         * @return
938
         */
939
        public ArrayList getAttributes() {
940
                ArrayList attr = new ArrayList();
941
                if(!isOpen())
942
                        return attr;
943
                Object [][] a = {
944
                        {"Filename", dataset.getDataset(0)[0].getFName()},
945
                        {"Filesize", new Long(dataset.getFileSize())},
946
                        {"Width", new Integer((int)dataset.getWidth())},
947
                        {"Height", new Integer((int)dataset.getHeight())},
948
                        {"Bands", new Integer(dataset.getBandCount())}
949
                };
950
                for (int i = 0; i < a.length; i++)
951
                        attr.add(a[i]);
952
                return attr;
953
        }
954

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

    
964
                return getXMLEntityWithoutChecks();
965
        }
966
        
967
        /**
968
         * This method has been added because a WMS server could be not running
969
         * where the project is loaded, but it doesn't mean that the layer
970
         * can not be loaded.
971
         * @return
972
         * @throws XMLException
973
         */
974
        public XMLEntity getXMLEntityWithoutChecks() throws XMLException {
975
                XMLEntity xml = super.getXMLEntity();
976
                if(getFile() != null)
977
                        xml.putProperty("file", pathGenerator.getPath(getFile().getAbsolutePath()));
978
                xml.putProperty("driverName", "gvSIG Raster Driver");
979

    
980
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
981
                if (status == null)
982
                        status = new StatusLayerRaster();
983
                status.getXMLEntity(xml, true, this);
984

    
985
                return xml;
986
        }
987

    
988
        public void setXMLEntity03(XMLEntity xml) throws XMLException {
989
        }
990

    
991
        /**
992
         * Recupera de disco los datos de la capa.
993
         */
994
        public void setXMLEntity(XMLEntity xml) throws XMLException {
995
                for (int i = 0; i < xml.getPropertyCount(); i++) {
996
                        String key = xml.getPropertyName(i);
997
                        if(key.startsWith("raster.file")) {
998
                                if(xml.getPropertyValue(i).startsWith(RasterLibrary.getTemporalPath()))
999
                                        throw new XMLException(new Throwable());
1000
                        }
1001
                }
1002

    
1003
                super.setXMLEntity(xml);
1004
                loadingFromProject = true;
1005
                
1006
                try {
1007
                        params = new File(pathGenerator.getAbsolutePath(xml.getStringProperty("file")));
1008

    
1009
                        if(params != null && getName() != null && getName().compareTo("") != 0) {
1010
                                try {
1011
                                        enableAwake();
1012
                                } catch (NotAvailableStateException e) {
1013
                                        RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
1014
                                }
1015
                        }
1016
                        if(!super.getFLayerStatus().visible)
1017
                                enableStopped();
1018

    
1019
                        // Para notificar al adapter-driver cual es la proyecci?n.
1020
                        setProjection(super.getProjection());
1021

    
1022
                        //Inicializamos la clase a la que se usa por defecto para
1023
                        //compatibilidad con proyectos antiguos
1024
                        String claseStr = StatusLayerRaster.defaultClass;
1025
                        if (xml.contains("raster.class"))
1026
                                claseStr = xml.getStringProperty("raster.class");
1027

    
1028
                        if (status != null)
1029
                                status.setXMLEntity(xml, this);
1030
                        else {
1031
                                // Cuando cargamos un proyecto
1032

    
1033
                                if (claseStr != null && !claseStr.equals("")) {
1034
                                        try {
1035
                                                Class clase = LayerFactory.getLayerClassForLayerClassName(claseStr);
1036
                                                Constructor constr = clase.getConstructor(null);
1037
                                                status = (IStatusRaster) constr.newInstance(null);
1038
                                                if (status != null) {
1039
                                                        ((StatusLayerRaster)status).setNameClass(claseStr);
1040
                                                        status.setXMLEntity(xml, this);
1041
                                                        filterArguments = status.getFilterArguments();
1042
                                                        
1043
                                                        //Creamos la tabla de color
1044
                                                        ArrayList color = (ArrayList) filterArguments.clone();
1045
                                                        loadedFromProject = ColorTableListManager.createColorTableFromArray(color);
1046
                                                }
1047
                                        } catch (ClassNotFoundException exc) {
1048
                                                throw new XMLException(exc);
1049
                                        } catch (InstantiationException exc) {
1050
                                                throw new XMLException(exc);
1051
                                        } catch (IllegalAccessException exc) {
1052
                                                throw new XMLException(exc);
1053
                                        } catch (NoSuchMethodException exc) {
1054
                                                throw new XMLException(exc);
1055
                                        } catch (InvocationTargetException exc) {
1056
                                                throw new XMLException(exc);
1057
                                        }
1058
                                }
1059
                        }
1060
                        firstLoad = true;
1061
                } catch (NotExistInXMLEntity e) {
1062

    
1063
                }
1064
        }
1065

    
1066
        /* (non-Javadoc)
1067
         * @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)
1068
         */
1069
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet propeties) throws ReadDriverException {
1070

    
1071
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
1072
                        return;
1073

    
1074
                if (!mustTilePrint) {
1075
                        draw(null, g, viewPort, cancel,scale);
1076
                } else {
1077
                        // Para no pedir imagenes demasiado grandes, vamos
1078
                        // a hacer lo mismo que hace EcwFile: chunkear.
1079
                        // Llamamos a drawView con cuadraditos m?s peque?os
1080
                        // del BufferedImage ni caso, cuando se imprime viene con null
1081
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1082
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1083

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

    
1087
                        //RasterStats stats = getSource().getFilterStack().getStats();
1088
                        //if(stats != null)
1089
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
1090

    
1091

    
1092
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
1093
                                // Parte que dibuja
1094
                                try {
1095
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1096
                                        draw(null, g, vp, cancel, scale);
1097
                                } catch (NoninvertibleTransformException e) {
1098
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
1099
                                }
1100
                        }
1101
                        /*if(stats != null){
1102
                                getSource().getFilterStack().getStats().history.clear();
1103
                                stats = getSource().getFilterStack().getStats();
1104
                        }*/
1105
                }
1106
        }
1107

    
1108
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale) throws ReadDriverException {
1109
                if(!isOpen())
1110
                        return;
1111

    
1112
                // Para no pedir imagenes demasiado grandes, vamos
1113
                // a hacer lo mismo que hace EcwFile: chunkear.
1114
                // Llamamos a drawView con cuadraditos m?s peque?os
1115
                // del BufferedImage ni caso, cuando se imprime viene con null
1116

    
1117
                int numW, numH;
1118
                int stepX, stepY;
1119
                int xProv, yProv;
1120
                int A = 1500;
1121
                int H = 1500;
1122
                int altoAux, anchoAux;
1123

    
1124
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
1125

    
1126
                // Vamos a hacerlo en trozos de AxH
1127
                Rectangle r = g.getClipBounds();
1128
                numW = (int) (r.width) / A;
1129
                numH = (int) (r.height) / H;
1130

    
1131
                double[] srcPts = new double[8];
1132
                double[] dstPts = new double[8];
1133

    
1134
                yProv = (int) r.y;
1135
                for (stepY = 0; stepY < numH + 1; stepY++) {
1136
                        if ((yProv + H) > r.getMaxY())
1137
                                altoAux = (int) r.getMaxY() - yProv;
1138
                        else
1139
                                altoAux = H;
1140

    
1141
                        xProv = (int) r.x;
1142
                        for (stepX = 0; stepX < numW + 1; stepX++) {
1143
                                if ((xProv + A) > r.getMaxX())
1144
                                        anchoAux = (int) r.getMaxX() - xProv;
1145
                                else
1146
                                        anchoAux = A;
1147

    
1148
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
1149

    
1150
                                // Parte que dibuja
1151
                                srcPts[0] = xProv;
1152
                                srcPts[1] = yProv;
1153
                                srcPts[2] = xProv + anchoAux + 1;
1154
                                srcPts[3] = yProv;
1155
                                srcPts[4] = xProv + anchoAux + 1;
1156
                                srcPts[5] = yProv + altoAux + 1;
1157
                                srcPts[6] = xProv;
1158
                                srcPts[7] = yProv + altoAux + 1;
1159

    
1160
                                try {
1161
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
1162
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
1163
                                        // Extent extent = new Extent(rectCuadricula);
1164

    
1165
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
1166
                                        ViewPort vp = viewPort.cloneViewPort();
1167
                                        vp.setImageSize(tam);
1168
                                        vp.setExtent(rectCuadricula);
1169
                                        vp.setAffineTransform(mat);
1170
                                        draw(null, g, vp, cancel, scale);
1171

    
1172
                                } catch (NoninvertibleTransformException e) {
1173
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
1174
                                }
1175
                                // Fin parte que dibuja
1176
                                xProv = xProv + A;
1177
                        }
1178
                        yProv = yProv + H;
1179
                }
1180
        }
1181

    
1182
        /**
1183
         * Borra de la lista de listeners el que se pasa como par?metro.
1184
         *
1185
         * @param o LayerListener a borrar.
1186
         *
1187
         * @return True si ha sido correcto el borrado del Listener.
1188
         */
1189
        public boolean removeLayerListener(LayerListener o) {
1190
                if (this.isRemoveRasterFlag()) {
1191
                        try {
1192
                                enableClosed();
1193
                        } catch (NotAvailableStateException e1) {
1194
                                // No se ha podido cambiar el estado de la capa a cerrado
1195
                        }
1196
                }
1197
                
1198
                // Salva a RMF
1199
                if (this.getDataSource() != null) {
1200
                        // Guardamos la GeoReferenciacion de cada dataset
1201
                        try {
1202
                                for (int i = 0; i < getDataSource().getDatasetCount(); i++) {
1203
                                        getDataSource().saveObjectToRmf(i, RasterDataset.class, getDataSource().getDataset(i)[0]);
1204
                                }
1205
                        } catch (RmfSerializerException e) {
1206
                                RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
1207
                        }
1208
                }
1209

    
1210
                if (this.isRemoveRasterFlag()) {
1211
                        image = null;
1212
                        String[] files = (String[]) getFileName().clone();
1213
                        if (dataset != null)
1214
                                dataset.close();
1215
                        if (bufferFactory != null)
1216
                                bufferFactory.free();
1217
                        bufferFactory = null;
1218
                        dataset = null;
1219
                        render = null;
1220
                        
1221
                        // System.gc();
1222
                        this.setRemoveRasterFlag(true);
1223
                        
1224
                        for (int i = 0; i < files.length; i++) {
1225
                                File file = new File(files[i]);
1226
                                File dirTemp = RasterLibrary.getTemporalFile();
1227
                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
1228
                                        file.delete();
1229
                                        
1230
                                        // Borramos todos los ficheros que puedan tener relacion con el fichero actual
1231
                                        String basefile = file.getName();
1232
                                        File basepath = file.getParentFile();
1233
                                        int last = basefile.lastIndexOf(".");
1234
                                        if (last != -1)
1235
                                                basefile = basefile.substring(0, last + 1);
1236
                                        File[] list = basepath.listFiles();
1237
                                        for (int j = 0; j < list.length; j++)
1238
                                                if (list[j].getName().startsWith(basefile))
1239
                                                        list[j].delete();
1240
                                }
1241
                        }
1242
                }
1243
                updateDrawVersion();
1244
                return super.layerListeners.remove(o);
1245
        }
1246

    
1247
        /**
1248
         * @return Returns the removeRasterFlag.
1249
         */
1250
        public boolean isRemoveRasterFlag() {
1251
                return removeRasterFlag;
1252
        }
1253

    
1254
        /**
1255
         * Asigna el valor del flag que dice si destruimos la memoria del raster
1256
         * al eliminarlo del TOC o  no.
1257
         * @param removeRasterFlag The removeRasterFlag to set.
1258
         */
1259
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1260
                this.removeRasterFlag = removeRasterFlag;
1261
        }
1262

    
1263
        /*
1264
         * (non-Javadoc)
1265
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1266
         */
1267
        public ImageIcon getTocImageIcon() {
1268
                return new ImageIcon(getClass().getResource("images/map_ico_ok.gif"));
1269
        }
1270

    
1271
        /*
1272
         *  (non-Javadoc)
1273
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1274
         */
1275
        public int[] getTileSize() {
1276
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1277
                return size;
1278
        }
1279

    
1280
        /*
1281
         *  (non-Javadoc)
1282
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1283
         */
1284
        public boolean isTiled() {
1285
                return mustTileDraw;
1286
        }
1287

    
1288
        /**
1289
         * Obtiene el flag que dice si la imagen est? o no georreferenciada
1290
         * @return true si est? georreferenciada y false si no lo est?.
1291
         */
1292
        public boolean isGeoreferenced() {
1293
                return dataset.isGeoreferenced();
1294
        }
1295

    
1296
        /**
1297
         * Get datasource object
1298
         * @return
1299
         */
1300
        public BufferFactory getBufferFactory(){
1301
                return bufferFactory;
1302
        }
1303

    
1304
        /**
1305
         * Obtiene el valor NoData asociado al raster.
1306
         * @return double
1307
         */
1308
        public double getNoDataValue() {
1309
                if (dataset == null)
1310
                        return RasterLibrary.defaultNoDataValue;
1311
                return dataset.getNoDataValue();
1312
        }
1313

    
1314
        /**
1315
         * Asigna el valor no data asociado a la capa
1316
         * @param nd
1317
         */
1318
        public void setNoDataValue(double nd) {
1319
                if (bufferFactory != null)
1320
                        bufferFactory.setNoDataToFill(nd);
1321
                if (dataset != null)
1322
                        dataset.setNoDataValue(nd);
1323
        }
1324

    
1325
        /*
1326
         * (non-Javadoc)
1327
         * @see org.gvsig.fmap.raster.IRasterOperations#getPXHeight()
1328
         */
1329
        public double getPxHeight() {
1330
                return dataset.getHeight();
1331
        }
1332

    
1333
        /*
1334
         * (non-Javadoc)
1335
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
1336
         */
1337
        public double getPxWidth() {
1338
                return dataset.getWidth();
1339
        }
1340

    
1341
        /*
1342
         * (non-Javadoc)
1343
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCHeight()
1344
         */
1345
        public double getWCHeight() {
1346
                return getFullExtent().getHeight();
1347
        }
1348

    
1349
        /*
1350
         * (non-Javadoc)
1351
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
1352
         */
1353
        public double getWCWidth() {
1354
                return getFullExtent().getWidth();
1355
        }
1356

    
1357
        /*
1358
         * (non-Javadoc)
1359
         * @see org.gvsig.fmap.raster.IRasterFile#getFileSize()
1360
         */
1361
        public long[] getFileSize(){
1362
                int nFiles = dataset.getDatasetCount();
1363
                long[] s = new long[nFiles];
1364
                for (int i = 0; i < nFiles; i++)
1365
                        s[i] = dataset.getDataset(i)[0].getFileSize();
1366
                return s;
1367
        }
1368

    
1369
        /*
1370
         * (non-Javadoc)
1371
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
1372
         */
1373
        public String[] getFileName(){
1374
                int nFiles = 0;
1375
                if (dataset != null)
1376
                        nFiles = dataset.getDatasetCount();
1377
                String[] s = new String[nFiles];
1378
                for (int i = 0; i < nFiles; i++)
1379
                        s[i] = dataset.getDataset(i)[0].getFName();
1380
                return s;
1381
        }
1382

    
1383
        /*
1384
         * (non-Javadoc)
1385
         * @see org.gvsig.fmap.raster.IRasterFile#getFileCount()
1386
         */
1387
        public int getFileCount() {
1388
                return (dataset != null) ? dataset.getDatasetCount() : 0;
1389
        }
1390

    
1391
        /*
1392
         * (non-Javadoc)
1393
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
1394
         */
1395
        public String getFileFormat() {
1396
                String fName = dataset.getDataset(0)[0].getFName();
1397
                int index = fName.lastIndexOf(".") + 1;
1398
                String ext = null;
1399
                if (index > 0)
1400
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1401
                return ext;
1402
        }
1403

    
1404
        /*
1405
         * (non-Javadoc)
1406
         * @see org.gvsig.fmap.raster.IRasterOperations#getBandCount()
1407
         */
1408
        public int getBandCount() {
1409
                return (dataset != null) ? dataset.getBandCount() : 0;
1410
        }
1411

    
1412
        /*
1413
         * (non-Javadoc)
1414
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1415
         */
1416
        public int[] getDataType() {
1417
                return dataset.getDataType();
1418
        }
1419

    
1420
        /*
1421
         * (non-Javadoc)
1422
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
1423
         */
1424
        public GridTransparency getRenderTransparency() {
1425
                return getRender().getLastTransparency();
1426
        }
1427

    
1428
        /*
1429
         * (non-Javadoc)
1430
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1431
         */
1432
        public RasterFilterList getRenderFilterList() {
1433
                return getRender().getFilterList();
1434
        }
1435

    
1436
        /*
1437
         * (non-Javadoc)
1438
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
1439
         */
1440
        public int[] getRenderBands() {
1441
                return getRender().getRenderBands();
1442
        }
1443

    
1444
        /*
1445
         * (non-Javadoc)
1446
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
1447
         */
1448
        public void setRenderBands(int[] renderBands) {
1449
                getRender().setRenderBands(renderBands);
1450
        }
1451

    
1452
        /*
1453
         * (non-Javadoc)
1454
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
1455
         */
1456
        public void setRenderFilterList(RasterFilterList filterList) {
1457
                getRender().setFilterList(filterList);
1458
        }
1459

    
1460
        /*
1461
         * (non-Javadoc)
1462
         * @see org.gvsig.raster.hierarchy.IRasterDataset#getDataSource()
1463
         */
1464
        public IRasterDataSource getDataSource() {
1465
                return dataset;
1466
        }
1467

    
1468
        /*
1469
         * (non-Javadoc)
1470
         * @see org.gvsig.fmap.raster.IRasterDataset#addFile(java.lang.String)
1471
         */
1472
        public void addFile(String fileName) throws NotSupportedExtensionException, RasterDriverException {
1473
                if (getRender() != null)
1474
                        bufferFactory.addFile(RasterDataset.open(getProjection(), fileName));
1475
        }
1476

    
1477
        /*
1478
         * (non-Javadoc)
1479
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
1480
         */
1481
        public void delFile(String fileName) {
1482
                if (getRender() != null)
1483
                        bufferFactory.removeFile(fileName);
1484
        }
1485

    
1486
        /*
1487
         * (non-Javadoc)
1488
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1489
         */
1490
        public Object getInfo(String key) {
1491
                if (key.equals("DriverName"))
1492
                        return "gvSIG Raster Driver";
1493
                return null;
1494
        }
1495

    
1496
        /*
1497
         * (non-Javadoc)
1498
         * @see org.gvsig.raster.shared.IRasterOperations#getMetadata()
1499
         */
1500
        public DatasetMetadata[] getMetadata() {
1501
                int count = dataset.getDatasetCount();
1502
                DatasetMetadata[] metadata = new DatasetMetadata[count];
1503
                for (int i = 0; i < count; i++) {
1504
                        metadata[i] = dataset.getDataset(i)[0].getMetadata();
1505
                }
1506
                return metadata;
1507
        }
1508

    
1509
        /*
1510
         * (non-Javadoc)
1511
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
1512
         */
1513
        public int[] getBandCountFromDataset() {
1514
                int count = dataset.getDatasetCount();
1515
                int[] bands = new int[count];
1516
                for (int i = 0; i < count; i++)
1517
                        bands[i] = dataset.getDataset(i)[0].getBandCount();
1518
                return bands;
1519
        }
1520

    
1521
        /*
1522
         * (non-Javadoc)
1523
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1524
         */
1525
        public String getColorInterpretation(int band, int dataset) {
1526
                if (this.dataset.getDataset(dataset)[0].getColorInterpretation().get(band) == null)
1527
                        return "Undefined";
1528
                return this.dataset.getDataset(dataset)[0].getColorInterpretation().get(band);
1529
        }
1530

    
1531
        /*
1532
         * (non-Javadoc)
1533
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
1534
         */
1535
        public String getWktProjection() throws RasterDriverException {
1536
                return dataset.getWktProjection();
1537
        }
1538

    
1539
        /**
1540
         * Metodo para consultar si una capa puede ser un RGB. Suponemos que es un RGB
1541
         * si el tipo de datos es de tipo byte y su interpretacion de color tiene
1542
         * asignada los tres colores.
1543
         * @return boolean
1544
         */
1545
        public boolean isRGB() {
1546
                if ((dataset == null) || (render == null))
1547
                        return false;
1548

    
1549
// Quitado pq no necesariamente tiene pq tener 3 bandas para ser RGB
1550
//                if (dataset.getBandCount() < 3)
1551
//                        return false;
1552

    
1553
                if (dataset.getDataType()[0] != IBuffer.TYPE_BYTE)
1554
                        return false;
1555

    
1556
                boolean R = false;
1557
                boolean G = false;
1558
                boolean B = false;
1559

    
1560
                int[] renderBands = render.getRenderBands();
1561
                for (int i = 0; i < renderBands.length; i++) {
1562
                        if (renderBands[i] >= 0) {
1563
                                switch (i) {
1564
                                        case 0:
1565
                                                R = true;
1566
                                                break;
1567
                                        case 1:
1568
                                                G = true;
1569
                                                break;
1570
                                        case 2:
1571
                                                B = true;
1572
                                                break;
1573
                                }
1574
                        }
1575
                }
1576

    
1577
                if (R && G && B)
1578
                        return true;
1579

    
1580
                return false;
1581
        }
1582
        
1583
        /**
1584
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1585
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1586
         * cacheado o no dependiendo del tama?o de esta.
1587
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1588
         * @return Grid.
1589
         * @throws InterruptedException
1590
         */
1591
        public Grid getFullGrid(boolean interpolated) throws GridException, InterruptedException {
1592
                BufferFactory bf = getBufferFactory();
1593
                bf.clearDrawableBand();
1594
                bf.setAllDrawableBands();
1595
                try {
1596
                        bf.setAreaOfInterest();
1597
                } catch (RasterDriverException e) {
1598
                        throw new GridException("Error reading buffer");
1599
                }
1600
                return new Grid(bf, interpolated);
1601
        }
1602
        
1603
        /**
1604
         * Obtiene el grid de la capa completa. Esta llamada devuelve un buffer de solo lectura
1605
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1606
         * @return Grid.
1607
         * @throws InterruptedException
1608
         */
1609
        public Grid getReadOnlyFullGrid(boolean interpolated) throws GridException, InterruptedException {
1610
                BufferFactory bf = new BufferFactory(dataset.newDataset());
1611
                bf.setReadOnly(true);
1612
                bf.clearDrawableBand();
1613
                bf.setAllDrawableBands();
1614
                try {
1615
                        bf.setAreaOfInterest();
1616
                } catch (RasterDriverException e) {
1617
                        throw new GridException("Error reading buffer");
1618
                }
1619
                return new Grid(bf, interpolated);
1620
        }
1621
        
1622
        /**
1623
         * Obtiene el tama?o de celda de la fuente de datos
1624
         * @return double con el tama?o de celda
1625
         */
1626
        public double getCellSize() {
1627
                return (getDataSource() != null) ? getDataSource().getCellSize() : 1;
1628
        }
1629
        
1630
        /*
1631
         * (non-Javadoc)
1632
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1633
         */
1634
        public Extent getFullRasterExtent() {
1635
                if (dataset == null){
1636
                        try {
1637
                                load();
1638
                        } catch (LoadLayerException e) {
1639
                                return null;
1640
                        }
1641
                }
1642
                return this.getDataSource().getExtent();
1643
        }
1644

    
1645

    
1646
        /**
1647
         * Devuelve el fichero asociado a la capa o null si no tiene.
1648
         * @return Fichero.
1649
         */
1650
        public File getFile() {
1651
                return (params instanceof File) ? ((File)params) : null;
1652
        }
1653

    
1654
        /**
1655
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1656
         * @param file Fichero a consultar
1657
         * @return true si es aceptado y false si no lo es.
1658
         */
1659
        public static boolean isFileAccepted(File file) {
1660
                return RasterDataset.fileIsSupported(file.getName());
1661
        }
1662

    
1663
        /*
1664
         * (non-Javadoc)
1665
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1666
         */
1667
        public boolean existColorTable() {
1668
                return getRender().existColorTable();
1669
        }
1670
        
1671
        /*
1672
         * (non-Javadoc)
1673
         * @see org.gvsig.raster.hierarchy.IRasterRendering#existsAlphaBand()
1674
         */
1675
        public boolean existsAlphaBand() {
1676
                if(getDataSource().getColorInterpretation() != null)
1677
                        return getDataSource().getColorInterpretation().isAlphaBand();
1678
                else 
1679
                        return false;
1680
        }
1681
        
1682
        /*
1683
         * (non-Javadoc)
1684
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getAlphaBandNumber()
1685
         */
1686
        public int getAlphaBandNumber() {
1687
                if(getDataSource().getColorInterpretation() != null)
1688
                        return getDataSource().getColorInterpretation().getBand(DatasetColorInterpretation.ALPHA_BAND);
1689
                return -1;
1690
        }
1691

    
1692
        /**
1693
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1694
         * capa busque una leyenda valida.
1695
         * @param ct
1696
         */
1697
        public void setLastLegend(ColorTable ct) {
1698
                lastLegend = ColorTableLegend.createLegend(ct);
1699
        }
1700

    
1701
        /**
1702
         * Devuelve la Leyenda de la capa.
1703
         * @return Leyenda.
1704
         */
1705
        public ILegend getLegend() {
1706
                if (lastLegend != null)
1707
                        return lastLegend;
1708

    
1709
                return null;
1710
        }
1711

    
1712
        /*
1713
         * (non-Javadoc)
1714
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1715
         */
1716
        public void addLegendListener(LegendListener listener) {
1717
                layerChangeSupport.addLayerListener(listener);
1718
        }
1719

    
1720
        /*
1721
         *  (non-Javadoc)
1722
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1723
         */
1724
        public int getShapeType() throws ReadDriverException {
1725
                return FShape.POLYGON;
1726
        }
1727

    
1728
        /*
1729
         * (non-Javadoc)
1730
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1731
         */
1732
        public void removeLegendListener(LegendListener listener) {
1733
                layerChangeSupport.removeLayerListener(listener);
1734
        }
1735

    
1736
        /**
1737
         * Metodo que obtiene si un punto cae dentro de los l?mites de la capa
1738
         * o fuera de ellos.
1739
         * @param p Punto a calcular
1740
         * @return true si est? dentro de los l?mites y false si est? fuera
1741
         */
1742
        public boolean isInside(Point2D p) {
1743
                 return getDataSource().isInside(p);
1744
        }
1745

    
1746
        /**
1747
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1748
         * @return AffineTransform
1749
         */
1750
        public AffineTransform getAffineTransform(int band) {
1751
                return getDataSource().getAffineTransform(band);
1752
        }
1753
        
1754
        /**
1755
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1756
         * @return AffineTransform
1757
         */
1758
        public AffineTransform getAffineTransform() {
1759
                if(getDataSource() != null)
1760
                        return getDataSource().getAffineTransform(0);
1761
                return null;
1762
        }
1763

    
1764
        /**
1765
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista
1766
         * @param transf
1767
         */
1768
        public void setAffineTransform(AffineTransform transf) {
1769
                if(transf == null)
1770
                        return;
1771
                affineTransformList.add(transf);
1772
                getDataSource().setAffineTransform(transf);
1773
                updateDrawVersion();
1774
        }
1775

    
1776
        /**
1777
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista.
1778
         * Esta versi?n no guarda en el historico.
1779
         * @param transf
1780
         */
1781
        public void setAT(AffineTransform transf) {
1782
                getDataSource().setAffineTransform(transf);
1783
                updateDrawVersion();
1784
        }
1785

    
1786
        /**
1787
         * Obtiene la lista de transformaciones que se han ido aplicando al raster.
1788
         * @return Historical. Lista de AffineTransform
1789
         */
1790
        public Historical getAffineTransformHistorical() {
1791
                return this.affineTransformList;
1792
        }
1793
        
1794
        /**
1795
         * Salva la georreferenciaci?n a fichero rmf.
1796
         * @param fName
1797
         * @throws RmfSerializerException 
1798
         */
1799
        public void saveGeoToRmf() throws RmfSerializerException {
1800
                if (!isOpen())
1801
                        return;
1802

    
1803
                // Guardamos la GeoReferenciacion de cada dataset
1804
                for (int i = 0; i < getDataSource().getDatasetCount(); i++)
1805
                        getDataSource().saveObjectToRmf(i, RasterDataset.class, getDataSource().getDataset(i)[0]);
1806
                
1807
                affineTransformList.clear();
1808
                affineTransformList.add(this.getAffineTransform());
1809
        }
1810

    
1811
        /*
1812
         * (non-Javadoc)
1813
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1814
         */
1815
        public boolean isActionEnabled(int action) {
1816
                switch (action) {
1817
                        case IRasterLayerActions.BANDS_FILE_LIST:
1818
                                if (existColorTable())
1819
                                        return false;
1820
                                break;
1821
                        case IRasterLayerActions.BANDS_RGB:
1822
                                if (existColorTable())
1823
                                        return false;
1824
                                break;
1825
                        case IRasterLayerActions.REPROJECT:
1826
                                if (!isReproyectable())
1827
                                        return false;
1828
                                break;
1829
                        case IRasterLayerActions.CREATEOVERVIEWS:
1830
                                return overviewsSupport();
1831
                        case IRasterLayerActions.OPACITY:
1832
                        case IRasterLayerActions.TRANSPARENCY:
1833
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1834
                        case IRasterLayerActions.ENHANCED:
1835
                        case IRasterLayerActions.PANSHARPENING:
1836
                        case IRasterLayerActions.SELECT_LAYER:
1837
                        case IRasterLayerActions.SAVE_COLORINTERP:
1838
                                return true;
1839
                        case IRasterLayerActions.REMOTE_ACTIONS:
1840
                                return false;
1841
                }
1842
                return true;
1843
        }
1844

    
1845
        /*
1846
         * (non-Javadoc)
1847
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1848
         */
1849
        public void setVisible(boolean visibility) {
1850
                if(visibility)
1851
                        state.disableStopped();
1852
                else
1853
                        enableStopped();
1854

    
1855
                if(isAwake() || isClosed()) {
1856
                        try {
1857
                                this.load();
1858
                        } catch (LoadLayerException e) {
1859
                                e.printStackTrace();
1860
                        }
1861
                }
1862

    
1863
                /*
1864
                 * Cuando se modifica la visibilidad de una capa raster se hace un updateDrawVersion de todas las
1865
                 * capas raster de ese MapContext. Esto es porque la estrategia utilizada por RasterDrawStrategy hace
1866
                 * que se cacheen en blanco las capas raster que est?n ocultas debajo de otras. Al hacer invisibles las
1867
                 * de arriba la cache que estaba en blanco hace que no se pinte nada. Para evitar esto las marcamos todas
1868
                 * como que han sido modificadas para que se vuelvan a leer.
1869
                 */
1870
                if(getMapContext() != null) {
1871
                        ArrayList listLayers = new ArrayList();
1872
                        listLayers = RasterDrawStrategy.getLayerList(getMapContext().getLayers(), listLayers);
1873
                        for (int i = 0; i < listLayers.size(); i++) {
1874
                                if(listLayers.get(i) instanceof FLyrRasterSE)
1875
                                        ((FLyrRasterSE)listLayers.get(i)).updateDrawVersion();
1876
                        }
1877
                }
1878

    
1879
                super.setVisible(visibility);
1880
        }
1881

    
1882
        /**
1883
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1884
         * @return valor de transparencia
1885
         */
1886
        public int getTransparency() {
1887
                try {
1888
                        return getRenderTransparency().getOpacity();
1889
                } catch (NullPointerException e) {
1890
                        return super.getTransparency();
1891
                }
1892
        }
1893

    
1894
        /**
1895
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1896
         * o no.
1897
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1898
         */
1899
        public boolean isTransparent() {
1900
                return getRenderTransparency().isTransparencyActive();
1901
        }
1902

    
1903
        /**
1904
         * Asigna la transparencia de la siguiente renderizaci?n
1905
         * @param valor de transparencia
1906
         */
1907
        public void setTransparency(int trans) {
1908
                super.setTransparency(trans);
1909
                try {
1910
                        getRenderTransparency().setOpacity(trans);
1911
                        getRenderTransparency().activeTransparency();
1912
                } catch (NullPointerException e) {
1913
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1914
                }
1915
        }
1916

    
1917
        /*
1918
         * (non-Javadoc)
1919
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getLastRenderBuffer()
1920
         */
1921
        public IBuffer getLastRenderBuffer() {
1922
                return getRender().getLastRenderBuffer();
1923
        }
1924

    
1925
        /**
1926
         *
1927
         * @return ROIs asociadas a la capa raster.
1928
         */
1929
        public ArrayList getRois() {
1930
                return rois;
1931
        }
1932

    
1933
        /**
1934
         * Establece las ROI asociadas a la capa raster.
1935
         *
1936
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1937
         */
1938
        public void setRois(ArrayList rois) {
1939
                this.rois = rois;
1940
        }
1941

    
1942
        /**
1943
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1944
         * devolver? null.
1945
         * @return TreeMap con la lista de capas a dibujar
1946
         */
1947
        public HashMap getRasterStrategy() {
1948
                if(strategy != null)
1949
                        return strategy.getStrategy();
1950
                return null;
1951
        }
1952
        
1953
        /**
1954
         * Devuelve el tipo de valor de NoData asociado a la capa.
1955
         * Sirve para diferenciar los estados seleccionados por el usuario. Siendo
1956
         * estos '0: Sin Valor NoData', '1: NoData de Capa'(Por defecto) y '2: Personalizado'
1957
         */
1958
        /**
1959
         * @return the noDataType
1960
         */
1961
        public int getNoDataType() {
1962
                return noDataType;
1963
        }
1964

    
1965
        /**
1966
         * @param noDataType the noDataType to set
1967
         */
1968
        public void setNoDataType(int noDataType) {
1969
                this.noDataType = noDataType;
1970
                if (dataset != null)
1971
                        dataset.setNoDataEnabled(noDataType != RasterLibrary.NODATATYPE_DISABLED);
1972
        }
1973

    
1974
        /**
1975
         * @return the configuration
1976
         */
1977
        static public IConfiguration getConfiguration() {
1978
                return configuration;
1979
        }
1980

    
1981
        /**
1982
         * @param configuration the configuration to set
1983
         */
1984
        static public void setConfiguration(IConfiguration configuration) {
1985
                FLyrRasterSE.configuration = configuration;
1986
        }
1987
        
1988
        /*
1989
         * (non-Javadoc)
1990
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#reload()
1991
         */
1992
        public void reload() throws ReloadLayerException {
1993
                try {
1994
                        super.reload();
1995
                        if (getMapContext() == null)
1996
                                return;
1997
                        if (isStopped())
1998
                                disableStopped();
1999
                        load();
2000
                        getMapContext().invalidate();
2001
                } catch (LoadLayerException e) {
2002
                        setAvailable(false);
2003
                        throw new ReloadLayerException(getName(), e);
2004
                }
2005
        }
2006
        
2007
        /**
2008
         * Devuelve si la capa tiene soporte para poder generar overviews
2009
         * @return
2010
         */
2011
        public boolean overviewsSupport() {
2012
                if ((getDataSource() != null) && (getDataSource().overviewsSupport()))
2013
                        return true;
2014

    
2015
                return false;
2016
        }
2017

    
2018
        /**
2019
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
2020
         * en escala de grises
2021
         * @return
2022
         */
2023
        public boolean isRenderingAsGray() {
2024
                int[] renderBands = getRenderBands();
2025
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
2026
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
2027
                        return true;
2028
                return false;
2029
        }
2030
        
2031
        /*
2032
         * (non-Javadoc)
2033
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
2034
         */
2035
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
2036
                updateDrawVersion();
2037
        }
2038
        
2039
        /*****************************************************/
2040
        //Utils
2041

    
2042
        /**
2043
         * Ajusta las coordenadas especificadas en el par?metro al ?rea m?xima
2044
         * del raster en p?xeles.
2045
         * @param req Punto a ajustar dentro del extener del raster
2046
         */
2047
        public Point2D adjustWorldRequest(Point2D req) {
2048
                Rectangle2D ext = null;
2049

    
2050
                ext = getFullExtent();
2051
                req.setLocation(Math.max(ext.getMinX(), req.getX()), Math.max(ext.getMinY(), req.getY()));
2052
                req.setLocation(Math.min(ext.getMaxX(), req.getX()), Math.min(ext.getMaxY(), req.getY()));
2053
                return req;
2054
        }
2055
        
2056
        /*
2057
         * (non-Javadoc)
2058
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#cloneLayer()
2059
         */
2060
        public FLayer cloneLayer() throws Exception {
2061
                FLyrRasterSE newLayer = FLyrRasterSE.createLayer(this.getName(), params, this.getProjection());
2062
                for (int i = 0; i < dataset.getDatasetCount(); i++) {
2063
                        String name = dataset.getDataset(i)[0].getFName();
2064
                        if (!(dataset instanceof CompositeDataset) && !name.equals(this.getName()) && !isActionEnabled(IRasterLayerActions.REMOTE_ACTIONS))
2065
                                newLayer.addFile(name);
2066
                }
2067
                ArrayList filters = getRender().getFilterList().getStatusCloned();
2068
        
2069
                //Hacemos una copia de las bandas a renderizar
2070
                if(getRenderBands() != null) {
2071
                        int[] rb = new int[getRenderBands().length];
2072
                        for (int i = 0; i < rb.length; i++) 
2073
                                rb[i] = getRenderBands()[i];
2074
                        newLayer.setRenderBands(rb);
2075
                }
2076
                
2077
                //Asignamos el entorno
2078
                if(newLayer.getRender().getFilterList() == null)
2079
                        newLayer.getRender().setFilterList(new RasterFilterList());
2080
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());        
2081
                newLayer.getRender().getFilterList().setStatus(filters);
2082

    
2083
                // Asignamos los valores noData del original
2084
                newLayer.setNoDataValue(getNoDataValue());
2085
                newLayer.setNoDataType(getNoDataType());
2086
                newLayer.applyNoData();
2087

    
2088
                return newLayer;
2089
        }
2090
        
2091
        /**
2092
         * Gets a layer which the source is a file
2093
         * @return
2094
         */
2095
        public FLayer getFileLayer() {
2096
                try {
2097
                        return cloneLayer();
2098
                } catch (Exception e) {
2099
                }
2100
                return null;
2101
        }
2102
        
2103
        /*****************************************************/
2104

    
2105
        public void disableStopped() {state.disableStopped();}
2106

    
2107
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
2108

    
2109
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
2110

    
2111
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
2112

    
2113
        public void enableStopped() {state.enableStopped();}
2114

    
2115
        public boolean isAwake() {return state.isAwake();}
2116

    
2117
        public boolean isClosed() {return state.isClosed();}
2118

    
2119
        public boolean isOpen() {return state.isOpen();}
2120

    
2121
        public boolean isStopped() {return state.isStopped();}
2122

    
2123
        /**
2124
         * Returns true if exists a process reading data from this layer
2125
         * @return
2126
         */
2127
        public boolean isReadingData() {
2128
                return readingData != null;
2129
        }
2130

    
2131
        /**
2132
         * When a process is using information of this layer this variable will contain
2133
         * the thread ID.
2134
         * @param readingData
2135
         */
2136
        public synchronized void setReadingData(String readingData) {
2137
                this.readingData = readingData;
2138
        }
2139

    
2140
}