Statistics
| Revision:

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

History | View | Annotate | Download (43.6 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.ColorTableFilter;
64
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
65
import org.gvsig.raster.grid.filter.enhancement.EnhancementListManager;
66
import org.gvsig.raster.grid.render.Rendering;
67
import org.gvsig.raster.hierarchy.IRasterDataset;
68
import org.gvsig.raster.hierarchy.IRasterOperations;
69
import org.gvsig.raster.hierarchy.IRasterProperties;
70
import org.gvsig.raster.hierarchy.IStatistics;
71
import org.gvsig.raster.util.Historical;
72
import org.gvsig.raster.util.MathUtils;
73

    
74
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
75
import com.iver.andami.PluginServices;
76
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
77
import com.iver.cit.gvsig.fmap.MapControl;
78
import com.iver.cit.gvsig.fmap.ViewPort;
79
import com.iver.cit.gvsig.fmap.core.FShape;
80
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
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
        
132
        /**
133
         * Lista de transformaciones afines que son aplicadas. Esta lista es simplemente un
134
         * historico que no se utiliza. Es posible utilizarlo para recuperar transformaciones
135
         * anteriores.
136
         */
137
        private Historical               affineTransformList = new Historical();
138
        
139
        static {
140
                 RasterLibrary.wakeUp();
141
        }
142

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

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

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

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

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

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

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

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

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

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

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

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

    
315
                filterList.setInitDataType(getDataType()[0]);
316
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
317

    
318
                if (this.getDataSource().getColorTables()[0] != null) {
319
                        GridPalette p = new GridPalette(getDataSource().getColorTables()[0]);
320
                        ColorTableListManager ctm = new ColorTableListManager(filterManager);
321
                        ctm.addColorTableFilter(p);
322
                } else {
323
                        if (getDataType()[0] != IBuffer.TYPE_BYTE) {
324
                                IStatistics stats = getDataSource().getStatistics();
325
                                EnhancementListManager elm = new EnhancementListManager(filterManager);
326
                                elm.addEnhancedFilter(false, stats, 0.0, getRender().getRenderBands());
327
                        }
328
                }
329

    
330
                getRender().setFilterList(filterList);
331
        }
332

    
333
        /**
334
         * @throws ReadDriverException 
335
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
336
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
337
         *                 com.iver.utiles.swing.threads.Cancellable)
338
         */
339
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadDriverException {
340
                if(!isOpen())
341
                        return;
342
                
343
                if (isWithinScale(scale)) {
344

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

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

    
417
                        if (getVirtualLayers() != null) {
418
                                getVirtualLayers().draw(image, g, vp, cancel, scale);
419
                        }
420
                }
421
        }
422

    
423
        private void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws ArrayIndexOutOfBoundsException, InvalidSetViewException, InterruptedException {
424
                Extent e = new Extent(vp.getAdjustedExtent());
425
                Dimension imgSz = vp.getImageSize();
426
                ViewPortData vp2 = new ViewPortData(vp.getProjection(), e, imgSz );
427
                vp2.setMat(vp.getAffineTransform());
428
                getRender().draw(g, vp2);
429
        }
430

    
431
        /**
432
         * Inserta la proyecci?n.
433
         *
434
         * @param proj Proyecci?n.
435
         */
436
        public void setProjection(IProjection proj) {
437
                super.setProjection(proj);
438
        }
439

    
440
        /*
441
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
442
         */
443
        public Rectangle2D getFullExtent() {
444
                if(!isOpen() || dataset == null || dataset.getExtent() == null)
445
                        return null;
446
                return dataset.getExtent().toRectangle2D();
447
        }
448

    
449
        /**
450
         * Obtiene el valor del pixel del Image en la posici?n real x,y
451
         * @param x Posici?n x
452
         * @param y Posici?n y
453
         * @return valor de pixel
454
         */
455
        public int[] getPixel(double wcx, double wcy) {
456
                if (!isOpen())
457
                        return null;
458
                
459
                int[] argb = { -1, -1, -1, -1 };
460
                if (wcx <= getMaxX() && wcx >= getMinX() && wcy <= getMaxY() && wcy >= getMinY()) {
461
                        View theView = (View) PluginServices.getMDIManager().getActiveWindow();
462
                        if (theView instanceof IView) {
463
                                // BufferedImage buf = ((IView) theView).getMapControl().getImage();
464
                                Point2D p = ((IView) theView).getMapControl().getViewPort().fromMapPoint(wcx, wcy);
465
                                return getPixel((int) p.getX(), (int) p.getY());
466
                        }
467
                }
468
                return argb;
469
        }
