Statistics
| Revision:

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

History | View | Annotate | Download (44.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
        
133
        /**
134
         * Lista de transformaciones afines que son aplicadas. Esta lista es simplemente un
135
         * historico que no se utiliza. Es posible utilizarlo para recuperar transformaciones
136
         * anteriores.
137
         */
138
        private Historical               affineTransformList = new Historical();
139
        
140
        static {
141
                 RasterLibrary.wakeUp();
142
        }
143

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
332
                getRender().setFilterList(filterList);
333
        }
334

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
691
                return xml;
692
        }
693

    
694
        public void setXMLEntity03(XMLEntity xml) throws XMLException {
695
        }
696

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

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

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

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

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

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

    
770
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
771
                        return;
772

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

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

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

    
791

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

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

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

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

    
832
                double[] srcPts = new double[8];
833
                double[] dstPts = new double[8];
834

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

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

    
849
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
850

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

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

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

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

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

    
899
                if (this.isRemoveRasterFlag()) {
900
                        if(dataset != null)
901
                                dataset.close();
902
                        this.setRemoveRasterFlag(true);
903
                }
904
                return super.layerListeners.remove(o);
905
        }
906

    
907
        /**
908
         * @return Returns the removeRasterFlag.
909
         */
910
        public boolean isRemoveRasterFlag() {
911
                return removeRasterFlag;
912
        }
913

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

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

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

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

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

    
959
        /**
960
         * Get datasource object
961
         * @return
962
         */
963
        public BufferFactory getBufferFactory(){
964
                return bufferFactory;
965
        }
966

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1086
        /*
1087
         * (non-Javadoc)
1088
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1089
         */
1090
        public RasterFilterList getRenderFilterList() {
1091
                return getRender().getFilterList();
1092
        }
1093
        
1094
        /*
1095
         * (non-Javadoc)
1096
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
1097
         */
1098
        public int[] getRenderBands() {
1099
                return getRender().getRenderBands();
1100
        }
1101
        
1102
        /*
1103
         * (non-Javadoc)
1104
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
1105
         */
1106
        public void setRenderBands(int[] renderBands) {
1107
                getRender().setRenderBands(renderBands);
1108
        }
1109
        
1110
        /*
1111
         * (non-Javadoc)
1112
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
1113
         */
1114
        public void setRenderFilterList(RasterFilterList filterList) {
1115
                getRender().setFilterList(filterList);
1116
        }
1117
        
1118
        /*
1119
         * (non-Javadoc)
1120
         * @see org.gvsig.raster.hierarchy.IRasterDataset#getDataSource()
1121
         */
1122
        public IRasterDataSource getDataSource() {
1123
                return dataset;
1124
        }
1125

    
1126
        /*
1127
         * (non-Javadoc)
1128
         * @see org.gvsig.fmap.raster.IRasterDataset#addFile(java.lang.String)
1129
         */
1130
        public void addFile(String fileName) throws NotSupportedExtensionException, RasterDriverException{
1131
                if (getRender() != null)
1132
                        bufferFactory.addFile(RasterDataset.open(getProjection(), fileName));
1133
        }
1134

    
1135
        /*
1136
         * (non-Javadoc)
1137
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
1138
         */
1139
        public void delFile(String fileName) {
1140
                if (getRender() != null)
1141
                        bufferFactory.removeFile(fileName);
1142
        }
1143

    
1144
        /*
1145
         * (non-Javadoc)
1146
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1147
         */
1148
        public Object getInfo(String key) {
1149
                if (key.equals("DriverName"))
1150
                        return "gvSIG Raster Driver";
1151
                return null;
1152
        }
1153

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

    
1167
        /*
1168
         * (non-Javadoc)
1169
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
1170
         */
1171
        public int[] getBandCountFromDataset() {
1172
                int count = dataset.getDatasetCount();
1173
                int[] bands = new int[count];
1174
                for (int i = 0; i < count; i++) 
1175
                        bands[i] = dataset.getDataset(i)[0].getBandCount();
1176
                return bands;
1177
        }
1178

    
1179
        /*
1180
         * (non-Javadoc)
1181
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1182
         */
1183
        public String getColourInterpretation(int band, int dataset) {
1184
                if (this.dataset.getColorInterpretation(dataset) == null)
1185
                        return "Undefined";
1186
                return this.dataset.getColorInterpretation(dataset).get(band);
1187
        }
