Statistics
| Revision:

root / branches / v2_0_0_prep / extensions / extRasterTools-SE / src / org / gvsig / fmap / raster / layers / FLyrRasterSE.java @ 32880

History | View | Annotate | Download (67.2 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2007 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 */
19
package org.gvsig.fmap.raster.layers;
20

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

    
37
import org.cresques.cts.IProjection;
38
import org.gvsig.compat.print.PrintAttributes;
39
import org.gvsig.fmap.crs.CRSFactory;
40
import org.gvsig.fmap.dal.DataStore;
41
import org.gvsig.fmap.dal.exception.DataException;
42
import org.gvsig.fmap.dal.exception.ReadException;
43
import org.gvsig.fmap.dal.raster.CoverageStore;
44
import org.gvsig.fmap.dal.store.raster.RasterStoreParameters;
45
import org.gvsig.fmap.geom.GeometryLocator;
46
import org.gvsig.fmap.geom.GeometryManager;
47
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
48
import org.gvsig.fmap.geom.Geometry.TYPES;
49
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
50
import org.gvsig.fmap.geom.primitive.Envelope;
51
import org.gvsig.fmap.mapcontext.ViewPort;
52
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
53
import org.gvsig.fmap.mapcontext.exceptions.ReloadLayerException;
54
import org.gvsig.fmap.mapcontext.layers.FLayer;
55
import org.gvsig.fmap.mapcontext.layers.FLyrDefault;
56
import org.gvsig.fmap.mapcontext.layers.LayerChangeSupport;
57
import org.gvsig.fmap.mapcontext.layers.LayerListener;
58
import org.gvsig.fmap.mapcontext.layers.Tiling;
59
import org.gvsig.fmap.mapcontext.layers.operations.Classifiable;
60
import org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint;
61
import org.gvsig.fmap.mapcontext.layers.operations.SingleLayer;
62
import org.gvsig.fmap.mapcontext.persistence.DummyFileFeatureStore;
63
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
64
import org.gvsig.fmap.mapcontext.rendering.legend.events.listeners.LegendListener;
65
import org.gvsig.fmap.raster.legend.ColorTableLegend;
66
import org.gvsig.raster.RasterLibrary;
67
import org.gvsig.raster.buffer.BufferFactory;
68
import org.gvsig.raster.dataset.CompositeDataset;
69
import org.gvsig.raster.dataset.FileNotOpenException;
70
import org.gvsig.raster.dataset.IBuffer;
71
import org.gvsig.raster.dataset.IRasterDataSource;
72
import org.gvsig.raster.dataset.InvalidSetViewException;
73
import org.gvsig.raster.dataset.MosaicNotValidException;
74
import org.gvsig.raster.dataset.MultiRasterDataset;
75
import org.gvsig.raster.dataset.NotSupportedExtensionException;
76
import org.gvsig.raster.dataset.RasterDataset;
77
import org.gvsig.raster.dataset.RasterDriverException;
78
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
79
import org.gvsig.raster.dataset.properties.DatasetMetadata;
80
import org.gvsig.raster.dataset.serializer.RmfSerializerException;
81
import org.gvsig.raster.datastruct.ColorTable;
82
import org.gvsig.raster.datastruct.Extent;
83
import org.gvsig.raster.datastruct.ViewPortData;
84
import org.gvsig.raster.datastruct.persistence.ColorTableLibraryPersistence;
85
import org.gvsig.raster.grid.Grid;
86
import org.gvsig.raster.grid.GridException;
87
import org.gvsig.raster.grid.GridPalette;
88
import org.gvsig.raster.grid.GridTransparency;
89
import org.gvsig.raster.grid.filter.FilterTypeException;
90
import org.gvsig.raster.grid.filter.RasterFilterList;
91
import org.gvsig.raster.grid.filter.RasterFilterListManager;
92
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
93
import org.gvsig.raster.grid.filter.enhancement.EnhancementStretchListManager;
94
import org.gvsig.raster.grid.filter.enhancement.LinearStretchParams;
95
import org.gvsig.raster.grid.render.Rendering;
96
import org.gvsig.raster.grid.render.VisualPropertyEvent;
97
import org.gvsig.raster.grid.render.VisualPropertyListener;
98
import org.gvsig.raster.grid.roi.ROI;
99
import org.gvsig.raster.hierarchy.IRasterDataset;
100
import org.gvsig.raster.hierarchy.IRasterOperations;
101
import org.gvsig.raster.hierarchy.IRasterProperties;
102
import org.gvsig.raster.hierarchy.IStatistics;
103
import org.gvsig.raster.process.RasterTask;
104
import org.gvsig.raster.process.RasterTaskQueue;
105
import org.gvsig.raster.projection.CRS;
106
import org.gvsig.raster.util.ColorConversion;
107
import org.gvsig.raster.util.Historical;
108
import org.gvsig.raster.util.MathUtils;
109
import org.gvsig.raster.util.RasterToolsUtil;
110
import org.gvsig.tools.ToolsLocator;
111
import org.gvsig.tools.dynobject.DynClass;
112
import org.gvsig.tools.dynobject.DynObjectManager;
113
import org.gvsig.tools.dynobject.DynStruct;
114
import org.gvsig.tools.exception.BaseException;
115
import org.gvsig.tools.persistence.PersistenceManager;
116
import org.gvsig.tools.persistence.PersistentState;
117
import org.gvsig.tools.persistence.exception.PersistenceException;
118
import org.gvsig.tools.task.Cancellable;
119
import org.gvsig.utils.XMLEntity;
120
import org.gvsig.utils.XMLException;
121
import org.slf4j.Logger;
122
import org.slf4j.LoggerFactory;
123

    
124

    
125
/**
126
 * Capa raster
127
 * @author Nacho Brodin (nachobrodin@gmail.com)
128
 */
129
public class FLyrRasterSE extends FLyrDefault implements IRasterProperties,
130
                IRasterDataset, InfoByPoint, Classifiable, IRasterOperations,
131
                IRasterLayerActions, ILayerState, VisualPropertyListener, SingleLayer {
132
        public static final String     PERSISTENT_NAME        = "FLyrRasterSE_Persistent";
133
    public static final String     PERSISTENT_DESCRIPTION = "FLyrRasterSE Persistent";
134
        
135
        private boolean                mustTileDraw        = false;
136
        private boolean                mustTilePrint       = true;
137
        private int                    maxTileDrawWidth    = 200;
138
        private int                    maxTileDrawHeight   = 200;
139
        private int                    maxTilePrintWidth   = 1500;
140
        private int                    maxTilePrintHeight  = 1500;
141
        protected IStatusRaster        status              = null;
142
        private boolean                firstLoad           = false;
143
        private boolean                removeRasterFlag    = true;
144
        private Object                 params              = null;
145
        protected IRasterDataSource    dataset             = null;
146
        protected Rendering            render              = null;
147
        protected BufferFactory        bufferFactory       = null;
148
        private int                    posX                = 0;
149
        private int                    posY                = 0;
150
        private double                 posXWC              = 0;
151
        private int                    posYWC              = 0;
152
        private int                    r                   = 0;
153
        private int                    g                   = 0;
154
        private int                    b                   = 0;
155
        private LayerChangeSupport     layerChangeSupport  = new LayerChangeSupport();
156
        private FLyrState              state               = new FLyrState();
157
        private ArrayList              filterArguments     = null;
158
        protected ILegend              lastLegend          = null;
159
        protected ColorTable           loadedFromProject   = null;
160
        private ArrayList              rois                = null;
161
        private RasterDrawStrategy     strategy            = null;
162
        static private IConfiguration  configuration       = new DefaultLayerConfiguration();
163

    
164
        private BufferedImage          image               = null;
165
        private static GeometryManager geomManager              = GeometryLocator.getGeometryManager();
166
        private static final Logger    logger              = LoggerFactory.getLogger(FLyrRasterSE.class);
167

    
168
        /**
169
         * Tipo de valor no data asociado a la capa.
170
         * Sirve para diferenciar los estados seleccionados por el usuario. Siendo
171
         * estos 'Sin Valor NoData', 'NoData de Capa'(Por defecto) y 'Personalizado'
172
         */
173
        private int                    noDataType          = RasterLibrary.NODATATYPE_LAYER;
174

    
175
        /**
176
         * Lista de transformaciones afines que son aplicadas. Esta lista es
177
         * simplemente un historico que no se utiliza. Es posible utilizarlo para
178
         * recuperar transformaciones anteriores.
179
         */
180
        private Historical             affineTransformList = new Historical();
181
        private CoverageStore          store               = null;
182
        protected String               readingData         = null;
183

    
184
        static {
185
                 RasterLibrary.wakeUp();
186
//                 try {
187
//                         new DefaultRasterIOLibrary().initialize();
188
//                 } catch (NoClassDefFoundError e) {
189
//                         RasterToolsUtil.debug("There was not possible to load drivers", e, null);
190
//                 }
191
        }
192

    
193
        /**
194
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
195
         *
196
         * @param layerName
197
         *            Nombre de la capa..
198
         * @param params
199
         *            Par?metros de carga del formato. El caso m?s simple es la ruta
200
         *            de la capa en disco.
201
         * @param d
202
         *            RasterDriver.
203
         * @param f
204
         *            Fichero.
205
         * @param proj
206
         *            Proyecci?n.
207
         * @return Nueva capa de tipo raster.
208
         * @throws DriverIOException
209
         *
210
         * @deprecated
211
         */
212
        public static FLyrRasterSE createLayer(String layerName, Object params,
213
                        IProjection proj) throws LoadLayerException {
214
                FLyrRasterSE capa = new FLyrRasterSE();
215
                capa.setLoadParams(params);
216
                capa.setName(layerName);
217
                capa.setProjection(proj);
218
                capa.load();
219
                return capa;
220
        }
221

    
222
        /**
223
         * Asigna los par?metros para la carga de la capa
224
         *
225
         * @param param
226
         *            Par?metros.
227
         *
228
         * @deprecated
229
         */
230
        public void setLoadParams(Object param){
231
                this.params = param;
232

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

    
242
        /**
243
         * Obtiene los par?metros para la carga de la capa
244
         *
245
         * @return param Par?metros.
246
         *
247
         * @deprecated
248
         */
249
        public Object getLoadParams() {
250
                return params;
251
        }
252

    
253
        /*
254
         * (non-Javadoc)
255
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setName(java.lang.String)
256
         */
257
        public void setName(String name) {
258
                super.setName(name);
259

    
260
                //Si la capa tiene nombre acivamos el estado awake
261
                if(getLoadParams() != null && name != null)
262
                        try {
263
                                if(isClosed())
264
                                        enableAwake();
265
                        } catch (NotAvailableStateException e) {
266
                                RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
267
                        }
268
        }
269

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

    
283
        /**
284
         * Asignar el estado del raster
285
         * @param status
286
         */
287
        public void setStatus(IStatusRaster status){
288
                this.status = status;
289
        }
290

    
291
        /**
292
         * Obtiene el estado del raster
293
         * @return
294
         */
295
        public IStatusRaster getStatus(){
296
                return this.status;
297
        }
298

    
299
        /*
300
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
301
         */
302
        public void load() throws LoadLayerException {
303
                if (isStopped())
304
                        return;
305

    
306
                enableStopped(); // Paramos la capa mientras se hace un load
307

    
308
                String fName = null;
309
                int test = -1;
310
                if (params != null && params instanceof File) {
311
                        fName = ((File) params).getAbsolutePath();
312
                        test = fName.indexOf("ecwp:");
313
                }
314

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

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

    
346
        /**
347
         * Acciones de inicializaci?n despu?s de que la fuente de datos
348
         * de la capa est? asignada. El tipo de fuente de datos es variable
349
         * puede ser MultiRasterDataset, CompositeDataset u otras que existan e
350
         * implementen IRasterDatasource.
351
         */
352
        public void init() throws LoadLayerException {
353
                if (dataset == null)
354
                        throw new LoadLayerException("Formato no valido", new IOException());
355

    
356
                bufferFactory = new BufferFactory(dataset);
357
                render = new Rendering(bufferFactory);
358
                render.addVisualPropertyListener(this);
359
                initFilters();
360

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

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

    
372
        /**
373
         * Obtiene la proyecci?n del fichero.
374
         * @return IProjection
375
         */
376
        public IProjection readProjection() {
377
                try {
378
                        CRS.setCRSFactory(CRSFactory.cp);
379
                        if( dataset == null )
380
                                return null;
381
                        return CRS.convertWktToIProjection(dataset.getWktProjection());
382
                } catch (RasterDriverException e) {
383
                        RasterToolsUtil.messageBoxError("Problemas accediendo a getWktProjection. Driver no inicializado", this, e);
384
                }
385
                return null;
386
        }
387

    
388
        /**
389
         * Crea el objeto renderizador de raster
390
         * @return Rendering
391
         */
392
        public Rendering getRender() {
393
                if (render == null) {
394
                        render = new Rendering(bufferFactory);
395
                        render.addVisualPropertyListener(this);
396
                }
397
                return render;
398
        }
399

    
400
        /**
401
         * Aplica los filtros noData al layer
402
         * @param rasterSE
403
         * @param filterManager
404
         */
405
        public void applyNoData() {
406
                Boolean noDataEnabled = configuration.getValueBoolean("nodata_transparency_enabled", Boolean.FALSE);
407
                if (noDataEnabled.booleanValue() && getDataSource().isNoDataEnabled()) {
408
                        noDataType = RasterLibrary.NODATATYPE_LAYER;
409
                        Double noDataValue = Double.valueOf(getNoDataValue());
410
                        getDataSource().getTransparencyFilesStatus().setNoData(noDataValue.doubleValue());
411
                } else {
412
                        getDataSource().getTransparencyFilesStatus().activeNoData(false);
413
                        noDataType = RasterLibrary.NODATATYPE_DISABLED;
414
                }
415
        }
416

    
417
        /**
418
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
419
         */
420
        private void initFilters() {
421
                RasterFilterList filterList = new RasterFilterList();
422
                filterList.addEnvParam("IStatistics", getDataSource().getStatistics());
423
                filterList.addEnvParam("MultiRasterDataset", getDataSource());
424

    
425
                if(getDataSource() == null)
426
                        return;
427
                
428
                getDataSource().resetNoDataValue();
429
                applyNoData();
430
                GridTransparency gridTransparency = new GridTransparency(getDataSource().getTransparencyFilesStatus());
431

    
432
                filterList.setInitDataType(getDataType()[0]);
433
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
434

    
435
                // Quitamos la leyenda
436
                lastLegend = null;
437

    
438
                try {
439
                        //Si en la carga del proyecto se carg? una tabla de color asignamos esta
440
                        if(loadedFromProject != null) {
441
                                GridPalette p = new GridPalette(loadedFromProject);
442
                                setLastLegend(p);
443
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
444
                                ctm.addColorTableFilter(p);
445
                        } else
446
                                //sino ponemos la tabla asociada al raster
447
                                if (this.getDataSource().getColorTables()[0] != null) {
448
                                GridPalette p = new GridPalette(getDataSource().getColorTables()[0]);
449
                                setLastLegend(p);
450
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
451
                                ctm.addColorTableFilter(p);
452
                        } else //sino hace lo que dice en las preferencias
453
                                if (getDataType()[0] != IBuffer.TYPE_BYTE)
454
                                        loadEnhancedOrColorTable(filterManager);
455
                        loadedFromProject = null;
456

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

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

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

    
480
                IStatistics stats = getDataSource().getStatistics();
481

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

    
494
                                                        ColorTable colorTable = new ColorTable();
495
                                                        colorTable.setName(paletteName);
496
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
497
                                                        colorTable.setInterpolated(true);
498

    
499
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
500

    
501
                                                        GridPalette p = new GridPalette(colorTable);
502
                                                        setLastLegend(p);
503

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

    
518
                /*EnhancementListManager elm = new EnhancementListManager(filterManager);
519
                elm.addEnhancedFilter(false, stats, 0.0, getRender().getRenderBands());*/
520

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

    
534
        /**
535
         * Devuelve si es reproyectable o no la capa
536
         * @return
537
         */
538
        public boolean isReproyectable() {
539
                if (dataset == null)
540
                        return false;
541

    
542
                int nFiles = dataset.getDatasetCount();
543
                for (int i = 0; i < nFiles; i++)
544
                        if (!dataset.getDataset(i)[0].isReproyectable())
545
                                return false;
546
                return true;
547
        }
548

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

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

    
565
                        enableStopped();
566
                        // callLegendChanged(null);
567

    
568
                        strategy = new RasterDrawStrategy(getMapContext(), this);
569
                        strategy.stackStrategy();
570
                        HashMap tStr = strategy.getStrategy();
571
                        if (tStr != null &&
572
                                tStr.get(this) != null &&
573
                                ((Boolean) (tStr.get(this))).booleanValue() == false) {
574
                                disableStopped();
575
                                return;
576
                        }
577

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

    
622
                                if (mustTileDraw) {
623
                                        Point2D p = vp.getOffset();
624
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
625
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
626
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
627
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
628
                                                // drawing part
629
                                                try {
630
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
631
                                                        draw(image, g, vport, cancel);
632
                                                } catch (InterruptedException e) {
633
                                                        System.out.println("Se ha cancelado el pintado");
634
                                                } catch (InvalidSetViewException e) {
635
                                                        throw new ReadException("Error reading file.", e);
636
                                                } catch (RasterDriverException e) {
637
                                                        throw new ReadException("Error reading file.", e);
638
                                                }  catch (NoninvertibleTransformException e) {
639
                                                        throw new ReadException("Error in the transformation.", e);
640
                                                }
641
                                } else
642
                                        try {
643
                                                draw(image, g, vp, cancel);
644
                                        } catch (InterruptedException e) {
645
                                                System.out.println("Se ha cancelado el pintado");
646
                                        } catch (InvalidSetViewException e) {
647
                                                throw new ReadException("Error reading file.", e);
648
                                        } catch (RasterDriverException e) {
649
                                                throw new ReadException("Error reading file.", e);
650
                                        }
651

    
652
                        }
653
                        //callLegendChanged(null);
654
                } finally {
655
                        disableStopped();
656
                        task.setEvent(null);
657
                }
658
        }
659

    
660
        private void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws RasterDriverException, InvalidSetViewException, InterruptedException {
661
                Envelope adjustedExtent = vp.getAdjustedExtent();
662
                if (adjustedExtent == null)
663
                        return;
664
                Extent e = new Extent(adjustedExtent.getLowerCorner().getX(),
665
                                adjustedExtent.getUpperCorner().getY(), adjustedExtent
666
                                                .getUpperCorner().getX(),
667
                                adjustedExtent
668
                                                .getLowerCorner().getY());
669
                Dimension imgSz = vp.getImageSize();
670
                ViewPortData vp2 = new ViewPortData(vp.getProjection(), e, imgSz );
671
                vp2.setMat(vp.getAffineTransform());
672
                getRender().draw(g, vp2);
673
        }
674

    
675
        /**
676
         * Inserta la proyecci?n.
677
         *
678
         * @param proj Proyecci?n.
679
         */
680
        public void setProjection(IProjection proj) {
681
                super.setProjection(proj);
682
        }
683

    
684
        /*
685
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
686
         */
687
        public Envelope getFullEnvelope() {
688
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
689
                //un extent aunque la capa no est? abierta
690
                if(/*!isOpen() || */dataset == null || dataset.getExtent() == null)
691
                        return null;
692

    
693
                Rectangle2D e = dataset.getExtent().toRectangle2D();
694
                try {
695
                        return geomManager.createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
696
                                        .getMaxY(), SUBTYPES.GEOM2D);
697
                } catch (CreateEnvelopeException e1) {
698
                        logger.error("Error creating the envelope", e);
699
                        return null;
700
                }
701
        }
702

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

    
723
        /*
724
         * (non-Javadoc)
725
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
726
         */
727
        public double getMaxX() {
728
                if(getFullEnvelope() != null)
729
                        return getFullEnvelope().getMaximum(0);
730
                return -1;
731
        }
732

    
733
        /*
734
         * (non-Javadoc)
735
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
736
         */
737
        public double getMaxY() {
738
                if(getFullEnvelope() != null)
739
                        return this.getFullEnvelope().getMaximum(1);
740
                return -1;
741
        }
742

    
743
        /*
744
         * (non-Javadoc)
745
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinX()
746
         */
747
        public double getMinX() {
748
                if(getFullEnvelope() != null)
749
                        return getFullEnvelope().getMinimum(0);
750
                return -1;
751
        }
752

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

    
763
        /* (non-Javadoc)
764
         * @deprecated. See String getInfo(Point p) throws DriverException
765
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
766
         */
767
        public String queryByPoint(Point p) {
768
                if (!isOpen())
769
                        return null;
770
                ColorConversion conv = new ColorConversion();
771

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

    
774
                ArrayList attr = getAttributes();
775
                data += "  <raster\n";
776
                data += "    File=\"" + getFile() + "\"\n";
777
                for (int i = 0; i < attr.size(); i++) {
778
                        Object[] a = (Object[]) attr.get(i);
779

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

    
798
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
799
                return data;
800
        }
801

    
802
        /**
803
         * Transforma un punto real a coordenadas pixel indicando la banda que es usada para la
804
         * transformaci?n. Hay que tener en cuenta que es posible que todas las transformaciones no
805
         * sean iguales en todas la bandas porque puede haber bandas de distinta resoluci?n.
806
         *
807
         * @param numberBand
808
         * @param pReal
809
         * @return
810
         * @throws ReadDriverException
811
         */
812
        private Point2D transformPoint(int numberBand, Point2D pReal) throws NoninvertibleTransformException {
813
                AffineTransform at = this.getDataSource().getAffineTransform(numberBand);
814
                Point2D px = new Point2D.Double();
815
                //px = new Point2D.Double(pReal.getX(), pReal.getY());
816
                at.inverseTransform(pReal, px);
817
                return px;
818
        }
819

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

    
907
        /**
908
         * Filters a string for being suitable as XML Tag, erasing
909
         * all not alphabetic or numeric characters.
910
         * @param s
911
         * @return string normalized
912
         */
913
        private String normalizeAsXMLTag(String s) {
914
                return s.replaceAll("[^a-zA-Z0-9]", "");
915
        }
916

    
917
        /**
918
         * Obtiene atributos a partir de un georasterfile
919
         * @return
920
         */
921
        public ArrayList getAttributes() {
922
                ArrayList attr = new ArrayList();
923
                if(!isOpen())
924
                        return attr;
925
                Object [][] a = {
926
                        {"Filename", dataset.getDataset(0)[0].getFName()},
927
                        {"Filesize", new Long(dataset.getFileSize())},
928
                        {"Width", new Integer((int)dataset.getWidth())},
929
                        {"Height", new Integer((int)dataset.getHeight())},
930
                        {"Bands", new Integer(dataset.getBandCount())}
931
                };
932
                for (int i = 0; i < a.length; i++)
933
                        attr.add(a[i]);
934
                return attr;
935
        }
936

    
937
        /**
938
         * Escribe en el proyecto la capa actual
939
         * @throws XMLException
940
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
941
         */
942
        public XMLEntity getXMLEntity() throws XMLException {
943
                if(isClosed() || isAwake())
944
                        return null;
945

    
946
//                XMLEntity xml = super.getXMLEntity();
947
//                if(getFile() != null)
948
//                        xml.putProperty("file", getFile());
949
//                xml.putProperty("driverName", "gvSIG Raster Driver");
950
//
951
//                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
952
//                if (status == null)
953
//                        status = new StatusLayerRaster();
954
//                status.getXMLEntity(xml, true, this);
955
//
956
//                return xml;
957
                return null;
958
        }
959

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

    
1029
        /* (non-Javadoc)
1030
         * @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)
1031
         */
1032
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
1033
                        double scale, PrintAttributes propeties) throws ReadException {
1034

    
1035
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
1036
                        return;
1037

    
1038
                if (!mustTilePrint)
1039
                        draw(null, g, viewPort, cancel,scale);
1040
                else {
1041
                        // Para no pedir imagenes demasiado grandes, vamos
1042
                        // a hacer lo mismo que hace EcwFile: chunkear.
1043
                        // Llamamos a drawView con cuadraditos m?s peque?os
1044
                        // del BufferedImage ni caso, cuando se imprime viene con null
1045
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1046
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1047

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

    
1051
                        //RasterStats stats = getSource().getFilterStack().getStats();
1052
                        //if(stats != null)
1053
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
1054

    
1055

    
1056
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
1057
                                // Parte que dibuja
1058
                                try {
1059
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1060
                                        draw(null, g, vp, cancel, scale);
1061
                                } catch (NoninvertibleTransformException e) {
1062
                                        throw new ReadException("Error en la transformaci?n.", e);
1063
                                }
1064
                }
1065
        }
1066

    
1067
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
1068
                        double scale) throws ReadException {
1069
                if(!isOpen())
1070
                        return;
1071

    
1072
                // Para no pedir imagenes demasiado grandes, vamos
1073
                // a hacer lo mismo que hace EcwFile: chunkear.
1074
                // Llamamos a drawView con cuadraditos m?s peque?os
1075
                // del BufferedImage ni caso, cuando se imprime viene con null
1076

    
1077
                int numW, numH;
1078
                int stepX, stepY;
1079
                int xProv, yProv;
1080
                int A = 1500;
1081
                int H = 1500;
1082
                int altoAux, anchoAux;
1083

    
1084
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
1085

    
1086
                // Vamos a hacerlo en trozos de AxH
1087
                Rectangle r = g.getClipBounds();
1088
                numW = (r.width) / A;
1089
                numH = (r.height) / H;
1090

    
1091
                double[] srcPts = new double[8];
1092
                double[] dstPts = new double[8];
1093

    
1094
                yProv = r.y;
1095
                for (stepY = 0; stepY < numH + 1; stepY++) {
1096
                        if ((yProv + H) > r.getMaxY())
1097
                                altoAux = (int) r.getMaxY() - yProv;
1098
                        else
1099
                                altoAux = H;
1100

    
1101
                        xProv = r.x;
1102
                        for (stepX = 0; stepX < numW + 1; stepX++) {
1103
                                if ((xProv + A) > r.getMaxX())
1104
                                        anchoAux = (int) r.getMaxX() - xProv;
1105
                                else
1106
                                        anchoAux = A;
1107

    
1108
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
1109

    
1110
                                // Parte que dibuja
1111
                                srcPts[0] = xProv;
1112
                                srcPts[1] = yProv;
1113
                                srcPts[2] = xProv + anchoAux + 1;
1114
                                srcPts[3] = yProv;
1115
                                srcPts[4] = xProv + anchoAux + 1;
1116
                                srcPts[5] = yProv + altoAux + 1;
1117
                                srcPts[6] = xProv;
1118
                                srcPts[7] = yProv + altoAux + 1;
1119

    
1120
                                try {
1121
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
1122
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
1123
                                        // Extent extent = new Extent(rectCuadricula);
1124

    
1125
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
1126
                                        ViewPort vp = viewPort.cloneViewPort();
1127
                                        vp.setImageSize(tam);
1128
                                        Envelope env = geomManager.createEnvelope(rectCuadricula
1129
                                                        .getMinX(), rectCuadricula.getMinY(),
1130
                                                        rectCuadricula.getMaxX(), rectCuadricula.getMaxY(),
1131
                                                        SUBTYPES.GEOM2D);
1132
                                        vp.setEnvelope(env);
1133
                                        vp.setAffineTransform(mat);
1134
                                        draw(null, g, vp, cancel, scale);
1135

    
1136
                                } catch (NoninvertibleTransformException e) {
1137
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
1138
                                } catch (ReadException e) {
1139
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
1140
                                } catch (CreateEnvelopeException e) {
1141
                                        logger.error("Error creating the envelope", e);
1142
                                }
1143
                                // Fin parte que dibuja
1144
                                xProv = xProv + A;
1145
                        }
1146
                        yProv = yProv + H;
1147
                }
1148
        }
1149

    
1150
        /**
1151
         * Borra de la lista de listeners el que se pasa como par?metro.
1152
         *
1153
         * @param o LayerListener a borrar.
1154
         *
1155
         * @return True si ha sido correcto el borrado del Listener.
1156
         */
1157
        public boolean removeLayerListener(LayerListener o) {
1158
                if (this.isRemoveRasterFlag()) {
1159
                        try {
1160
                                enableClosed();
1161
                        } catch (NotAvailableStateException e1) {
1162
                                // No se ha podido cambiar el estado de la capa a cerrado
1163
                        }
1164
                }
1165
                
1166
                // Salva a RMF
1167
                if (this.getDataSource() != null)
1168
                        // Guardamos la GeoReferenciacion de cada dataset
1169
                        try {
1170
                                for (int i = 0; i < getDataSource().getDatasetCount(); i++)
1171
                                        getDataSource().saveObjectToRmf(i, RasterDataset.class, getDataSource().getDataset(i)[0]);
1172
                        } catch (RmfSerializerException e) {
1173
                                RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
1174
                        }
1175

    
1176
                if (this.isRemoveRasterFlag()) {
1177
                        image = null;
1178
                        String[] files = getFileName().clone();
1179
                        if (dataset != null)
1180
                                dataset.close();
1181
                        if (bufferFactory != null)
1182
                                bufferFactory.free();
1183
                        bufferFactory = null;
1184
                        dataset = null;
1185
                        render = null;
1186
                        // System.gc();
1187
                        this.setRemoveRasterFlag(true);
1188

    
1189
                        for (int i = 0; i < files.length; i++) {
1190
                                File file = new File(files[i]);
1191
                                File dirTemp = RasterLibrary.getTemporalFile();
1192
                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
1193
                                        file.delete();
1194

    
1195
                                        // Borramos todos los ficheros que puedan tener relacion con el fichero actual
1196
                                        String basefile = file.getName();
1197
                                        File basepath = file.getParentFile();
1198
                                        int last = basefile.lastIndexOf(".");
1199
                                        if (last != -1)
1200
                                                basefile = basefile.substring(0, last + 1);
1201
                                        File[] list = basepath.listFiles();
1202
                                        for (int j = 0; j < list.length; j++)
1203
                                                if (list[j].getName().startsWith(basefile))
1204
                                                        list[j].delete();
1205
                                }
1206
                        }
1207
                }
1208
                updateDrawVersion();
1209
                return super.layerListeners.remove(o);
1210
        }
1211

    
1212
        /**
1213
         * @return Returns the removeRasterFlag.
1214
         */
1215
        public boolean isRemoveRasterFlag() {
1216
                return removeRasterFlag;
1217
        }
1218

    
1219
        /**
1220
         * Asigna el valor del flag que dice si destruimos la memoria del raster
1221
         * al eliminarlo del TOC o  no.
1222
         * @param removeRasterFlag The removeRasterFlag to set.
1223
         */
1224
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1225
                this.removeRasterFlag = removeRasterFlag;
1226
        }