470

    
471
        /**
472
         * Obtiene el valor del pixel del Image en la posici?n x,y
473
         * @param x Posici?n x
474
         * @param y Posici?n y
475
         * @return valor de pixel
476
         */
477
        public int[] getPixel(int pxx, int pxy) {
478
                if (!isOpen())
479
                        return null;
480
                
481
                int[] argb = { -1, -1, -1, -1 };
482
                View theView = (View) PluginServices.getMDIManager().getActiveWindow();
483
                BufferedImage buf = null;
484
                if (theView instanceof IView)
485
                        buf = ((IView) theView).getMapControl().getImage();
486
                if (pxx >= 0 && pxx < buf.getWidth() && pxy >= 0 && pxy < buf.getHeight()) {
487
                        if (theView instanceof IView) {
488
                                int value = buf.getRGB(pxx, pxy);
489
                                argb[0] = ((value & 0xff000000) >> 24);
490
                                argb[1] = ((value & 0x00ff0000) >> 16);
491
                                argb[2] = ((value & 0x0000ff00) >> 8);
492
                                argb[3] = (value & 0x000000ff);
493
                        }
494
                }
495
                return argb;
496
        }
497

    
498
        /*
499
         * (non-Javadoc)
500
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
501
         */
502
        public double getMaxX() {
503
                if(getFullExtent() != null)
504
                        return getFullExtent().getMaxX();
505
                return -1;
506
        }
507

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

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

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

    
538
        /* (non-Javadoc)
539
         * @deprecated. See String getInfo(Point p) throws DriverException
540
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
541
         */
542
        public String queryByPoint(Point p) {
543
                if (!isOpen())
544
                        return null;
545
                
546
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
547

    
548
                ArrayList attr = getAttributes();
549
                data += "  <raster\n";
550
                data += "    File=\"" + getFile() + "\"\n";
551
                for (int i = 0; i < attr.size(); i++) {
552
                        Object[] a = (Object[]) attr.get(i);
553

    
554
                        data += "    " + a[0].toString() + "=";
555
                        if (a[1].toString() instanceof String)
556
                                data += "\"" + a[1].toString() + "\"\n";
557
                        else
558
                                data += a[1].toString() + "\n";
559
                }
560
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
561
                data += "    Point_WC=\"" + MathUtils.format(posXWC, 3) + " , " + MathUtils.format(posYWC, 3) + "\"\n";
562
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
563
                data += "  />\n";
564

    
565
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
566
                return data;
567
        }
568

    
569
        /*
570
         * (non-Javadoc)
571
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo(java.awt.Point, double, com.iver.utiles.swing.threads.Cancellable)
572
         */
573
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException {
574
                if (!isOpen())
575
                        return null;
576
                
577
                Point2D pReal = getMapContext().getViewPort().toMapPoint(p);
578
                Point2D px = null;
579
                if(        pReal.getX() > this.getMinX() &&
580
                        pReal.getX() < this.getMaxX() &&
581
                        pReal.getY() > this.getMinY() &&
582
                        pReal.getY() < this.getMaxY()) {
583
                        ArrayList attr = getAttributes();
584
                        int w = 0, h = 0;
585
                        for (int i = 0; i < attr.size(); i++) {
586
                                Object[] a = (Object[]) attr.get(i);
587
                                if (a[0].toString().equals("Width"))
588
                                        w = ((Integer) a[1]).intValue();
589
                                if (a[0].toString().equals("Height"))
590
                                        h = ((Integer) a[1]).intValue();
591
                        }
592
                        px = new Point2D.Double();
593
                        px.setLocation( ((pReal.getX() - this.getMinX()) * w) / getWCWidth(),
594
                                                        ((this.getMaxY() - pReal.getY()) * h) / getWCHeight());
595
                }
596
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
597

    
598
                StringXMLItem[] item = new StringXMLItem[1];
599
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
600

    
601
                data += "  <raster\n";
602
                data += "    View_Point=\"" + p.getX() + " , " + p.getY() + "\"\n";
603
                data += "    World_Point=\"" + MathUtils.format(pReal.getX(), 3) + " , " + MathUtils.format(pReal.getY(), 3) + "\"\n";
604
                if (px == null)
605
                        data += "    Pixel_Point=\"Out\"\n";
606
                else
607
                        data += "    Pixel_Point=\"" + (int) px.getX() + " , " + (int) px.getY() + "\"\n";
608
                data += "    RGB=\"" + rgb[1] + "  " + rgb[2] + "  " + rgb[3] + "\"\n";
609
                data += "    Band_Value=\"";
610
                try {
611
                        if (px != null) {
612
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3){
613
                                        for(int i = 0; i < getBandCount(); i++)
614
                                                data += ((Integer)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).intValue() + "  ";
615
                                }
616
                                if(getDataType()[0] == 4){
617
                                        for(int i = 0; i < getBandCount(); i++)
618
                                                data += ((Float)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).floatValue() + "  ";
619
                                }
620
                                if(getDataType()[0] == 5){
621
                                        for(int i = 0; i < getBandCount(); i++)
622
                                                data += ((Double)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).doubleValue() + "  ";
623
                                }
624
                        }
625
                } catch (RasterDriverException ex) {
626
                        throw new ReadDriverException("Error en el acceso al dataset", ex);
627
                } catch (InvalidSetViewException ex) {
628
                        throw new ReadDriverException("Error en la asignaci?n de la vista en getData", ex);
629
                } catch (FileNotOpenException ex) {
630
                        throw new ReadDriverException("Fichero no abierto en el dataset", ex);
631
                }
