Statistics
| Revision:

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

History | View | Annotate | Download (45.3 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.lang.reflect.Constructor;
33
import java.lang.reflect.InvocationTargetException;
34
import java.util.ArrayList;
35

    
36
import javax.print.attribute.PrintRequestAttributeSet;
37
import javax.swing.ImageIcon;
38

    
39
import org.apache.log4j.Logger;
40
import org.cresques.cts.IProjection;
41
import org.gvsig.fmap.raster.legend.ColorTableLegend;
42
import org.gvsig.raster.RasterLibrary;
43
import org.gvsig.raster.buffer.BufferFactory;
44
import org.gvsig.raster.dataset.CompositeDataset;
45
import org.gvsig.raster.dataset.FileNotOpenException;
46
import org.gvsig.raster.dataset.IBuffer;
47
import org.gvsig.raster.dataset.IRasterDataSource;
48
import org.gvsig.raster.dataset.InvalidSetViewException;
49
import org.gvsig.raster.dataset.MosaicNotValidException;
50
import org.gvsig.raster.dataset.MultiRasterDataset;
51
import org.gvsig.raster.dataset.NotSupportedExtensionException;
52
import org.gvsig.raster.dataset.RasterDataset;
53
import org.gvsig.raster.dataset.RasterDriverException;
54
import org.gvsig.raster.dataset.properties.DatasetMetadata;
55
import org.gvsig.raster.datastruct.ColorTable;
56
import org.gvsig.raster.datastruct.Extent;
57
import org.gvsig.raster.datastruct.ViewPortData;
58
import org.gvsig.raster.grid.Grid;
59
import org.gvsig.raster.grid.GridPalette;
60
import org.gvsig.raster.grid.GridTransparency;
61
import org.gvsig.raster.grid.filter.RasterFilterList;
62
import org.gvsig.raster.grid.filter.RasterFilterListManager;
63
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
64
import org.gvsig.raster.grid.filter.enhancement.EnhancementListManager;
65
import org.gvsig.raster.grid.render.Rendering;
66
import org.gvsig.raster.hierarchy.IRasterDataset;
67
import org.gvsig.raster.hierarchy.IRasterOperations;
68
import org.gvsig.raster.hierarchy.IRasterProperties;
69
import org.gvsig.raster.hierarchy.IStatistics;
70
import org.gvsig.raster.util.Historical;
71
import org.gvsig.raster.util.MathUtils;
72

    
73
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
74
import com.iver.andami.PluginServices;
75
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
76
import com.iver.cit.gvsig.fmap.ViewPort;
77
import com.iver.cit.gvsig.fmap.core.FShape;
78
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
79
import com.iver.cit.gvsig.fmap.layers.FLayer;
80
import com.iver.cit.gvsig.fmap.layers.FLyrDefault;
81
import com.iver.cit.gvsig.fmap.layers.LayerChangeSupport;
82
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
83
import com.iver.cit.gvsig.fmap.layers.LayerListener;
84
import com.iver.cit.gvsig.fmap.layers.LegendListener;
85
import com.iver.cit.gvsig.fmap.layers.Tiling;
86
import com.iver.cit.gvsig.fmap.layers.XMLException;
87
import com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable;
88
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
89
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
90
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
91
import com.iver.cit.gvsig.fmap.rendering.ILegend;
92
import com.iver.cit.gvsig.project.documents.view.gui.IView;
93
import com.iver.cit.gvsig.project.documents.view.gui.View;
94
import com.iver.utiles.NotExistInXMLEntity;
95
import com.iver.utiles.XMLEntity;
96
import com.iver.utiles.swing.threads.Cancellable;
97
/**
98
 * Capa raster
99
 * @author Nacho Brodin (nachobrodin@gmail.com)
100
 */
101
public class FLyrRasterSE extends FLyrDefault
102
        implements IRasterProperties, IRasterDataset, InfoByPoint, Classifiable,
103
        IRasterOperations, IRasterLayerActions, ILayerState {
104
        public static double             noDataDefault      = -99999;
105
        boolean                          isPrinting         = false;
106
        boolean                          mustTileDraw       = false;
107
        boolean                          mustTilePrint      = true;
108
        private int                      maxTileDrawWidth   = 200;
109
        private int                      maxTileDrawHeight  = 200;
110
        int                              maxTilePrintWidth  = 1500;
111
        int                              maxTilePrintHeight = 1500;
112
        protected IStatusRaster          status             = null;
113
        private boolean                  firstLoad          = false;
114
        private boolean                  removeRasterFlag   = true;
115
        private Object                   params             = null;
116
        protected IRasterDataSource      dataset            = null;
117
        protected Rendering              render             = null;
118
        protected BufferFactory          bufferFactory      = null;
119
        private int                      posX               = 0;
120
        private int                      posY               = 0;
121
        private double                   posXWC             = 0;
122
        private int                      posYWC             = 0;
123
        private int                      r                  = 0;
124
        private int                      g                  = 0;
125
        private int                      b                  = 0;
126
        private LayerChangeSupport       layerChangeSupport = new LayerChangeSupport();
127
        public double                    noDataValue        = -99999;
128
        private FLyrState                state              = new FLyrState();
129
        private ArrayList                filterArguments    = null;
130
        protected ILegend                lastLegend         = null;
131
        private ArrayList                                 rois               = null;
132
        
133
        /**
134
         * Lista de transformaciones afines que son aplicadas. Esta lista es simplemente un
135
         * historico que no se utiliza. Es posible utilizarlo para recuperar transformaciones
136
         * anteriores.
137
         */
138
        private Historical               affineTransformList = new Historical();
139
        
140
        static {
141
                 RasterLibrary.wakeUp();
142
        }
143

    
144
        /**
145
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
146
         * @param layerName Nombre de la capa.
147
         * @param d RasterDriver.
148
         * @param f Fichero.
149
         * @param proj Proyecci?n.
150
         * @return Nueva capa de tipo raster.
151
         * @throws DriverIOException
152
         */
153
        public static FLyrRasterSE createLayer(String layerName, Object params,
154
                        IProjection proj) throws LoadLayerException {
155
                FLyrRasterSE capa = new FLyrRasterSE();
156
                capa.setLoadParams(params);
157
                capa.setName(layerName);
158
                capa.setProjection(proj);
159
                capa.load();
160
                return capa;
161
        }
162

    
163
        /**
164
         * Asigna los par?metros para la carga de la capa
165
         * @param param Par?metros.
166
         */
167
        public void setLoadParams(Object param){
168
                this.params = param;
169
                
170
                //Si la capa tiene nombre acivamos el estado awake
171
                if(params != null && getName() != null) {
172
                        try {
173
                                enableAwake();
174
                        } catch (NotAvailableStateException e) {
175
                                Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
176
                        }
177
                }
178
        }
179

    
180
        /**
181
         * Obtiene los par?metros para la carga de la capa
182
         * @return param Par?metros.
183
         */
184
        public Object getLoadParams() {
185
                return params;
186
        }
187
        
188
        /*
189
         * (non-Javadoc)
190
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setName(java.lang.String)
191
         */
192
        public void setName(String name) {
193
                super.setName(name);
194

    
195
                //Si la capa tiene nombre acivamos el estado awake
196
                if(getLoadParams() != null && name != null) {
197
                        try {
198
                                enableAwake();
199
                        } catch (NotAvailableStateException e) {
200
                                Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
201
                        }
202
                }
203
        }
204

    
205
        /**
206
         * Redefine wakeUp de FLyrDefault
207
         */
208
        public void wakeUp(){
209
        }
210

    
211
        /**
212
         * Asignar el estado del raster
213
         * @param status
214
         */
215
        public void setStatus(IStatusRaster status){
216
                this.status = status;
217
        }
218

    
219
        /**
220
         * Obtiene el estado del raster
221
         * @return
222
         */
223
        public IStatusRaster getStatus(){
224
                return this.status;
225
        }
226

    
227
        /*
228
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
229
         */
230
        public void load() throws LoadLayerException {
231
                if(isStopped())
232
                        return;
233
                
234
                enableStopped(); //Paramos la capa mientras se hace un load
235
                
236
                String fName = null;
237
                int test = -1;
238
                if (params != null && params instanceof File) {
239
                        fName = ((File) params).getAbsolutePath();
240
                        test = fName.indexOf("ecwp:");
241
                }
242

    
243
                if (test != -1) {
244
                        String urlECW = fName.substring(test + 6);
245
                        fName = "ecwp://" + urlECW;
246
                        System.err.println(test + " " + fName);
247
                }
248

    
249
                try {
250
                        if(params instanceof String[][]) {
251
                                String[][] files = (String[][])params;
252
                                MultiRasterDataset[][] dt = new MultiRasterDataset[files.length][files[0].length];
253
                                for (int i = 0; i < files.length; i++) 
254
                                        for (int j = 0; j < files[i].length; j++) 
255
                                                dt[i][j] = MultiRasterDataset.open(getProjection(), files[i][j]);
256
                                dataset = new CompositeDataset(dt);
257
                        } else if (params == null || params instanceof File) {
258
                                if(fName != null)
259
                                        dataset = MultiRasterDataset.open(getProjection(), fName);
260
                        } else
261
                                dataset = MultiRasterDataset.open(getProjection(), params);
262
                } catch (NotSupportedExtensionException e) {
263
                        throw new LoadLayerException("Formato no valido", e);
264
                } catch (RasterDriverException e) {
265
                        throw new LoadLayerException("Formato no valido", e);
266
                } catch (MosaicNotValidException e) {
267
                        throw new LoadLayerException("Error en el mosaico", e);
268
                } catch (Exception e) {
269
                        throw new LoadLayerException("No existe la capa.", e);
270
                }
271
                if(dataset != null)
272
                        this.init();
273
        }
274

    
275
        /**
276
         * Acciones de inicializaci?n despu?s de que la fuente de datos
277
         * de la capa est? asignada. El tipo de fuente de datos es variable
278
         * puede ser MultiRasterDataset, CompositeDataset u otras que existan e
279
         * implementen IRasterDatasource.
280
         */
281
        public void init() throws LoadLayerException {
282
                if (dataset == null)
283
                        throw new LoadLayerException("Formato no valido", new IOException());
284
                bufferFactory = new BufferFactory(dataset);
285
                render = new Rendering(bufferFactory);
286
                initFilters();
287
                
288
                //Inicializaci?n del historico de transformaciones
289
                affineTransformList.clear();
290
                affineTransformList.add(this.getAffineTransform());
291
                try {
292
                        enableOpen();
293
                } catch (NotAvailableStateException e) {
294
                        Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Awake=" + isAwake(), e);
295
                }
296
        }
297
        
298
        /**
299
         * Crea el objeto renderizador de raster
300
         * @return Rendering
301
         */
302
        public Rendering getRender() {
303
                if (render == null)
304
                        render = new Rendering(bufferFactory);
305
                return render;
306
        }
307

    
308
        /**
309
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
310
         */
311
        private void initFilters() {
312
                RasterFilterList filterList = new RasterFilterList();
313
                filterList.addEnvParam("IStatistics", getDataSource().getStatistics());
314
                filterList.addEnvParam("MultiRasterDataset", getDataSource());
315
                GridTransparency gridTransparency = new GridTransparency(getDataSource().getTransparencyFilesStatus());
316
                // Inicializo la transparencia tanto para el filtro como para el render
317
                filterList.addEnvParam("Transparency", gridTransparency);
318
                getRender().setLastTransparency(gridTransparency);
319

    
320
                filterList.setInitDataType(getDataType()[0]);
321
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
322

    
323
                if (this.getDataSource().getColorTables()[0] != null) {
324
                        GridPalette p = new GridPalette(getDataSource().getColorTables()[0]);
325
                        setLastLegend(p);
326
                        ColorTableListManager ctm = new ColorTableListManager(filterManager);
327
                        ctm.addColorTableFilter(p);
328
                } else {
329
                        if (getDataType()[0] != IBuffer.TYPE_BYTE) {
330
                                IStatistics stats = getDataSource().getStatistics();
331
                                EnhancementListManager elm = new EnhancementListManager(filterManager);
332
                                elm.addEnhancedFilter(false, stats, 0.0, getRender().getRenderBands());
333
                        }
334
                }
335

    
336
                getRender().setFilterList(filterList);
337
        }
338

    
339
        /**
340
         * @throws ReadDriverException 
341
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
342
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
343
         *                 com.iver.utiles.swing.threads.Cancellable)
344
         */
345
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadDriverException {
346
                if(!isOpen())
347
                        return;
348
                
349
                enableStopped();
350
                //callLegendChanged(null);
351
                
352
                if (isWithinScale(scale)) {
353

    
354
                        if (status != null && firstLoad) {
355
                                if (mustTileDraw) {
356
                                        Point2D p = vp.getOffset();
357
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
358
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
359
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
360
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
361
                                                // drawing part
362
                                                try {
363
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
364
                                                        // g.setClip(tiles.getClip(tileNr).x, tiles.getClip(tileNr).y, tiles.getClip(tileNr).width - 5, tiles.getClip(tileNr).height);
365
                                                        try {
366
                                                                draw(image, g, vport, cancel);
367
                                                        } catch (ArrayIndexOutOfBoundsException e) {
368
                                                                throw new ReadDriverException("", e);
369
                                                        } catch (InvalidSetViewException e) {
370
                                                                throw new ReadDriverException("Error al asignar la vista en el draw.", e);
371
                                                        } catch (InterruptedException e) {
372
                                                                throw new ReadDriverException("Dibujado interrumpido.", e);
373
                                                        }
374
                                                } catch (NoninvertibleTransformException e) {
375
                                                        throw new ReadDriverException("Error en la transformaci?n", e);
376
                                                }
377
                                        }
378
                                } else
379
                                        try {
380
                                                draw(image, g, vp, cancel);
381
                                        } catch (ArrayIndexOutOfBoundsException e) {
382
                                                throw new ReadDriverException("", e);
383
                                        } catch (InvalidSetViewException e) {
384
                                                throw new ReadDriverException("Error al asignar la vista en el draw.", e);
385
                                        } catch (InterruptedException e) {
386
                                                throw new ReadDriverException("Dibujado interrumpido.", e);
387
                                        }
388
                                status.applyStatus(this);
389
                                firstLoad = false;
390
                        }
391

    
392
                        if (mustTileDraw) {
393
                                Point2D p = vp.getOffset();
394
                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
395
                                Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
396
                                tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
397
                                for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
398
                                        // drawing part
399
                                        try {
400
                                                ViewPort vport = tiles.getTileViewPort(vp, tileNr);
401
                                                try {
402
                                                        draw(image, g, vport, cancel);
403
                                                } catch (ArrayIndexOutOfBoundsException e) {
404
                                                        throw new ReadDriverException("", e);
405
                                                } catch (InvalidSetViewException e) {
406
                                                        throw new ReadDriverException("Error al asignar la vista en el draw.", e);
407
                                                } catch (InterruptedException e) {
408
                                                        throw new ReadDriverException("Dibujado interrumpido.", e);
409
                                                }
410
                                        } catch (NoninvertibleTransformException e) {
411
                                                throw new ReadDriverException("Error en la transformaci?n", e);
412
                                        }
413
                                }
414
                        } else {
415
                                try {
416
                                        draw(image, g, vp, cancel);
417
                                } catch (ArrayIndexOutOfBoundsException e) {
418
                                        throw new ReadDriverException("", e);
419
                                } catch (InvalidSetViewException e) {
420
                                        throw new ReadDriverException("Error al asignar la vista en el draw.", e);
421
                                } catch (InterruptedException e) {
422
                                        throw new ReadDriverException("Dibujado interrumpido.", e);
423
                                }
424
                        }
425

    
426
                        if (getVirtualLayers() != null) {
427
                                getVirtualLayers().draw(image, g, vp, cancel, scale);
428
                        }
429
                }
430
                
431
                disableStopped();
432
                //callLegendChanged(null);
433
        }