1227

    
1228
        /*
1229
         * (non-Javadoc)
1230
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1231
         */
1232
        public String getTocImageIcon() {
1233
                return "map-ico-ok";
1234
        }
1235

    
1236
        /*
1237
         *  (non-Javadoc)
1238
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1239
         */
1240
        public int[] getTileSize() {
1241
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1242
                return size;
1243
        }
1244

    
1245
        /*
1246
         *  (non-Javadoc)
1247
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1248
         */
1249
        public boolean isTiled() {
1250
                return mustTileDraw;
1251
        }
1252

    
1253
        /**
1254
         * Obtiene el flag que dice si la imagen est? o no georreferenciada
1255
         * @return true si est? georreferenciada y false si no lo est?.
1256
         */
1257
        public boolean isGeoreferenced() {
1258
                return dataset.isGeoreferenced();
1259
        }
1260

    
1261
        /**
1262
         * Get datasource object
1263
         * @return
1264
         */
1265
        public BufferFactory getBufferFactory(){
1266
                return bufferFactory;
1267
        }
1268

    
1269
        /**
1270
         * Obtiene el valor NoData asociado al raster.
1271
         * @return double
1272
         */
1273
        public double getNoDataValue() {
1274
                if (dataset == null)
1275
                        return RasterLibrary.defaultNoDataValue;
1276
                return dataset.getNoDataValue();
1277
        }