632
                data += "\"\n";
633
                data += "  />\n";
634
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
635

    
636
                item[0] = new StringXMLItem(data, this);
637
                return item;
638
        }
639

    
640
        /**
641
         * Filters a string for being suitable as XML Tag, erasing
642
         * all not alphabetic or numeric characters.
643
         * @param s
644
         * @return string normalized
645
         */
646
        private String normalizeAsXMLTag(String s) {
647
                return s.replaceAll("[^a-zA-Z0-9]", "");
648
        }
649

    
650
        /**
651
         * Obtiene atributos a partir de un georasterfile
652
         * @return
653
         */
654
        public ArrayList getAttributes() {
655
                ArrayList attr = new ArrayList();
656
                if(!isOpen())
657
                        return attr;
658
                Object [][] a = {
659
                        {"Filename", dataset.getDataset(0)[0].getFName()},
660
                        {"Filesize", new Long(dataset.getFileSize())},
661
                        {"Width", new Integer((int)dataset.getWidth())},
662
                        {"Height", new Integer((int)dataset.getHeight())},
663
                        {"Bands", new Integer(dataset.getBandCount())}
664
                };
665
                for (int i = 0; i < a.length; i++)
666
                        attr.add(a[i]);
667
                return attr;
668
        }
669

    
670
        /**
671
         * Escribe en el proyecto la capa actual
672
         * @throws XMLException
673
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
674
         */
675
        public XMLEntity getXMLEntity() throws XMLException {
676
                if(isClosed() || isAwake())
677
                        return null;
678
                
679
                XMLEntity xml = super.getXMLEntity();
680
                if(getFile() != null)
681
                        xml.putProperty("file", getFile());
682
                xml.putProperty("driverName", "gvSIG Raster Driver");
683

    
684
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
685
                if (status == null)
686
                        status = new StatusLayerRaster();
687
                status.getXMLEntity(xml, true, this);
688

    
689
                return xml;
690
        }
691

    
692
        public void setXMLEntity03(XMLEntity xml) throws XMLException {
693
        }
694

    
695
        /**
696
         * Recupera de disco los datos de la capa.
697
         */
