Statistics
| Revision:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
712
                return xml;
713
        }
714

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

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

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

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

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

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

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

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

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

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

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

    
812

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1245

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

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

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

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

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

    
1288
                return null;
1289
        }
1290

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

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

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

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

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

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

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

    
1413
        /**
1414
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1415
         * @return valor de transparencia
1416
         */
1417
        public int getTransparency() {
1418
                return getRenderTransparency().getOpacity();
1419
        }
1420
        
1421
        /**
1422
         * Asigna la transparencia de la siguiente renderizaci?n
1423
         * @param valor de transparencia
1424
         */
1425
        public void setTransparency(int 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
                ArrayList filters = getRender().getFilterList().getStatusCloned();
1445
                RasterFilterList filterList = new RasterFilterList();
1446
                //TODO: Los parametros deberiamos clonarlos
1447
                filterList.setEnv(getRenderFilterList().getEnv());
1448
                filterList.setInitDataType(getDataType()[0]);
1449
                filterList.setStatus(filters);
1450
                newLayer.getRender().setFilterList(filterList);
1451
                newLayer.getRender().setLastTransparency(new GridTransparency(getRenderTransparency()));
1452
                return newLayer;
1453
        }
1454
        
1455
        /**
1456
         * 
1457
         * @return ROIs asociadas a la capa raster.
1458
         */
1459
        public ArrayList getRois() {
1460
                return rois;
1461
        }
1462

    
1463
        /**
1464
         * Establece las ROI asociadas a la capa raster.
1465
         * 
1466
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1467
         */
1468
        public void setRois(ArrayList rois) {
1469
                this.rois = rois;
1470
        }
1471
        
1472
        /*****************************************************/
1473
        
1474
        public void disableStopped() {state.disableStopped();}
1475

    
1476
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1477

    
1478
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
1479

    
1480
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1481

    
1482
        public void enableStopped() {state.enableStopped();}
1483

    
1484
        public boolean isAwake() {return state.isAwake();}
1485

    
1486
        public boolean isClosed() {return state.isClosed();}
1487

    
1488
        public boolean isOpen() {return state.isOpen();}
1489

    
1490
        public boolean isStopped() {return state.isStopped();}
1491
}