1278

    
1279
        /**
1280
         * Asigna el valor no data asociado a la capa
1281
         * @param nd
1282
         */
1283
        public void setNoDataValue(double nd) {
1284
                if (bufferFactory != null)
1285
                        bufferFactory.setNoDataToFill(nd);
1286
                if (dataset != null)
1287
                        dataset.setNoDataValue(nd);
1288
        }
1289

    
1290
        /*
1291
         * (non-Javadoc)
1292
         * @see org.gvsig.fmap.raster.IRasterOperations#getPXHeight()
1293
         */
1294
        public double getPxHeight() {
1295
                return dataset.getHeight();
1296
        }
1297

    
1298
        /*
1299
         * (non-Javadoc)
1300
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
1301
         */
1302
        public double getPxWidth() {
1303
                return dataset.getWidth();
1304
        }
1305

    
1306
        /*
1307
         * (non-Javadoc)
1308
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCHeight()
1309
         */
1310
        public double getWCHeight() {
1311
                return getFullEnvelope().getMaximum(1);
1312
        }
1313

    
1314
        /*
1315
         * (non-Javadoc)
1316
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
1317
         */
1318
        public double getWCWidth() {
1319
                return getFullEnvelope().getMaximum(0);
1320
        }
1321

    
1322
        /*
1323
         * (non-Javadoc)
1324
         * @see org.gvsig.fmap.raster.IRasterFile#getFileSize()
1325
         */