434

    
435
        private void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws ArrayIndexOutOfBoundsException, InvalidSetViewException, InterruptedException {
436
                Extent e = new Extent(vp.getAdjustedExtent());
437
                Dimension imgSz = vp.getImageSize();
438
                ViewPortData vp2 = new ViewPortData(vp.getProjection(), e, imgSz );
439
                vp2.setMat(vp.getAffineTransform());
440
                getRender().draw(g, vp2);
441
        }
442

    
443
        /**
444
         * Inserta la proyecci?n.
445
         *
446
         * @param proj Proyecci?n.
447
         */
448
        public void setProjection(IProjection proj) {
449
                super.setProjection(proj);
450
        }
451

    
452
        /*
453
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
454
         */
455
        public Rectangle2D getFullExtent() {
456
                if(!isOpen() || dataset == null || dataset.getExtent() == null)
457
                        return null;
458
                return dataset.getExtent().toRectangle2D();
459
        }
460

    
461
        /**
462
         * Obtiene el valor del pixel del Image en la posici?n real x,y
463
         * @param x Posici?n x
464
         * @param y Posici?n y
465
         * @return valor de pixel
466
         */
467
        public int[] getPixel(double wcx, double wcy) {
468
                if (!isOpen())
469
                        return null;
470
                
471
                int[] argb = { -1, -1, -1, -1 };
472
                if (wcx <= getMaxX() && wcx >= getMinX() && wcy <= getMaxY() && wcy >= getMinY()) {
473
                        View theView = (View) PluginServices.getMDIManager().getActiveWindow();
474
                        if (theView instanceof IView) {
475
                                // BufferedImage buf = ((IView) theView).getMapControl().getImage();
476
                                Point2D p = ((IView) theView).getMapControl().getViewPort().fromMapPoint(wcx, wcy);
477
                                return getPixel((int) p.getX(), (int) p.getY());
478
                        }
479
                }
480
                return argb;
481
        }