698
        public void setXMLEntity(XMLEntity xml) throws XMLException {
699
                super.setXMLEntity(xml);
700

    
701
                try {                                
702
                        params = new File(xml.getStringProperty("file"));
703
                        
704
                        if(params != null && getName() != null && getName().compareTo("") != 0) {
705
                                try {
706
                                        enableAwake();
707
                                } catch (NotAvailableStateException e) {
708
                                        Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
709
                                }
710
                        }
711
                        if(!super.getFLayerStatus().visible) 
712
                                enableStopped();
713
                
714
                        // Para notificar al adapter-driver cual es la proyecci?n.
715
                        setProjection(super.getProjection());
716

    
717
                        //Inicializamos la clase a la que se usa por defecto para
718
                        //compatibilidad con proyectos antiguos
719
                        String claseStr = StatusLayerRaster.defaultClass;
720
                        if (xml.contains("raster.class"))
721
                                claseStr = xml.getStringProperty("raster.class");
722

    
723
                        if (status != null)
724
                                status.setXMLEntity(xml, this);
725
                        else {
726
                                // Cuando cargamos un proyecto
727

    
728
                                if (claseStr != null && !claseStr.equals("")) {
729
                                        try {
730
                                                Class clase = LayerFactory.getLayerClassForLayerClassName(claseStr);
731
                                                Constructor constr = clase.getConstructor(null);
732
                                                status = (IStatusRaster) constr.newInstance(null);
733
                                                if (status != null) {
734
                                                        status.setXMLEntity(xml, this);
735
                                                        filterArguments = status.getFilterArguments();
736
                                                        
737
                                                        crearColorTable();
738
                                                }
739
                                        } catch (ClassNotFoundException exc) {
740
                                                throw new XMLException("Error localizando la clase a instanciar. " + claseStr, exc);
741
                                        } catch (InstantiationException exc) {
742
                                                throw new XMLException("Error instanciando " + claseStr, exc);
743
                                        } catch (IllegalAccessException exc) {
744
                                                throw new XMLException("Error instanciando " + claseStr, exc);
745
                                        } catch (NoSuchMethodException exc) {
746
                                                throw new XMLException("Error instanciando " + claseStr, exc);
747
                                        } catch (InvocationTargetException exc) {
748
                                                throw new XMLException("Error obteniendo el constructor para la clase " + claseStr, exc);
749
                                        }
750
                                }
751
                        }
752
                        firstLoad = true;
753
                } catch (NotExistInXMLEntity e) {
754
                        
755
                }
756
        }
757
        
758
        private void crearColorTable() {
759
                ArrayList color = (ArrayList) filterArguments.clone();
760
                setLastLegend(ColorTableListManager.createColorTableFromArray(color));
761
        }
762

    
763
        /* (non-Javadoc)
764
         * @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)
765
         */
766
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet propeties) throws ReadDriverException {
767

    
768
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
769
                        return;
770

    
771
                isPrinting = true;
772
                if (!mustTilePrint) {
773
                        draw(null, g, viewPort, cancel,scale);
774
                } else {
775
                        // Para no pedir imagenes demasiado grandes, vamos
776
                        // a hacer lo mismo que hace EcwFile: chunkear.
777
                        // Llamamos a drawView con cuadraditos m?s peque?os
778
                        // del BufferedImage ni caso, cuando se imprime viene con null
779
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
780
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
781

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

    
785
                        //RasterStats stats = getSource().getFilterStack().getStats();
786
                        //if(stats != null)
787
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
788

    
789

    
790
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
791
                                // Parte que dibuja
792
                                try {
793
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
794
                                        draw(null, g, vp, cancel, scale);
795
                                } catch (NoninvertibleTransformException e) {
796
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
797
                                }
798
                        }
799
                        /*if(stats != null){
800
                                getSource().getFilterStack().getStats().history.clear();
801
                                stats = getSource().getFilterStack().getStats();
802
                        }*/
803
                }
804
                isPrinting = false;
805
        }
806

    
807
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale) throws ReadDriverException {
808
                if(!isOpen())
809
                        return;
810
                
811
                // Para no pedir imagenes demasiado grandes, vamos
812
                // a hacer lo mismo que hace EcwFile: chunkear.
813
                // Llamamos a drawView con cuadraditos m?s peque?os
814
                // del BufferedImage ni caso, cuando se imprime viene con null
815

    
816
                int numW, numH;
817
                int stepX, stepY;
818
                int xProv, yProv;
819
                int A = 1500;
820
                int H = 1500;
821
                int altoAux, anchoAux;
822
                
823
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
824

    
825
                // Vamos a hacerlo en trozos de AxH
826
                Rectangle r = g.getClipBounds();
827
                numW = (int) (r.width) / A;
828
                numH = (int) (r.height) / H;
829

    
830
                double[] srcPts = new double[8];
831
                double[] dstPts = new double[8];
832

    
833
                yProv = (int) r.y;
834
                for (stepY = 0; stepY < numH + 1; stepY++) {
835
                        if ((yProv + H) > r.getMaxY())
836
                                altoAux = (int) r.getMaxY() - yProv;
837
                        else
838
                                altoAux = H;
839

    
840
                        xProv = (int) r.x;
841
                        for (stepX = 0; stepX < numW + 1; stepX++) {
842
                                if ((xProv + A) > r.getMaxX())
843
                                        anchoAux = (int) r.getMaxX() - xProv;
844
                                else
845
                                        anchoAux = A;
846

    
847
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
848

    
849
                                // Parte que dibuja
850
                                srcPts[0] = xProv;
851
                                srcPts[1] = yProv;
852
                                srcPts[2] = xProv + anchoAux + 1;
853
                                srcPts[3] = yProv;
854
                                srcPts[4] = xProv + anchoAux + 1;
855
                                srcPts[5] = yProv + altoAux + 1;
856
                                srcPts[6] = xProv;
857
                                srcPts[7] = yProv + altoAux + 1;
858

    
859
                                try {
860
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
861
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
862
                                        // Extent extent = new Extent(rectCuadricula);
863

    
864
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
865
                                        ViewPort vp = viewPort.cloneViewPort();
866
                                        vp.setImageSize(tam);
867
                                        vp.setExtent(rectCuadricula);
868
                                        vp.setAffineTransform(mat);
869
                                        draw(null, g, vp, cancel, scale);
870

    
871
                                } catch (NoninvertibleTransformException e) {
872
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
873
                                }
874
                                // Fin parte que dibuja
875
                                xProv = xProv + A;
876
                        }
877
                        yProv = yProv + H;
878
                }
879
        }