1326
        public long[] getFileSize(){
1327
                int nFiles = dataset.getDatasetCount();
1328
                long[] s = new long[nFiles];
1329
                for (int i = 0; i < nFiles; i++)
1330
                        s[i] = dataset.getDataset(i)[0].getFileSize();
1331
                return s;
1332
        }
1333

    
1334
        /*
1335
         * (non-Javadoc)
1336
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
1337
         */
1338
        public String[] getFileName(){
1339
                int nFiles = 0;
1340
                if (dataset != null)
1341
                        nFiles = dataset.getDatasetCount();
1342
                String[] s = new String[nFiles];
1343
                for (int i = 0; i < nFiles; i++)
1344
                        s[i] = dataset.getDataset(i)[0].getFName();
1345
                return s;
1346
        }
1347

    
1348
        /*
1349
         * (non-Javadoc)
1350
         * @see org.gvsig.fmap.raster.IRasterFile#getFileCount()
1351
         */
1352
        public int getFileCount() {
1353
                return (dataset != null) ? dataset.getDatasetCount() : 0;
1354
        }
1355

    
1356
        /*
1357
         * (non-Javadoc)
1358
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
1359
         */
1360
        public String getFileFormat() {
1361
                String fName = dataset.getDataset(0)[0].getFName();
1362
                int index = fName.lastIndexOf(".") + 1;
1363
                String ext = null;
1364
                if (index > 0)
1365
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1366
                return ext;
1367
        }