482

    
483
        /**
484
         * Obtiene el valor del pixel del Image en la posici?n x,y
485
         * @param x Posici?n x
486
         * @param y Posici?n y
487
         * @return valor de pixel
488
         */
489
        public int[] getPixel(int pxx, int pxy) {
490
                if (!isOpen())
491
                        return null;
492
                
493
                int[] argb = { -1, -1, -1, -1 };
494
                View theView = (View) PluginServices.getMDIManager().getActiveWindow();
495
                BufferedImage buf = null;
496
                if (theView instanceof IView)
497
                        buf = ((IView) theView).getMapControl().getImage();
498
                if (pxx >= 0 && pxx < buf.getWidth() && pxy >= 0 && pxy < buf.getHeight()) {
499
                        if (theView instanceof IView) {
500
                                int value = buf.getRGB(pxx, pxy);
501
                                argb[0] = ((value & 0xff000000) >> 24);
502
                                argb[1] = ((value & 0x00ff0000) >> 16);
503
                                argb[2] = ((value & 0x0000ff00) >> 8);
504
                                argb[3] = (value & 0x000000ff);
505
                        }
506
                }
507
                return argb;
508
        }
509

    
510
        /*
511
         * (non-Javadoc)
512
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
513
         */
514
        public double getMaxX() {
515
                if(getFullExtent() != null)
516
                        return getFullExtent().getMaxX();
517
                return -1;
518
        }
