Statistics
| Revision:

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

History | View | Annotate | Download (67.4 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.Set;
35

    
36
import org.cresques.cts.IProjection;
37
import org.slf4j.Logger;
38
import org.slf4j.LoggerFactory;
39

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

    
122

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
304
                enableStopped(); // Paramos la capa mientras se hace un load
305

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

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

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

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

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

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

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

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

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

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

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

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

    
430
                filterList.setInitDataType(getDataType()[0]);
431
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
432

    
433
                // Quitamos la leyenda
434
                lastLegend = null;
435

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

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

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

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

    
478
                IStatistics stats = getDataSource().getStatistics();
479

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

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

    
497
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
498

    
499
                                                        GridPalette p = new GridPalette(colorTable);
500
                                                        setLastLegend(p);
501

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

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

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

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

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

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

    
559
                try {
560
                        if (!isOpen())
561
                                return;
562

    
563
                        enableStopped();
564
                        // callLegendChanged(null);
565

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1033
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
1034
                        return;
1035

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

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

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

    
1053

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

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

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

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

    
1082
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
1083

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

    
1089
                double[] srcPts = new double[8];
1090
                double[] dstPts = new double[8];
1091

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

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

    
1106
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
1107

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

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

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

    
1134
                                } catch (NoninvertibleTransformException e) {
1135
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
1136
                                } catch (ReadException e) {
1137
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
1138
                                } catch (CreateEnvelopeException e) {
1139
                                        logger.error("Error creating the envelope", e);
1140
                                } catch (CloneNotSupportedException e) {
1141
                                    logger.error("Excepci?n :", 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 DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel)
2129
                        throws LoadLayerException, DataException {
2130
        return this.getInfo(p, tolerance, cancel, true);
2131
        }
2132

    
2133
    public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel,
2134
        boolean fast) throws LoadLayerException, DataException {
2135
        // TODO: pending to be implemented
2136
        return null;
2137
    }
2138

    
2139
        @Override
2140
        protected void doDispose() throws BaseException {
2141
                // Nothing to do
2142
        }
2143

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

    
2160
        @Override
2161
        public void saveToState(PersistentState state) throws PersistenceException {
2162
                super.saveToState(state);
2163
                
2164
//                if(isClosed() || isAwake())
2165
//                        return;
2166
                
2167
                if(getFile() != null){
2168
                        state.set("file", getFile().toString());
2169
                }                
2170

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