1368

    
1369
        /*
1370
         * (non-Javadoc)
1371
         * @see org.gvsig.fmap.raster.IRasterOperations#getBandCount()
1372
         */
1373
        public int getBandCount() {
1374
                return (dataset != null) ? dataset.getBandCount() : 0;
1375
        }
1376

    
1377
        /*
1378
         * (non-Javadoc)
1379
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1380
         */
1381
        public int[] getDataType() {
1382
                return dataset.getDataType();
1383
        }
1384

    
1385
        /*
1386
         * (non-Javadoc)
1387
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
1388
         */
1389
        public GridTransparency getRenderTransparency() {
1390
                return getRender().getLastTransparency();
1391
        }
1392

    
1393
        /*
1394
         * (non-Javadoc)
1395
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1396
         */
1397
        public RasterFilterList getRenderFilterList() {
1398
                return getRender().getFilterList();
1399
        }
1400

    
1401
        /*
1402
         * (non-Javadoc)
1403
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
1404
         */
1405
        public int[] getRenderBands() {
1406
                return getRender().getRenderBands();
1407
        }
1408

    
1409
        /*
1410
         * (non-Javadoc)
1411
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
1412
         */
1413
        public void setRenderBands(int[] renderBands) {
1414
                getRender().setRenderBands(renderBands);
1415
        }
1416

    
1417
        /*
1418
         * (non-Javadoc)
1419
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
1420
         */
1421
        public void setRenderFilterList(RasterFilterList filterList) {
1422
                getRender().setFilterList(filterList);
1423
        }
1424

    
1425
        /*
1426
         * (non-Javadoc)
1427
         * @see org.gvsig.raster.hierarchy.IRasterDataset#getDataSource()
1428
         */
1429
        public IRasterDataSource getDataSource() {
1430
                return dataset;
1431
        }
1432

    
1433
        /*
1434
         * (non-Javadoc)
1435
         * @see org.gvsig.fmap.raster.IRasterDataset#addFile(java.lang.String)
1436
         */
1437
        public void addFile(String fileName) throws NotSupportedExtensionException, RasterDriverException {
1438
                if (getRender() != null)
1439
                        bufferFactory.addFile(RasterDataset.open(getProjection(), fileName));
1440
        }
1441

    
1442
        /*
1443
         * (non-Javadoc)
1444
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
1445
         */
1446
        public void delFile(String fileName) {
1447
                if (getRender() != null)
1448
                        bufferFactory.removeFile(fileName);
1449
        }
1450

    
1451
        /*
1452
         * (non-Javadoc)
1453
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1454
         */