519

    
520
        /*
521
         * (non-Javadoc)
522
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
523
         */
524
        public double getMaxY() {
525
                if(getFullExtent() != null)
526
                        return this.getFullExtent().getMaxY();
527
                return -1;
528
        }
529

    
530
        /*
531
         * (non-Javadoc)
532
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinX()
533
         */
534
        public double getMinX() {
535
                if(getFullExtent() != null)
536
                        return getFullExtent().getMinX();
537
                return -1;
538
        }
539

    
540
        /*
541
         * (non-Javadoc)
542
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinY()
543
         */
544
        public double getMinY() {
545
                if(getFullExtent() != null)
546
                        return getFullExtent().getMinY();
547
                return -1;
548
        }
549

    
550
        /* (non-Javadoc)
551
         * @deprecated. See String getInfo(Point p) throws DriverException
552
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
553
         */
554
        public String queryByPoint(Point p) {
555
                if (!isOpen())
556
                        return null;
557
                
558
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
559

    
560
                ArrayList attr = getAttributes();
561
                data += "  <raster\n";
562
                data += "    File=\"" + getFile() + "\"\n";
563
                for (int i = 0; i < attr.size(); i++) {
564
                        Object[] a = (Object[]) attr.get(i);
565

    
566
                        data += "    " + a[0].toString() + "=";
567
                        if (a[1].toString() instanceof String)
568
                                data += "\"" + a[1].toString() + "\"\n";
569
                        else
570
                                data += a[1].toString() + "\n";
571
                }
572
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
573
                data += "    Point_WC=\"" + MathUtils.format(posXWC, 3) + " , " + MathUtils.format(posYWC, 3) + "\"\n";
574
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
575
                data += "  />\n";
576

    
577
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
578
                return data;
579
        }
580

    
581
        /*
582
         * (non-Javadoc)
583
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo(java.awt.Point, double, com.iver.utiles.swing.threads.Cancellable)
584
         */
585
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException {
586
                if (!isOpen()) {
587
                        StringXMLItem[] item = new StringXMLItem[1];
588
                        String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
589
                        data += "  <raster\n" + "  Layer=\" Not available\"\n" + "  />\n";
590
                        data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
591
                        item[0] = new StringXMLItem(data, this);
592
                        return item;
593
                }
594
                
595
                Point2D pReal = getMapContext().getViewPort().toMapPoint(p);
596
                Point2D px = new Point2D.Double();
597
                if(        pReal.getX() > this.getMinX() &&
598
                        pReal.getX() < this.getMaxX() &&
599
                        pReal.getY() > this.getMinY() &&
600
                        pReal.getY() < this.getMaxY()) {
601
                        ArrayList attr = getAttributes();
602
                        int w = 0, h = 0;
603
                        for (int i = 0; i < attr.size(); i++) {
604
                                Object[] a = (Object[]) attr.get(i);
605
                                if (a[0].toString().equals("Width"))
606
                                        w = ((Integer) a[1]).intValue();
607
                                if (a[0].toString().equals("Height"))
608
                                        h = ((Integer) a[1]).intValue();
609
                        }
610
                        AffineTransform at = this.getDataSource().getAffineTransform();
611
                        px = new Point2D.Double(pReal.getX(), pReal.getY());
612
                        try {
613
                                at.inverseTransform(px, px);
614
                        } catch (NoninvertibleTransformException e) {
615
                                throw new ReadDriverException("Error en la transformaci?n del punto", e);
616
                        }
617
                }
618
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
619

    
620
                StringXMLItem[] item = new StringXMLItem[1];
621
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
622

    
623
                data += "  <raster\n";
624
                data += "    View_Point=\"" + p.getX() + " , " + p.getY() + "\"\n";
625
                data += "    World_Point=\"" + MathUtils.format(pReal.getX(), 3) + " , " + MathUtils.format(pReal.getY(), 3) + "\"\n";
626
                if (px == null)
627
                        data += "    Pixel_Point=\"Out\"\n";
628
                else
629
                        data += "    Pixel_Point=\"" + (int) px.getX() + " , " + (int) px.getY() + "\"\n";
630
                data += "    RGB=\"" + rgb[1] + "  " + rgb[2] + "  " + rgb[3] + "\"\n";
631
                data += "    Band_Value=\"";
632
                try {
633
                        if (px != null) {
634
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3){
635
                                        for(int i = 0; i < getBandCount(); i++)
636
                                                data += ((Integer)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).intValue() + "  ";
637
                                }
638
                                if(getDataType()[0] == 4){
639
                                        for(int i = 0; i < getBandCount(); i++)
640
                                                data += ((Float)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).floatValue() + "  ";
641
                                }
642
                                if(getDataType()[0] == 5){
643
                                        for(int i = 0; i < getBandCount(); i++)
644
                                                data += ((Double)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).doubleValue() + "  ";
645
                                }
646
                        }
647
                } catch (RasterDriverException ex) {
648
                        throw new ReadDriverException("Error en el acceso al dataset", ex);
649
                } catch (InvalidSetViewException ex) {
650
                        throw new ReadDriverException("Error en la asignaci?n de la vista en getData", ex);
651
                } catch (FileNotOpenException ex) {
652
                        throw new ReadDriverException("Fichero no abierto en el dataset", ex);
653
                }
654
                data += "\"\n";
655
                data += "  />\n";
656
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
657

    
658
                item[0] = new StringXMLItem(data, this);
659
                return item;
660
        }
661

    
662
        /**
663
         * Filters a string for being suitable as XML Tag, erasing
664
         * all not alphabetic or numeric characters.
665
         * @param s
666
         * @return string normalized
667
         */
668
        private String normalizeAsXMLTag(String s) {
669
                return s.replaceAll("[^a-zA-Z0-9]", "");
670
        }
671

    
672
        /**
673
         * Obtiene atributos a partir de un georasterfile
674
         * @return
675
         */
676
        public ArrayList getAttributes() {
677
                ArrayList attr = new ArrayList();
678
                if(!isOpen())
679
                        return attr;
680
                Object [][] a = {
681
                        {"Filename", dataset.getDataset(0)[0].getFName()},
682
                        {"Filesize", new Long(dataset.getFileSize())},
683
                        {"Width", new Integer((int)dataset.getWidth())},
684
                        {"Height", new Integer((int)dataset.getHeight())},
685
                        {"Bands", new Integer(dataset.getBandCount())}
686
                };
687
                for (int i = 0; i < a.length; i++)
688
                        attr.add(a[i]);
689
                return attr;
690
        }