880

    
881
        /**
882
         * Borra de la lista de listeners el que se pasa como par?metro.
883
         *
884
         * @param o LayerListener a borrar.
885
         *
886
         * @return True si ha sido correcto el borrado del Listener.
887
         */
888
        public boolean removeLayerListener(LayerListener o) {
889
                //Salva a RMF
890
                try {
891
                        if(this.getDataSource() != null)
892
                                this.getDataSource().saveRmfModification();
893
                } catch (IOException e) {
894
                        //No se ha salvado nada
895
                }
896

    
897
                if (this.isRemoveRasterFlag()) {
898
                        dataset.close();
899
                        this.setRemoveRasterFlag(true);
900
                }
901
                return super.layerListeners.remove(o);
902
        }
903

    
904
        /**
905
         * @return Returns the removeRasterFlag.
906
         */
907
        public boolean isRemoveRasterFlag() {
908
                return removeRasterFlag;
909
        }
910

    
911
        /**
912
         * Asigna el valor del flag que dice si destruimos la memoria del raster
913
         * al eliminarlo del TOC o  no.
914
         * @param removeRasterFlag The removeRasterFlag to set.
915
         */
916
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
917
                this.removeRasterFlag = removeRasterFlag;
918
        }
919

    
920
        /*
921
         * (non-Javadoc)
922
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
923
         */
924
        public ImageIcon getTocImageIcon() {
925
                //El icono de capa detenida no se utiliza de momento ya que los refrescos del TOC no se hacen en el momento deseado
926
                //if(!isOpen())
927
                        //return new ImageIcon(MapControl.class.getResource("images/map_ico_ko.gif"));
928
                return new ImageIcon(MapControl.class.getResource("images/map_ico_ok.gif"));
929
        }
930

    
931
        /*
932
         *  (non-Javadoc)
933
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
934
         */
935
        public int[] getTileSize() {
936
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
937
                return size;
938
        }
939

    
940
        /*
941
         *  (non-Javadoc)
942
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
943
         */
944
        public boolean isTiled() {
945
                return mustTileDraw;
946
        }
947

    
948
        /**
949
         * Obtiene el flag que dice si la imagen est? o no georreferenciada
950
         * @return true si est? georreferenciada y false si no lo est?.
951
         */
952
        public boolean isGeoreferenced() {
953
                return dataset.isGeoreferenced();
954
        }
955

    
956
        /**
957
         * Get datasource object
958
         * @return
959
         */
960
        public BufferFactory getBufferFactory(){
961
                return bufferFactory;
962
        }
963

    
964
        /**
965
         * Asigna el valor noData asociado a la capa
966
         * @return double que representa el valor noData asociado a la capa
967
         */
968
        public double getNoDataValue() {
969
                return noDataValue;
970
        }
971

    
972
        /**
973
         * Asigna el valor no data asociado a la capa
974
         * @param nd
975
         */
976
        public void setNoDataValue(double nd){
977
                if (bufferFactory != null)
978
                        bufferFactory.setNoDataValue(nd);
979
                noDataValue = nd;
980
        }
981

    
982
        /*
983
         * (non-Javadoc)
984
         * @see org.gvsig.fmap.raster.IRasterOperations#getPXHeight()
985
         */
986
        public double getPxHeight() {
987
                return dataset.getHeight();
988
        }
989

    
990
        /*
991
         * (non-Javadoc)
992
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
993
         */