1455
        public Object getInfo(String key) {
1456
                if (key.equals("DriverName"))
1457
                        return "gvSIG Raster Driver";
1458
                return null;
1459
        }
1460

    
1461
        /*
1462
         * (non-Javadoc)
1463
         * @see org.gvsig.raster.shared.IRasterOperations#getMetadata()
1464
         */
1465
        public DatasetMetadata[] getMetadata() {
1466
                int count = dataset.getDatasetCount();
1467
                DatasetMetadata[] metadata = new DatasetMetadata[count];
1468
                for (int i = 0; i < count; i++)
1469
                        metadata[i] = dataset.getDataset(i)[0].getMetadata();
1470
                return metadata;
1471
        }
1472

    
1473
        /*
1474
         * (non-Javadoc)
1475
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
1476
         */
1477
        public int[] getBandCountFromDataset() {
1478
                int count = dataset.getDatasetCount();
1479
                int[] bands = new int[count];
1480
                for (int i = 0; i < count; i++)
1481
                        bands[i] = dataset.getDataset(i)[0].getBandCount();
1482
                return bands;
1483
        }
1484

    
1485
        /*
1486
         * (non-Javadoc)
1487
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1488
         */
1489
        public String getColorInterpretation(int band, int dataset) {
1490
                if (this.dataset.getDataset(dataset)[0].getColorInterpretation().get(band) == null)
1491
                        return "Undefined";
1492
                return this.dataset.getDataset(dataset)[0].getColorInterpretation().get(band);
1493
        }
1494

    
1495
        /*
1496
         * (non-Javadoc)
1497
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
1498
         */
1499
        public String getWktProjection() throws RasterDriverException {
1500
                return dataset.getWktProjection();
1501
        }
1502

    
1503
        /**
1504
         * Metodo para consultar si una capa puede ser un RGB. Suponemos que es un RGB
1505
         * si el tipo de datos es de tipo byte y su interpretacion de color tiene
1506
         * asignada los tres colores.
1507
         * @return boolean
1508
         */
1509
        public boolean isRGB() {
1510
                if ((dataset == null) || (render == null))
1511
                        return false;
1512

    
1513
// Quitado pq no necesariamente tiene pq tener 3 bandas para ser RGB
1514
//                if (dataset.getBandCount() < 3)
1515
//                        return false;
1516

    
1517
                if (dataset.getDataType()[0] != IBuffer.TYPE_BYTE)
1518
                        return false;
1519

    
1520
                boolean R = false;
1521
                boolean G = false;
1522
                boolean B = false;
1523

    
1524
                int[] renderBands = render.getRenderBands();
1525
                for (int i = 0; i < renderBands.length; i++)
1526
                        if (renderBands[i] >= 0)
1527
                                switch (i) {
1528
                                        case 0:
1529
                                                R = true;
1530
                                                break;
1531
                                        case 1:
1532
                                                G = true;
1533
                                                break;
1534
                                        case 2:
1535
                                                B = true;
1536
                                                break;
1537
                                }
1538

    
1539
                if (R && G && B)
1540
                        return true;
1541

    
1542
                return false;
1543
        }
1544

    
1545
        /**
1546
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1547
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1548
         * cacheado o no dependiendo del tama?o de esta.
1549
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1550
         * @return Grid.
1551
         * @throws InterruptedException
1552
         */
1553
        public Grid getFullGrid(boolean interpolated) throws GridException, InterruptedException {
1554
                BufferFactory bf = getBufferFactory();
1555
                bf.clearDrawableBand();
1556
                bf.setAllDrawableBands();
1557
                try {
1558
                        bf.setAreaOfInterest();
1559
                } catch (RasterDriverException e) {
1560
                        throw new GridException("Error reading buffer");
1561
                }
1562
                return new Grid(bf, interpolated);
1563
        }
1564

    
1565
        /**
1566
         * Obtiene el grid de la capa completa. Esta llamada devuelve un buffer de solo lectura
1567
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1568
         * @return Grid.
1569
         * @throws InterruptedException
1570
         */
1571
        public Grid getReadOnlyFullGrid(boolean interpolated) throws GridException, InterruptedException {
1572
                BufferFactory bf = getBufferFactory();
1573
                bf.setReadOnly(true);
1574
                bf.clearDrawableBand();
1575
                bf.setAllDrawableBands();
1576
                try {
1577
                        bf.setAreaOfInterest();
1578
                } catch (RasterDriverException e) {
1579
                        throw new GridException("Error reading buffer");
1580
                }
1581
                return new Grid(bf, interpolated);
1582
        }
1583

    
1584
        /**
1585
         * Obtiene el tama?o de celda de la fuente de datos
1586
         * @return double con el tama?o de celda
1587
         */
1588
        public double getCellSize() {
1589
                return (getDataSource() != null) ? getDataSource().getCellSize() : 1;
1590
        }
1591

    
1592
        /*
1593
         * (non-Javadoc)
1594
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1595
         */
1596
        public Extent getFullRasterExtent() {
1597
                return this.getDataSource().getExtent();
1598
        }
1599

    
1600

    
1601
        /**
1602
         * Devuelve el fichero asociado a la capa o null si no tiene.
1603
         * @return Fichero.
1604
         */
1605
        public File getFile() {
1606
                return (params instanceof File) ? ((File)params) : null;
1607
        }
1608

    
1609
        /**
1610
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1611
         * @param file Fichero a consultar
1612
         * @return true si es aceptado y false si no lo es.
1613
         */
1614
        public static boolean isFileAccepted(File file) {
1615
                return RasterDataset.fileIsSupported(file.getName());
1616
        }
1617

    
1618
        /*
1619
         * (non-Javadoc)
1620
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1621
         */
1622
        public boolean existColorTable() {
1623
                return getRender().existColorTable();
1624
        }
1625

    
1626
        /*
1627
         * (non-Javadoc)
1628
         * @see org.gvsig.raster.hierarchy.IRasterRendering#existsAlphaBand()
1629
         */
1630
        public boolean existsAlphaBand() {
1631
                if(getDataSource().getColorInterpretation() != null)
1632
                        return getDataSource().getColorInterpretation().isAlphaBand();
1633
                else
1634
                        return false;
1635
        }
1636

    
1637
        /*
1638
         * (non-Javadoc)
1639
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getAlphaBandNumber()
1640
         */
1641
        public int getAlphaBandNumber() {
1642
                if(getDataSource().getColorInterpretation() != null)
1643
                        return getDataSource().getColorInterpretation().getBand(DatasetColorInterpretation.ALPHA_BAND);
1644
                return -1;
1645
        }
1646

    
1647
        /**
1648
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1649
         * capa busque una leyenda valida.
1650
         * @param ct
1651
         */
1652
        public void setLastLegend(ColorTable ct) {
1653
                lastLegend = ColorTableLegend.createLegend(ct);
1654
        }
1655

    
1656
        /**
1657
         * Devuelve la Leyenda de la capa.
1658
         * @return Leyenda.
1659
         */
1660
        public ILegend getLegend() {
1661
                if (lastLegend != null)
1662
                        return lastLegend;
1663

    
1664
                return null;
1665
        }
1666

    
1667
        /*
1668
         * (non-Javadoc)
1669
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1670
         */
1671
        public void addLegendListener(LegendListener listener) {
1672
                layerChangeSupport.addLayerListener(listener);
1673
        }
1674

    
1675
        /*
1676
         *  (non-Javadoc)
1677
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1678
         */
1679
        public int getShapeType() {
1680
                return TYPES.SURFACE;
1681
        }
1682

    
1683
        /*
1684
         * (non-Javadoc)
1685
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1686
         */