691

    
692
        /**
693
         * Escribe en el proyecto la capa actual
694
         * @throws XMLException
695
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
696
         */
697
        public XMLEntity getXMLEntity() throws XMLException {
698
                if(isClosed() || isAwake())
699
                        return null;
700
                
701
                XMLEntity xml = super.getXMLEntity();
702
                if(getFile() != null)
703
                        xml.putProperty("file", getFile());
704
                xml.putProperty("driverName", "gvSIG Raster Driver");
705

    
706
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
707
                if (status == null)
708
                        status = new StatusLayerRaster();
709
                status.getXMLEntity(xml, true, this);
710

    
711
                return xml;
712
        }
713

    
714
        public void setXMLEntity03(XMLEntity xml) throws XMLException {
715
        }
716

    
717
        /**
718
         * Recupera de disco los datos de la capa.
719
         */
720
        public void setXMLEntity(XMLEntity xml) throws XMLException {
721
                super.setXMLEntity(xml);
722

    
723
                try {                                
724
                        params = new File(xml.getStringProperty("file"));
725
                        
726
                        if(params != null && getName() != null && getName().compareTo("") != 0) {
727
                                try {
728
                                        enableAwake();
729
                                } catch (NotAvailableStateException e) {
730
                                        Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
731
                                }
732
                        }
733
                        if(!super.getFLayerStatus().visible) 
734
                                enableStopped();
735
                
736
                        // Para notificar al adapter-driver cual es la proyecci?n.
737
                        setProjection(super.getProjection());
738

    
739
                        //Inicializamos la clase a la que se usa por defecto para
740
                        //compatibilidad con proyectos antiguos
741
                        String claseStr = StatusLayerRaster.defaultClass;
742
                        if (xml.contains("raster.class"))
743
                                claseStr = xml.getStringProperty("raster.class");
744

    
745
                        if (status != null)
746
                                status.setXMLEntity(xml, this);
747
                        else {
748
                                // Cuando cargamos un proyecto
749

    
750
                                if (claseStr != null && !claseStr.equals("")) {
751
                                        try {
752
                                                Class clase = LayerFactory.getLayerClassForLayerClassName(claseStr);
753
                                                Constructor constr = clase.getConstructor(null);
754
                                                status = (IStatusRaster) constr.newInstance(null);
755
                                                if (status != null) {
756
                                                        ((StatusLayerRaster)status).setNameClass(claseStr);
757
                                                        status.setXMLEntity(xml, this);
758
                                                        filterArguments = status.getFilterArguments();
759
                                                        crearColorTable();
760
                                                }
761
                                        } catch (ClassNotFoundException exc) {
762
                                                throw new XMLException(exc);
763
                                        } catch (InstantiationException exc) {
764
                                                throw new XMLException(exc);
765
                                        } catch (IllegalAccessException exc) {
766
                                                throw new XMLException(exc);
767
                                        } catch (NoSuchMethodException exc) {
768
                                                throw new XMLException(exc);
769
                                        } catch (InvocationTargetException exc) {
770
                                                throw new XMLException(exc);
771
                                        }
772
                                }
773
                        }
774
                        firstLoad = true;
775
                } catch (NotExistInXMLEntity e) {
776
                        
777
                }
778
        }
779
        
780
        private void crearColorTable() {
781
                ArrayList color = (ArrayList) filterArguments.clone();
782
                setLastLegend(ColorTableListManager.createColorTableFromArray(color));
783
        }
784

    
785
        /* (non-Javadoc)
786
         * @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)
787
         */
788
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet propeties) throws ReadDriverException {
789

    
790
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
791
                        return;
792

    
793
                isPrinting = true;
794
                if (!mustTilePrint) {
795
                        draw(null, g, viewPort, cancel,scale);
796
                } else {
797
                        // Para no pedir imagenes demasiado grandes, vamos
798
                        // a hacer lo mismo que hace EcwFile: chunkear.
799
                        // Llamamos a drawView con cuadraditos m?s peque?os
800
                        // del BufferedImage ni caso, cuando se imprime viene con null
801
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
802
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
803

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

    
807
                        //RasterStats stats = getSource().getFilterStack().getStats();
808
                        //if(stats != null)
809
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
810

    
811

    
812
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
813
                                // Parte que dibuja
814
                                try {
815
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
816
                                        draw(null, g, vp, cancel, scale);
817
                                } catch (NoninvertibleTransformException e) {
818
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
819
                                }
820
                        }
821
                        /*if(stats != null){
822
                                getSource().getFilterStack().getStats().history.clear();
823
                                stats = getSource().getFilterStack().getStats();
824
                        }*/
825
                }
826
                isPrinting = false;
827
        }
828

    
829
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale) throws ReadDriverException {
830
                if(!isOpen())
831
                        return;
832
                
833
                // Para no pedir imagenes demasiado grandes, vamos
834
                // a hacer lo mismo que hace EcwFile: chunkear.
835
                // Llamamos a drawView con cuadraditos m?s peque?os
836
                // del BufferedImage ni caso, cuando se imprime viene con null
837

    
838
                int numW, numH;
839
                int stepX, stepY;
840
                int xProv, yProv;
841
                int A = 1500;
842
                int H = 1500;
843
                int altoAux, anchoAux;
844
                
845
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
846

    
847
                // Vamos a hacerlo en trozos de AxH
848
                Rectangle r = g.getClipBounds();
849
                numW = (int) (r.width) / A;
850
                numH = (int) (r.height) / H;
851

    
852
                double[] srcPts = new double[8];
853
                double[] dstPts = new double[8];
854

    
855
                yProv = (int) r.y;
856
                for (stepY = 0; stepY < numH + 1; stepY++) {
857
                        if ((yProv + H) > r.getMaxY())
858
                                altoAux = (int) r.getMaxY() - yProv;
859
                        else
860
                                altoAux = H;
861

    
862
                        xProv = (int) r.x;
863
                        for (stepX = 0; stepX < numW + 1; stepX++) {
864
                                if ((xProv + A) > r.getMaxX())
865
                                        anchoAux = (int) r.getMaxX() - xProv;
866
                                else
867
                                        anchoAux = A;
868

    
869
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
870

    
871
                                // Parte que dibuja
872
                                srcPts[0] = xProv;
873
                                srcPts[1] = yProv;
874
                                srcPts[2] = xProv + anchoAux + 1;
875
                                srcPts[3] = yProv;
876
                                srcPts[4] = xProv + anchoAux + 1;
877
                                srcPts[5] = yProv + altoAux + 1;
878
                                srcPts[6] = xProv;
879
                                srcPts[7] = yProv + altoAux + 1;
880

    
881
                                try {
882
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
883
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
884
                                        // Extent extent = new Extent(rectCuadricula);
885

    
886
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
887
                                        ViewPort vp = viewPort.cloneViewPort();
888
                                        vp.setImageSize(tam);
889
                                        vp.setExtent(rectCuadricula);
890
                                        vp.setAffineTransform(mat);
891
                                        draw(null, g, vp, cancel, scale);
892

    
893
                                } catch (NoninvertibleTransformException e) {
894
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
895
                                }
896
                                // Fin parte que dibuja
897
                                xProv = xProv + A;
898
                        }
899
                        yProv = yProv + H;
900
                }
901
        }