994
        public double getPxWidth() {
995
                return dataset.getWidth();
996
        }
997

    
998
        /*
999
         * (non-Javadoc)
1000
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCHeight()
1001
         */
1002
        public double getWCHeight() {
1003
                return getFullExtent().getHeight();
1004
        }
1005

    
1006
        /*
1007
         * (non-Javadoc)
1008
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
1009
         */
1010
        public double getWCWidth() {
1011
                return getFullExtent().getWidth();
1012
        }
1013

    
1014
        /*
1015
         * (non-Javadoc)
1016
         * @see org.gvsig.fmap.raster.IRasterFile#getFileSize()
1017
         */
1018
        public long[] getFileSize(){
1019
                int nFiles = dataset.getDatasetCount();
1020
                long[] s = new long[nFiles];
1021
                for (int i = 0; i < nFiles; i++)
1022
                        s[i] = dataset.getFileSize();
1023
                return s;
1024
        }
1025

    
1026
        /*
1027
         * (non-Javadoc)
1028
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
1029
         */
1030
        public String[] getFileName(){
1031
                int nFiles = dataset.getDatasetCount();
1032
                String[] s = new String[nFiles];
1033
                for (int i = 0; i < nFiles; i++)
1034
                        s[i] = dataset.getDataset(i)[0].getFName();
1035
                return s;
1036
        }
1037

    
1038
        /*
1039
         * (non-Javadoc)
1040
         * @see org.gvsig.fmap.raster.IRasterFile#getFileCount()
1041
         */
1042
        public int getFileCount() {
1043
                return (dataset != null) ? dataset.getDatasetCount() : 0;
1044
        }
1045

    
1046
        /*
1047
         * (non-Javadoc)
1048
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
1049
         */
1050
        public String getFileFormat() {
1051
                String fName = dataset.getDataset(0)[0].getFName();
1052
                int index = fName.lastIndexOf(".") + 1;
1053
                String ext = null;
1054
                if (index > 0)
1055
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1056
                return ext;
1057
        }
1058

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

    
1067
        /*
1068
         * (non-Javadoc)
1069
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1070
         */
1071
        public int[] getDataType() {
1072
                return dataset.getDataType();
1073
        }
1074

    
1075
        /*
1076
         * (non-Javadoc)
1077
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
1078
         */
1079
        public GridTransparency getRenderTransparency() {
1080
                return getRender().getLastTransparency();
1081
        }
1082

    
1083
        /*
1084
         * (non-Javadoc)
1085
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1086
         */
1087
        public RasterFilterList getRenderFilterList() {
1088
                return getRender().getFilterList();
1089
        }
1090
        
1091
        /*
1092
         * (non-Javadoc)
1093
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
1094
         */
1095
        public int[] getRenderBands() {
1096
                return getRender().getRenderBands();
1097
        }
1098
        
1099
        /*
1100
         * (non-Javadoc)
1101
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
1102
         */
1103
        public void setRenderBands(int[] renderBands) {
1104
                getRender().setRenderBands(renderBands);
1105
        }
1106
        
1107
        /*
1108
         * (non-Javadoc)
1109
         * @see org.gvsig.raster.hierarchy.IRasterDataset#getDataSource()
1110
         */
1111
        public IRasterDataSource getDataSource() {
1112
                return dataset;
1113
        }
1114

    
1115
        /*
1116
         * (non-Javadoc)
1117
         * @see org.gvsig.fmap.raster.IRasterDataset#addFile(java.lang.String)
1118
         */
1119
        public void addFile(String fileName) throws NotSupportedExtensionException, RasterDriverException{
1120
                if (getRender() != null)
1121
                        bufferFactory.addFile(RasterDataset.open(getProjection(), fileName));
1122
        }
1123

    
1124
        /*
1125
         * (non-Javadoc)
1126
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
1127
         */
1128
        public void delFile(String fileName) {
1129
                if (getRender() != null)
1130
                        bufferFactory.removeFile(fileName);
1131
        }
1132

    
1133
        /*
1134
         * (non-Javadoc)
1135
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1136
         */
1137
        public Object getInfo(String key) {
1138
                if (key.equals("DriverName"))
1139
                        return "gvSIG Raster Driver";
1140
                return null;
1141
        }
1142

    
1143
        /*
1144
         * (non-Javadoc)
1145
         * @see org.gvsig.raster.shared.IRasterOperations#getMetadata()
1146
         */