1687
        public void removeLegendListener(LegendListener listener) {
1688
                layerChangeSupport.removeLayerListener(listener);
1689
        }
1690

    
1691
        /**
1692
         * Metodo que obtiene si un punto cae dentro de los l?mites de la capa
1693
         * o fuera de ellos.
1694
         * @param p Punto a calcular
1695
         * @return true si est? dentro de los l?mites y false si est? fuera
1696
         */
1697
        public boolean isInside(Point2D p) {
1698
                 return getDataSource().isInside(p);
1699
        }
1700

    
1701
        /**
1702
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1703
         * @return AffineTransform
1704
         */
1705
        public AffineTransform getAffineTransform(int band) {
1706
                return getDataSource().getAffineTransform(band);
1707
        }
1708

    
1709
        /**
1710
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1711
         * @return AffineTransform
1712
         */
1713
        public AffineTransform getAffineTransform() {
1714
                return getDataSource().getAffineTransform(0);
1715
        }
1716

    
1717
        /**
1718
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista
1719
         * @param transf
1720
         */
1721
        public void setAffineTransform(AffineTransform transf) {
1722
                if(transf == null)
1723
                        return;
1724
                affineTransformList.add(transf);
1725
                getDataSource().setAffineTransform(transf);
1726
                updateDrawVersion();
1727
        }
1728

    
1729
        /**
1730
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista.
1731
         * Esta versi?n no guarda en el historico.
1732
         * @param transf
1733
         */
1734
        public void setAT(AffineTransform transf) {
1735
                getDataSource().setAffineTransform(transf);
1736
                updateDrawVersion();
1737
        }
1738

    
1739
        /**
1740
         * Obtiene la lista de transformaciones que se han ido aplicando al raster.
1741
         * @return Historical. Lista de AffineTransform
1742
         */
1743
        public Historical getAffineTransformHistorical() {
1744
                return this.affineTransformList;
1745
        }
1746

    
1747
        /**
1748
         * Salva la georreferenciaci?n a fichero rmf.
1749
         * @param fName
1750
         * @throws RmfSerializerException
1751
         */
1752
        public void saveGeoToRmf() throws RmfSerializerException {
1753
                if (!isOpen())
1754
                        return;
1755

    
1756
                // Guardamos la GeoReferenciacion de cada dataset
1757
                for (int i = 0; i < getDataSource().getDatasetCount(); i++)
1758
                        getDataSource().saveObjectToRmf(i, RasterDataset.class, getDataSource().getDataset(i)[0]);
1759

    
1760
                affineTransformList.clear();
1761
                affineTransformList.add(this.getAffineTransform());
1762
        }
1763

    
1764
        /*
1765
         * (non-Javadoc)
1766
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1767
         */
1768
        public boolean isActionEnabled(int action) {
1769
                switch (action) {
1770
                        case IRasterLayerActions.BANDS_FILE_LIST:
1771
                                if (existColorTable())
1772
                                        return false;
1773
                                break;
1774
                        case IRasterLayerActions.BANDS_RGB:
1775
                                if (existColorTable())
1776
                                        return false;
1777
                                break;
1778
                        case IRasterLayerActions.REPROJECT:
1779
                                if (!isReproyectable())
1780
                                        return false;
1781
                                break;
1782
                        case IRasterLayerActions.CREATEOVERVIEWS:
1783
                                return overviewsSupport();
1784
                        case IRasterLayerActions.OPACITY:
1785
                        case IRasterLayerActions.TRANSPARENCY:
1786
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1787
                        case IRasterLayerActions.ENHANCED:
1788
                        case IRasterLayerActions.PANSHARPENING:
1789
                        case IRasterLayerActions.SELECT_LAYER:
1790
                        case IRasterLayerActions.SAVE_COLORINTERP:
1791
                                return true;
1792
                        case IRasterLayerActions.REMOTE_ACTIONS:
1793
                                return false;
1794
                }
1795
                return true;
1796
        }
1797

    
1798
        /*
1799
         * (non-Javadoc)
1800
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1801
         */
1802
        public void setVisible(boolean visibility) {
1803
                if(visibility)
1804
                        state.disableStopped();
1805
                else
1806
                        enableStopped();
1807

    
1808
                if(isAwake() || isClosed())
1809
                        try {
1810
                                this.load();
1811
                        } catch (LoadLayerException e) {
1812
                                e.printStackTrace();
1813
                        }
1814

    
1815
                /*
1816
                 * Cuando se modifica la visibilidad de una capa raster se hace un updateDrawVersion de todas las
1817
                 * capas raster de ese MapContext. Esto es porque la estrategia utilizada por RasterDrawStrategy hace
1818
                 * que se cacheen en blanco las capas raster que est?n ocultas debajo de otras. Al hacer invisibles las
1819
                 * de arriba la cache que estaba en blanco hace que no se pinte nada. Para evitar esto las marcamos todas
1820
                 * como que han sido modificadas para que se vuelvan a leer.
1821
                 */
1822
                if(getMapContext() != null) {
1823
                        ArrayList listLayers = new ArrayList();
1824
                        listLayers = RasterDrawStrategy.getLayerList(getMapContext().getLayers(), listLayers);
1825
                        for (int i = 0; i < listLayers.size(); i++)
1826
                                if(listLayers.get(i) instanceof FLyrRasterSE)
1827
                                        ((FLyrRasterSE)listLayers.get(i)).updateDrawVersion();
1828
                }
1829

    
1830
                super.setVisible(visibility);
1831
        }
1832

    
1833
        /**
1834
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1835
         * @return valor de transparencia
1836
         */
1837
        public int getTransparency() {
1838
                try {
1839
                        return getRenderTransparency().getOpacity();
1840
                } catch (NullPointerException e) {
1841
                        return super.getTransparency();
1842
                }
1843
        }
1844

    
1845
        /**
1846
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1847
         * o no.
1848
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1849
         */
1850
        public boolean isTransparent() {
1851
                return getRenderTransparency().isTransparencyActive();
1852
        }
1853

    
1854
        /**
1855
         * Asigna la transparencia de la siguiente renderizaci?n
1856
         * @param valor de transparencia
1857
         */
1858
        public void setTransparency(int trans) {
1859
                super.setTransparency(trans);
1860
                try {
1861
                        getRenderTransparency().setOpacity(trans);
1862
                        getRenderTransparency().activeTransparency();
1863
                } catch (NullPointerException e) {
1864
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1865
                }
1866
        }
1867

    
1868
        /*
1869
         * (non-Javadoc)
1870
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getLastRenderBuffer()
1871
         */
1872
        public IBuffer getLastRenderBuffer() {
1873
                return getRender().getLastRenderBuffer();
1874
        }
1875

    
1876
        /**
1877
         *
1878
         * @return ROIs asociadas a la capa raster.
1879
         */
1880
        public ArrayList<ROI> getRois() {
1881
                return rois;
1882
        }
1883

    
1884
        /**
1885
         * Establece las ROI asociadas a la capa raster.
1886
         *
1887
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1888
         */
1889
        public void setRois(ArrayList<ROI> rois) {
1890
                this.rois = rois;
1891
        }
1892

    
1893
        /**
1894
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1895
         * devolver? null.
1896
         * @return TreeMap con la lista de capas a dibujar
1897
         */
1898
        public HashMap getRasterStrategy() {
1899
                if(strategy != null)
1900
                        return strategy.getStrategy();
1901
                return null;
1902
        }
1903

    
1904
        /**
1905
         * Devuelve el tipo de valor de NoData asociado a la capa.
1906
         * Sirve para diferenciar los estados seleccionados por el usuario. Siendo
1907
         * estos '0: Sin Valor NoData', '1: NoData de Capa'(Por defecto) y '2: Personalizado'
1908
         */