902

    
903
        /**
904
         * Borra de la lista de listeners el que se pasa como par?metro.
905
         *
906
         * @param o LayerListener a borrar.
907
         *
908
         * @return True si ha sido correcto el borrado del Listener.
909
         */
910
        public boolean removeLayerListener(LayerListener o) {
911
                //Salva a RMF
912
                try {
913
                        if(this.getDataSource() != null)
914
                                this.getDataSource().saveRmfModification();
915
                } catch (IOException e) {
916
                        //No se ha salvado nada
917
                }
918

    
919
                if (this.isRemoveRasterFlag()) {
920
                        if(dataset != null)
921
                                dataset.close();
922
                        this.setRemoveRasterFlag(true);
923
                }
924
                return super.layerListeners.remove(o);
925
        }
926

    
927
        /**
928
         * @return Returns the removeRasterFlag.
929
         */
930
        public boolean isRemoveRasterFlag() {
931
                return removeRasterFlag;
932
        }
933

    
934
        /**
935
         * Asigna el valor del flag que dice si destruimos la memoria del raster
936
         * al eliminarlo del TOC o  no.
937
         * @param removeRasterFlag The removeRasterFlag to set.
938
         */
939
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
940
                this.removeRasterFlag = removeRasterFlag;
941
        }
942

    
943
        /*
944
         * (non-Javadoc)
945
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
946
         */
947
        public ImageIcon getTocImageIcon() {
948
                /*if(!isOpen())
949
                        return new ImageIcon(MapControl.class.getResource("images/map_ico_ko.gif"));*/
950
                return PluginServices.getIconTheme().get("map-ok-ico");
951
        }
952

    
953
        /*
954
         *  (non-Javadoc)
955
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
956
         */
957
        public int[] getTileSize() {
958
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
959
                return size;
960
        }
961

    
962
        /*
963
         *  (non-Javadoc)
964
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
965
         */
966
        public boolean isTiled() {
967
                return mustTileDraw;
968
        }
969

    
970
        /**
971
         * Obtiene el flag que dice si la imagen est? o no georreferenciada
972
         * @return true si est? georreferenciada y false si no lo est?.
973
         */
974
        public boolean isGeoreferenced() {
975
                return dataset.isGeoreferenced();
976
        }
977

    
978
        /**
979
         * Get datasource object
980
         * @return
981
         */
982
        public BufferFactory getBufferFactory(){
983
                return bufferFactory;
984
        }
985

    
986
        /**
987
         * Asigna el valor noData asociado a la capa
988
         * @return double que representa el valor noData asociado a la capa
989
         */
990
        public double getNoDataValue() {
991
                return noDataValue;
992
        }
993

    
994
        /**
995
         * Asigna el valor no data asociado a la capa
996
         * @param nd
997
         */
998
        public void setNoDataValue(double nd){
999
                if (bufferFactory != null)
1000
                        bufferFactory.setNoDataValue(nd);
1001
                noDataValue = nd;
1002
        }
1003

    
1004
        /*
1005
         * (non-Javadoc)
1006
         * @see org.gvsig.fmap.raster.IRasterOperations#getPXHeight()
1007
         */
1008
        public double getPxHeight() {
1009
                return dataset.getHeight();
1010
        }
1011

    
1012
        /*
1013
         * (non-Javadoc)
1014
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
1015
         */
1016
        public double getPxWidth() {
1017
                return dataset.getWidth();
1018
        }
1019

    
1020
        /*
1021
         * (non-Javadoc)
1022
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCHeight()
1023
         */
1024
        public double getWCHeight() {
1025
                return getFullExtent().getHeight();
1026
        }
1027

    
1028
        /*
1029
         * (non-Javadoc)
1030
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
1031
         */
1032
        public double getWCWidth() {
1033
                return getFullExtent().getWidth();
1034
        }
1035

    
1036
        /*
1037
         * (non-Javadoc)
1038
         * @see org.gvsig.fmap.raster.IRasterFile#getFileSize()
1039
         */
1040
        public long[] getFileSize(){
1041
                int nFiles = dataset.getDatasetCount();
1042
                long[] s = new long[nFiles];
1043
                for (int i = 0; i < nFiles; i++)
1044
                        s[i] = dataset.getFileSize();
1045
                return s;
1046
        }
1047

    
1048
        /*
1049
         * (non-Javadoc)
1050
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
1051
         */
1052
        public String[] getFileName(){
1053
                int nFiles = dataset.getDatasetCount();
1054
                String[] s = new String[nFiles];
1055
                for (int i = 0; i < nFiles; i++)
1056
                        s[i] = dataset.getDataset(i)[0].getFName();
1057
                return s;
1058
        }
1059

    
1060
        /*
1061
         * (non-Javadoc)
1062
         * @see org.gvsig.fmap.raster.IRasterFile#getFileCount()
1063
         */
1064
        public int getFileCount() {
1065
                return (dataset != null) ? dataset.getDatasetCount() : 0;
1066
        }
1067

    
1068
        /*
1069
         * (non-Javadoc)
1070
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
1071
         */
1072
        public String getFileFormat() {
1073
                String fName = dataset.getDataset(0)[0].getFName();
1074
                int index = fName.lastIndexOf(".") + 1;
1075
                String ext = null;
1076
                if (index > 0)
1077
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1078
                return ext;
1079
        }
1080

    
1081
        /*
1082
         * (non-Javadoc)
1083
         * @see org.gvsig.fmap.raster.IRasterOperations#getBandCount()
1084
         */
1085
        public int getBandCount() {
1086
                return (dataset != null) ? dataset.getBandCount() : 0;
1087
        }