1147
        public DatasetMetadata[] getMetadata() {
1148
                int count = dataset.getDatasetCount();
1149
                DatasetMetadata[] metadata = new DatasetMetadata[count];
1150
                for (int i = 0; i < count; i++) {
1151
                        metadata[i] = dataset.getDataset(i)[0].getMetadata();
1152
                }
1153
                return metadata;
1154
        }
1155

    
1156
        /*
1157
         * (non-Javadoc)
1158
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
1159
         */
1160
        public int[] getBandCountFromDataset() {
1161
                int count = dataset.getDatasetCount();
1162
                int[] bands = new int[count];
1163
                for (int i = 0; i < count; i++) 
1164
                        bands[i] = dataset.getDataset(i)[0].getBandCount();
1165
                return bands;
1166
        }
1167

    
1168
        /*
1169
         * (non-Javadoc)
1170
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1171
         */
1172
        public String getColourInterpretation(int band, int dataset) {
1173
                if (this.dataset.getColorInterpretation(dataset) == null)
1174
                        return "Undefined";
1175
                return this.dataset.getColorInterpretation(dataset).get(band);
1176
        }
1177

    
1178
        /*
1179
         * (non-Javadoc)
1180
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
1181
         */
1182
        public String getWktProjection() throws RasterDriverException {
1183
                try {
1184
                        return dataset.getWktProjection();
1185
                } catch (RasterDriverException e) {
1186
                        throw new RasterDriverException("No puedo obtener la proyecci?n asociada al dataset.", e);
1187
                }
1188
        }
1189

    
1190
        /**
1191
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1192
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1193
         * cacheado o no dependiendo del tama?o de esta.
1194
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1195
         * @return Grid.
1196
         * @throws InterruptedException 
1197
         */
1198
        public Grid getFullGrid(boolean interpolated) throws InterruptedException {
1199
                BufferFactory bf = getBufferFactory();
1200
                bf.clearDrawableBand();
1201
                bf.setAllDrawableBands();
1202
                bf.setAreaOfInterest();
1203
                return new Grid(bf, interpolated);
1204
        }
1205

    
1206
        /*
1207
         * (non-Javadoc)
1208
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1209
         */
1210
        public Extent getFullRasterExtent() {
1211
                return this.getDataSource().getExtent();
1212
        }
1213

    
1214

    
1215
        /**
1216
         * Devuelve el fichero asociado a la capa o null si no tiene.
1217
         * @return Fichero.
1218
         */
1219
        public File getFile() {
1220
                return (params instanceof File) ? ((File)params) : null;
1221
        }
1222

    
1223
        /**
1224
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1225
         * @param file Fichero a consultar
1226
         * @return true si es aceptado y false si no lo es.
1227
         */
1228
        public static boolean isFileAccepted(File file) {
1229
                return RasterDataset.fileIsSupported(file.getName());
1230
        }
1231

    
1232
        /*
1233
         * (non-Javadoc)
1234
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1235
         */
1236
        public boolean existColorTable() {
1237
                return getRender().existColorTable();
1238
        }
1239

    
1240
        ILegend lastLegend = null;
1241
        /**
1242
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1243
         * capa busque una leyenda valida.
1244
         * @param ct
1245
         */
1246
        public void setLastLegend(ColorTable ct) {
1247
                lastLegend = ColorTableLegend.createLegend(ct);
1248
        }
1249

    
1250
        /**
1251
         * Devuelve la Leyenda de la capa.
1252
         * @return Leyenda.
1253
         */
1254
        public ILegend getLegend() {
1255
                if (lastLegend != null)
1256
                        return lastLegend;
1257

    
1258
                ColorTable ct = null;
1259
                if(getRenderFilterList() == null)
1260
                        return null;
1261
                
1262
                ColorTableFilter colorTableFilter = (ColorTableFilter) getRenderFilterList().getByName(ColorTableFilter.names[0]);
1263
                if (colorTableFilter != null) {
1264
                        ColorTable ct2 = new GridPalette((ColorTable) colorTableFilter.getColorTable());
1265
                        if (ct2.getColorItems() != null)
1266
                                ct = ct2;
1267
                }
1268
                if (ct == null)
1269
                        ct = this.getDataSource().getColorTables()[0];
1270

    
1271
                return ColorTableLegend.createLegend(ct);
1272
        }
1273

    
1274
        /*
1275
         * (non-Javadoc)
1276
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1277
         */
1278
        public void addLegendListener(LegendListener listener) {
1279
                layerChangeSupport.addLayerListener(listener);
1280
        }