1909
        /**
1910
         * @return the noDataType
1911
         */
1912
        public int getNoDataType() {
1913
                return noDataType;
1914
        }
1915

    
1916
        /**
1917
         * @param noDataType the noDataType to set
1918
         */
1919
        public void setNoDataType(int noDataType) {
1920
                this.noDataType = noDataType;
1921
                if (dataset != null)
1922
                        dataset.setNoDataEnabled(noDataType != RasterLibrary.NODATATYPE_DISABLED);
1923
        }
1924

    
1925
        /**
1926
         * @return the configuration
1927
         */
1928
        static public IConfiguration getConfiguration() {
1929
                return configuration;
1930
        }
1931

    
1932
        /**
1933
         * @param configuration the configuration to set
1934
         */
1935
        static public void setConfiguration(IConfiguration configuration) {
1936
                FLyrRasterSE.configuration = configuration;
1937
        }
1938

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

    
1958
        /**
1959
         * Devuelve si la capa tiene soporte para poder generar overviews
1960
         * @return
1961
         */
1962
        public boolean overviewsSupport() {
1963
                if ((getDataSource() != null) && (getDataSource().overviewsSupport()))
1964
                        return true;
1965

    
1966
                return false;
1967
        }
1968

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

    
1982
        /*
1983
         * (non-Javadoc)
1984
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
1985
         */
1986
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1987
                updateDrawVersion();
1988
        }
1989

    
1990
        /*****************************************************/
1991
        //Utils
1992

    
1993
        /**
1994
         * Ajusta las coordenadas especificadas en el par?metro al ?rea m?xima
1995
         * del raster en p?xeles.
1996
         * @param req Punto a ajustar dentro del extener del raster
1997
         */
1998
        public Point2D adjustWorldRequest(Point2D req) {
1999
                Envelope ext = null;
2000

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

    
2007
        /*
2008
         * (non-Javadoc)
2009
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#cloneLayer()
2010
         */
2011
        public FLayer cloneLayer() throws Exception {
2012
                FLyrRasterSE newLayer = FLyrRasterSE.createLayer(this.getName(), params, this.getProjection());
2013
                for (int i = 0; i < dataset.getDatasetCount(); i++) {
2014
                        String name = dataset.getDataset(i)[0].getFName();
2015
                        if (!(dataset instanceof CompositeDataset) && !name.equals(this.getName()))
2016
                                newLayer.addFile(name);
2017
                }
2018
                ArrayList filters = getRender().getFilterList().getStatusCloned();
2019

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

    
2028
                //Asignamos el entorno
2029
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
2030
                newLayer.getRender().getFilterList().setStatus(filters);
2031

    
2032
                // Asignamos los valores noData del original
2033
                newLayer.setNoDataValue(getNoDataValue());
2034
                newLayer.setNoDataType(getNoDataType());
2035
                newLayer.applyNoData();
2036

    
2037
                return newLayer;
2038
        }
2039
        
2040
        /**
2041
         * Gets a layer which the source is a file
2042
         * @return
2043
         */
2044
        public FLayer getFileLayer() {
2045
                try {
2046
                        return cloneLayer();
2047
                } catch (Exception e) {
2048
                }
2049
                return null;
2050
        }
2051

    
2052
        /*****************************************************/
2053

    
2054
        public void disableStopped() {state.disableStopped();}
2055

    
2056
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
2057

    
2058
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
2059

    
2060
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
2061

    
2062
        public void enableStopped() {state.enableStopped();}
2063

    
2064
        public boolean isAwake() {return state.isAwake();}
2065

    
2066
        public boolean isClosed() {return state.isClosed();}
2067

    
2068
        public boolean isOpen() {return state.isOpen();}
2069

    
2070
        public boolean isStopped() {return state.isStopped();}
2071

    
2072

    
2073
        public Set getMetadataChildren() {
2074
                // TODO Auto-generated method stub
2075
                return null;
2076
        }
2077

    
2078
        public Object getMetadataID() {
2079
                // TODO: create a more correct implementation with a real unique ID,
2080
                // maybe extracted from the raster driver. 
2081
                return getName();
2082
        }
2083

    
2084
        public String getMetadataName() {
2085
                // TODO Auto-generated method stub
2086
                return null;
2087
        }
2088

    
2089
        /*
2090
         * (non-Javadoc)
2091
         * @see org.gvsig.fmap.mapcontext.layers.operations.SingleLayer#getDataStore()
2092
         */
2093
        public DataStore getDataStore() {
2094
                return this.store;
2095
        }
2096

    
2097
        /*
2098
         * (non-Javadoc)
2099
         * @see org.gvsig.fmap.mapcontext.layers.operations.SingleLayer#setDataStore(org.gvsig.fmap.dal.DataStore)
2100
         */
2101
        public void setDataStore(DataStore dataStore) throws LoadLayerException {
2102
                this.store = (CoverageStore) dataStore;
2103
                // TODO temporal
2104
                RasterStoreParameters params = (RasterStoreParameters)store.getParameters();
2105
                this.setLoadParams(params.getFile());
2106
                if (params.getSRS() != null)
2107
                        this.setProjection(params.getSRS());
2108
                this.load();
2109
        }
2110
        
2111
        /**
2112
         * Returns true if exists a process reading data from this layer
2113
         * @return
2114
         */
2115
        public boolean isReadingData() {
2116
                return readingData != null;
2117
        }
2118

    
2119
        /**
2120
         * When a process is using information of this layer this variable will contain
2121
         * the thread ID.
2122
         * @param readingData
2123
         */
2124
        public synchronized void setReadingData(String readingData) {
2125
                this.readingData = readingData;
2126
        }
2127

    
2128
        public Iterator getInfo(Point p, double tolerance, Cancellable cancel)
2129
                        throws LoadLayerException, DataException {
2130
                // TODO Auto-generated method stub
2131
                return null;
2132
        }
2133

    
2134
        @Override
2135
        protected void doDispose() throws BaseException {
2136
                // Nothing to do
2137
        }
2138

    
2139
        @Override
2140
        public void loadFromState(PersistentState state)
2141
                        throws PersistenceException {
2142
                super.loadFromState(state);
2143
                
2144
                String fileName = state.getString("file");
2145
                if (fileName != null){                        
2146
                        params = new File(fileName);
2147
                }
2148
                
2149
                status = (IStatusRaster)state.get("status");
2150
                status.setStateProperties(true, this);
2151
                
2152
                render = (Rendering)state.get("render");
2153
        }
2154

    
2155
        @Override
2156
        public void saveToState(PersistentState state) throws PersistenceException {
2157
                super.saveToState(state);
2158
                
2159
//                if(isClosed() || isAwake())
2160
//                        return;
2161
                
2162
                if(getFile() != null){
2163
                        state.set("file", getFile().toString());
2164
                }                
2165

    
2166
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
2167
                if (status == null)
2168
                        status = new StatusLayerRaster();
2169
                
2170
                state.set("render", render);                
2171
                
2172
                status.setStateProperties(true, this);
2173
                state.set("status", status);                                
2174
        }        
2175
        
2176
        public static void registerPersistent() {
2177
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
2178
                DynStruct definition = manager.addDefinition(
2179
                                FLyrRasterSE.class,
2180
                                PERSISTENT_NAME,
2181
                                PERSISTENT_DESCRIPTION,
2182
                                null, 
2183
                                null
2184
                );
2185
                definition.addDynFieldString("file").setMandatory(false);
2186
                definition.addDynFieldString("driverName").setMandatory(true);
2187
                definition.addDynFieldString("render").setMandatory(false);
2188
        }
2189
}