1088

    
1089
        /*
1090
         * (non-Javadoc)
1091
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1092
         */
1093
        public int[] getDataType() {
1094
                return dataset.getDataType();
1095
        }
1096

    
1097
        /*
1098
         * (non-Javadoc)
1099
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
1100
         */
1101
        public GridTransparency getRenderTransparency() {
1102
                return getRender().getLastTransparency();
1103
        }
1104

    
1105
        /*
1106
         * (non-Javadoc)
1107
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1108
         */
1109
        public RasterFilterList getRenderFilterList() {
1110
                return getRender().getFilterList();
1111
        }
1112
        
1113
        /*
1114
         * (non-Javadoc)
1115
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
1116
         */
1117
        public int[] getRenderBands() {
1118
                return getRender().getRenderBands();
1119
        }
1120
        
1121
        /*
1122
         * (non-Javadoc)
1123
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
1124
         */
1125
        public void setRenderBands(int[] renderBands) {
1126
                getRender().setRenderBands(renderBands);
1127
        }
1128
        
1129
        /*
1130
         * (non-Javadoc)
1131
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
1132
         */
1133
        public void setRenderFilterList(RasterFilterList filterList) {
1134
                getRender().setFilterList(filterList);
1135
        }
1136
        
1137
        /*
1138
         * (non-Javadoc)
1139
         * @see org.gvsig.raster.hierarchy.IRasterDataset#getDataSource()
1140
         */
1141
        public IRasterDataSource getDataSource() {
1142
                return dataset;
1143
        }
1144

    
1145
        /*
1146
         * (non-Javadoc)
1147
         * @see org.gvsig.fmap.raster.IRasterDataset#addFile(java.lang.String)
1148
         */
1149
        public void addFile(String fileName) throws NotSupportedExtensionException, RasterDriverException{
1150
                if (getRender() != null)
1151
                        bufferFactory.addFile(RasterDataset.open(getProjection(), fileName));
1152
        }
1153

    
1154
        /*
1155
         * (non-Javadoc)
1156
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
1157
         */
1158
        public void delFile(String fileName) {
1159
                if (getRender() != null)
1160
                        bufferFactory.removeFile(fileName);
1161
        }
1162

    
1163
        /*
1164
         * (non-Javadoc)
1165
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1166
         */
1167
        public Object getInfo(String key) {
1168
                if (key.equals("DriverName"))
1169
                        return "gvSIG Raster Driver";
1170
                return null;
1171
        }
1172

    
1173
        /*
1174
         * (non-Javadoc)
1175
         * @see org.gvsig.raster.shared.IRasterOperations#getMetadata()
1176
         */
1177
        public DatasetMetadata[] getMetadata() {
1178
                int count = dataset.getDatasetCount();
1179
                DatasetMetadata[] metadata = new DatasetMetadata[count];
1180
                for (int i = 0; i < count; i++) {
1181
                        metadata[i] = dataset.getDataset(i)[0].getMetadata();
1182
                }
1183
                return metadata;
1184
        }
1185

    
1186
        /*
1187
         * (non-Javadoc)
1188
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
1189
         */
1190
        public int[] getBandCountFromDataset() {
1191
                int count = dataset.getDatasetCount();
1192
                int[] bands = new int[count];
1193
                for (int i = 0; i < count; i++) 
1194
                        bands[i] = dataset.getDataset(i)[0].getBandCount();
1195
                return bands;
1196
        }
1197

    
1198
        /*
1199
         * (non-Javadoc)
1200
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1201
         */
1202
        public String getColourInterpretation(int band, int dataset) {
1203
                if (this.dataset.getColorInterpretation(dataset) == null)
1204
                        return "Undefined";
1205
                return this.dataset.getColorInterpretation(dataset).get(band);
1206
        }
1207

    
1208
        /*
1209
         * (non-Javadoc)
1210
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
1211
         */
1212
        public String getWktProjection() throws RasterDriverException {
1213
                try {
1214
                        return dataset.getWktProjection();
1215
                } catch (RasterDriverException e) {
1216
                        throw new RasterDriverException("No puedo obtener la proyecci?n asociada al dataset.", e);
1217
                }
1218
        }
1219

    
1220
        /**
1221
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1222
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1223
         * cacheado o no dependiendo del tama?o de esta.
1224
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1225
         * @return Grid.
1226
         * @throws InterruptedException 
1227
         */
1228
        public Grid getFullGrid(boolean interpolated) throws InterruptedException {
1229
                BufferFactory bf = getBufferFactory();
1230
                bf.clearDrawableBand();
1231
                bf.setAllDrawableBands();
1232
                bf.setAreaOfInterest();
1233
                return new Grid(bf, interpolated);
1234
        }
1235

    
1236
        /*
1237
         * (non-Javadoc)
1238
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1239
         */
1240
        public Extent getFullRasterExtent() {
1241
                return this.getDataSource().getExtent();
1242
        }
1243

    
1244

    
1245
        /**
1246
         * Devuelve el fichero asociado a la capa o null si no tiene.
1247
         * @return Fichero.
1248
         */
1249
        public File getFile() {
1250
                return (params instanceof File) ? ((File)params) : null;
1251
        }
1252

    
1253
        /**
1254
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1255
         * @param file Fichero a consultar
1256
         * @return true si es aceptado y false si no lo es.
1257
         */
1258
        public static boolean isFileAccepted(File file) {
1259
                return RasterDataset.fileIsSupported(file.getName());
1260
        }
1261

    
1262
        /*
1263
         * (non-Javadoc)
1264
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1265
         */
1266
        public boolean existColorTable() {
1267
                return getRender().existColorTable();
1268
        }
1269

    
1270
        /**
1271
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1272
         * capa busque una leyenda valida.
1273
         * @param ct
1274
         */
1275
        public void setLastLegend(ColorTable ct) {
1276
                lastLegend = ColorTableLegend.createLegend(ct);
1277
        }
1278

    
1279
        /**
1280
         * Devuelve la Leyenda de la capa.
1281
         * @return Leyenda.
1282
         */
1283
        public ILegend getLegend() {
1284
                if (lastLegend != null)
1285
                        return lastLegend;
1286

    
1287
                return null;
1288
        }
1289

    
1290
        /*
1291
         * (non-Javadoc)
1292
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1293
         */
1294
        public void addLegendListener(LegendListener listener) {
1295
                layerChangeSupport.addLayerListener(listener);
1296
        }
1297

    
1298
        /*
1299
         *  (non-Javadoc)
1300
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1301
         */