1281

    
1282
        /*
1283
         *  (non-Javadoc)
1284
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1285
         */
1286
        public int getShapeType() throws ReadDriverException {
1287
                return FShape.POLYGON;
1288
        }
1289

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

    
1298
        /**
1299
         * Metodo que obtiene si un punto cae dentro de los l?mites de la capa
1300
         * o fuera de ellos.
1301
         * @param p Punto a calcular
1302
         * @return true si est? dentro de los l?mites y false si est? fuera
1303
         */
1304
        public boolean isInside(Point2D p) {
1305
                 return getDataSource().isInside(p);
1306
        }
1307

    
1308
        /**
1309
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1310
         * @return AffineTransform
1311
         */
1312
        public AffineTransform getAffineTransform() {
1313
                return getDataSource().getAffineTransform();
1314
        }
1315

    
1316
        /**
1317
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista
1318
         * @param transf
1319
         */
1320
        public void setAffineTransform(AffineTransform transf) {
1321
                affineTransformList.add(transf);
1322
                getDataSource().setAffineTransform(transf);
1323
        }
1324
        
1325
        /**
1326
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista.
1327
         * Esta versi?n no guarda en el historico.
1328
         * @param transf
1329
         */
1330
        public void setAT(AffineTransform transf) {
1331
                getDataSource().setAffineTransform(transf);
1332
        }
1333
        
1334
        /**
1335
         * Obtiene la lista de transformaciones que se han ido aplicando al raster.
1336
         * @return Historical. Lista de AffineTransform
1337
         */
1338
        public Historical getAffineTransformHistorical() {
1339
                return this.affineTransformList;
1340
        }
1341
        
1342
        /**
1343
         * Salva la georreferenciaci?n a fichero rmf.
1344
         * @param fName
1345
         * @throws IOException  
1346
         */
1347
        public void saveGeoToRmf() throws IOException {
1348
                if(!isOpen())
1349
                        return;
1350
                getDataSource().saveGeoToRmf();
1351
                affineTransformList.clear();
1352
                affineTransformList.add(this.getAffineTransform());
1353
        }
1354

    
1355
        /*
1356
         * (non-Javadoc)
1357
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1358
         */
1359
        public boolean isActionEnabled(int action) {
1360
                switch (action) {
1361
                        case IRasterLayerActions.BANDS_FILE_LIST:
1362
                                if (existColorTable())
1363
                                        return false;
1364
                        case IRasterLayerActions.BANDS_RGB:
1365
                                if (existColorTable())
1366
                                        return false;
1367
                        case IRasterLayerActions.OPACITY:
1368
                        case IRasterLayerActions.TRANSPARENCY:
1369
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1370
                        case IRasterLayerActions.ENHANCED:
1371
                        case IRasterLayerActions.PANSHARPENING:
1372
                                return true;
1373
                }
1374
                return true;
1375
        }
1376
                
1377
        /*
1378
         * (non-Javadoc)
1379
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1380
         */
1381
        public void setVisible(boolean visibility) {
1382
                if(visibility)
1383
                        state.disableStopped();
1384
                else
1385
                        enableStopped();
1386
                
1387
                if(isAwake() || isClosed())
1388
                        try {
1389
                                this.load();
1390
                        } catch (LoadLayerException e) {
1391
                                e.printStackTrace();
1392
                        }
1393
                super.setVisible(visibility);
1394
        }
1395

    
1396
        /**
1397
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1398
         * @return valor de transparencia
1399
         */
1400
        public int getTransparency() {
1401
                return getRenderTransparency().getOpacity();
1402
        }
1403
        
1404
        /**
1405
         * Asigna la transparencia de la siguiente renderizaci?n
1406
         * @param valor de transparencia
1407
         */
1408
        public void setTransparency(int trans) {
1409
                getRenderTransparency().setOpacity(trans);
1410
        }
1411
        
1412
        /*****************************************************/
1413
        
1414
        public void disableStopped() {state.disableStopped();}
1415

    
1416
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1417

    
1418
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
1419

    
1420
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1421

    
1422
        public void enableStopped() {state.enableStopped();}
1423

    
1424
        public boolean isAwake() {return state.isAwake();}
1425

    
1426
        public boolean isClosed() {return state.isClosed();}
1427

    
1428
        public boolean isOpen() {return state.isOpen();}
1429

    
1430
        public boolean isStopped() {return state.isStopped();}
1431
}