1188

    
1189
        /*
1190
         * (non-Javadoc)
1191
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
1192
         */
1193
        public String getWktProjection() throws RasterDriverException {
1194
                try {
1195
                        return dataset.getWktProjection();
1196
                } catch (RasterDriverException e) {
1197
                        throw new RasterDriverException("No puedo obtener la proyecci?n asociada al dataset.", e);
1198
                }
1199
        }
1200

    
1201
        /**
1202
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1203
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1204
         * cacheado o no dependiendo del tama?o de esta.
1205
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1206
         * @return Grid.
1207
         * @throws InterruptedException 
1208
         */
1209
        public Grid getFullGrid(boolean interpolated) throws InterruptedException {
1210
                BufferFactory bf = getBufferFactory();
1211
                bf.clearDrawableBand();
1212
                bf.setAllDrawableBands();
1213
                bf.setAreaOfInterest();
1214
                return new Grid(bf, interpolated);
1215
        }
1216

    
1217
        /*
1218
         * (non-Javadoc)
1219
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1220
         */
1221
        public Extent getFullRasterExtent() {
1222
                return this.getDataSource().getExtent();
1223
        }
1224

    
1225

    
1226
        /**
1227
         * Devuelve el fichero asociado a la capa o null si no tiene.
1228
         * @return Fichero.
1229
         */
1230
        public File getFile() {
1231
                return (params instanceof File) ? ((File)params) : null;
1232
        }
1233

    
1234
        /**
1235
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1236
         * @param file Fichero a consultar
1237
         * @return true si es aceptado y false si no lo es.
1238
         */
1239
        public static boolean isFileAccepted(File file) {
1240
                return RasterDataset.fileIsSupported(file.getName());
1241
        }
1242

    
1243
        /*
1244
         * (non-Javadoc)
1245
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1246
         */
1247
        public boolean existColorTable() {
1248
                return getRender().existColorTable();
1249
        }
1250

    
1251
        /**
1252
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1253
         * capa busque una leyenda valida.
1254
         * @param ct
1255
         */
1256
        public void setLastLegend(ColorTable ct) {
1257
                lastLegend = ColorTableLegend.createLegend(ct);
1258
        }
1259

    
1260
        /**
1261
         * Devuelve la Leyenda de la capa.
1262
         * @return Leyenda.
1263
         */
1264
        public ILegend getLegend() {
1265
                if (lastLegend != null)
1266
                        return lastLegend;
1267

    
1268
                return null;
1269
        }
1270

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

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

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

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

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

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

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

    
1393
        /**
1394
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1395
         * @return valor de transparencia
1396
         */
1397
        public int getTransparency() {
1398
                return getRenderTransparency().getOpacity();
1399
        }
1400
        
1401
        /**
1402
         * Asigna la transparencia de la siguiente renderizaci?n
1403
         * @param valor de transparencia
1404
         */
1405
        public void setTransparency(int trans) {
1406
                getRenderTransparency().setOpacity(trans);
1407
                getRenderTransparency().activeTransparency();
1408
        }
1409
        
1410
        /*
1411
         * (non-Javadoc)
1412
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#cloneLayer()
1413
         */
1414
        public FLayer cloneLayer() throws Exception {
1415
                FLyrRasterSE newLayer = FLyrRasterSE.createLayer(this.getName(), params, this.getProjection());
1416
                ArrayList filters = getRender().getFilterList().getStatusCloned();
1417
                RasterFilterList filterList = new RasterFilterList();
1418
                filterList.setInitDataType(newLayer.getDataType()[0]);
1419
                filterList.setStatus(filters);
1420
                newLayer.getRender().setFilterList(filterList);
1421
                newLayer.getRender().setLastTransparency(new GridTransparency(getRenderTransparency()));
1422
                return newLayer;
1423
        }
1424
        
1425
        /*****************************************************/
1426
        
1427
        public void disableStopped() {state.disableStopped();}
1428

    
1429
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1430

    
1431
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
1432

    
1433
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1434

    
1435
        public void enableStopped() {state.enableStopped();}
1436

    
1437
        public boolean isAwake() {return state.isAwake();}
1438

    
1439
        public boolean isClosed() {return state.isClosed();}
1440

    
1441
        public boolean isOpen() {return state.isOpen();}
1442

    
1443
        public boolean isStopped() {return state.isStopped();}
1444
}