1302
        public int getShapeType() throws ReadDriverException {
1303
                return FShape.POLYGON;
1304
        }
1305

    
1306
        /*
1307
         * (non-Javadoc)
1308
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1309
         */
1310
        public void removeLegendListener(LegendListener listener) {
1311
                layerChangeSupport.removeLayerListener(listener);
1312
        }
1313

    
1314
        /**
1315
         * Metodo que obtiene si un punto cae dentro de los l?mites de la capa
1316
         * o fuera de ellos.
1317
         * @param p Punto a calcular
1318
         * @return true si est? dentro de los l?mites y false si est? fuera
1319
         */
1320
        public boolean isInside(Point2D p) {
1321
                 return getDataSource().isInside(p);
1322
        }
1323

    
1324
        /**
1325
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1326
         * @return AffineTransform
1327
         */
1328
        public AffineTransform getAffineTransform() {
1329
                return getDataSource().getAffineTransform();
1330
        }
1331

    
1332
        /**
1333
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista
1334
         * @param transf
1335
         */
1336
        public void setAffineTransform(AffineTransform transf) {
1337
                affineTransformList.add(transf);
1338
                getDataSource().setAffineTransform(transf);
1339
        }
1340
        
1341
        /**
1342
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista.
1343
         * Esta versi?n no guarda en el historico.
1344
         * @param transf
1345
         */
1346
        public void setAT(AffineTransform transf) {
1347
                getDataSource().setAffineTransform(transf);
1348
        }
1349
        
1350
        /**
1351
         * Obtiene la lista de transformaciones que se han ido aplicando al raster.
1352
         * @return Historical. Lista de AffineTransform
1353
         */
1354
        public Historical getAffineTransformHistorical() {
1355
                return this.affineTransformList;
1356
        }
1357
        
1358
        /**
1359
         * Salva la georreferenciaci?n a fichero rmf.
1360
         * @param fName
1361
         * @throws IOException  
1362
         */
1363
        public void saveGeoToRmf() throws IOException {
1364
                if(!isOpen())
1365
                        return;
1366
                getDataSource().saveGeoToRmf();
1367
                affineTransformList.clear();
1368
                affineTransformList.add(this.getAffineTransform());
1369
        }
1370

    
1371
        /*
1372
         * (non-Javadoc)
1373
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1374
         */
1375
        public boolean isActionEnabled(int action) {
1376
                switch (action) {
1377
                        case IRasterLayerActions.BANDS_FILE_LIST:
1378
                                if (existColorTable())
1379
                                        return false;
1380
                        case IRasterLayerActions.BANDS_RGB:
1381
                                if (existColorTable())
1382
                                        return false;
1383
                        case IRasterLayerActions.OPACITY:
1384
                        case IRasterLayerActions.TRANSPARENCY:
1385
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1386
                        case IRasterLayerActions.ENHANCED:
1387
                        case IRasterLayerActions.PANSHARPENING:
1388
                                return true;
1389
                }
1390
                return true;
1391
        }
1392
                
1393
        /*
1394
         * (non-Javadoc)
1395
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1396
         */
1397
        public void setVisible(boolean visibility) {
1398
                if(visibility)
1399
                        state.disableStopped();
1400
                else
1401
                        enableStopped();
1402
                
1403
                if(isAwake() || isClosed())
1404
                        try {
1405
                                this.load();
1406
                        } catch (LoadLayerException e) {
1407
                                e.printStackTrace();
1408
                        }
1409
                super.setVisible(visibility);
1410
        }
1411

    
1412
        /**
1413
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1414
         * @return valor de transparencia
1415
         */
1416
        public int getTransparency() {
1417
                return getRenderTransparency().getOpacity();
1418
        }
1419
        
1420
        /**
1421
         * Asigna la transparencia de la siguiente renderizaci?n
1422
         * @param valor de transparencia
1423
         */
1424
        public void setTransparency(int trans) {
1425
                super.setTransparency(trans);
1426
                getRenderTransparency().setOpacity(trans);
1427
                getRenderTransparency().activeTransparency();
1428
        }
1429
        
1430
        /*
1431
         * (non-Javadoc)
1432
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getLastRenderBuffer()
1433
         */
1434
        public IBuffer getLastRenderBuffer() {
1435
                return getRender().getLastRenderBuffer();
1436
        }
1437
        
1438
        /*
1439
         * (non-Javadoc)
1440
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#cloneLayer()
1441
         */
1442
        public FLayer cloneLayer() throws Exception {
1443
                FLyrRasterSE newLayer = FLyrRasterSE.createLayer(this.getName(), params, this.getProjection());
1444
                for (int i = 0; i < dataset.getDatasetCount(); i++) {
1445
                        String name = dataset.getDataset(i)[0].getFName();
1446
                        if(!(dataset instanceof CompositeDataset) && !name.equals(this.getName())) 
1447
                                newLayer.addFile(name);
1448
                }
1449
                ArrayList filters = getRender().getFilterList().getStatusCloned();
1450
                RasterFilterList filterList = new RasterFilterList();
1451
                //TODO: Los parametros deberiamos clonarlos
1452
                filterList.setEnv(getRenderFilterList().getEnv());
1453
                filterList.setInitDataType(getDataType()[0]);
1454
                filterList.setStatus(filters);
1455
                newLayer.getRender().setFilterList(filterList);
1456
                newLayer.getRender().setLastTransparency(new GridTransparency(getRenderTransparency()));
1457
                return newLayer;
1458
        }
1459
        
1460
        /**
1461
         * 
1462
         * @return ROIs asociadas a la capa raster.
1463
         */
1464
        public ArrayList getRois() {
1465
                return rois;
1466
        }
1467

    
1468
        /**
1469
         * Establece las ROI asociadas a la capa raster.
1470
         * 
1471
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1472
         */
1473
        public void setRois(ArrayList rois) {
1474
                this.rois = rois;
1475
        }
1476
        
1477
        /*****************************************************/
1478
        
1479
        public void disableStopped() {state.disableStopped();}
1480

    
1481
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1482

    
1483
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
1484

    
1485
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1486

    
1487
        public void enableStopped() {state.enableStopped();}
1488

    
1489
        public boolean isAwake() {return state.isAwake();}
1490

    
1491
        public boolean isClosed() {return state.isClosed();}
1492

    
1493
        public boolean isOpen() {return state.isOpen();}
1494

    
1495
        public boolean isStopped() {return state.isStopped();}
1496
}