Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRasterTools-SE / src / org / gvsig / fmap / raster / layers / FLyrRasterSE.java @ 13829

History | View | Annotate | Download (44.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.FLayer;
82
import com.iver.cit.gvsig.fmap.layers.FLyrDefault;
83
import com.iver.cit.gvsig.fmap.layers.LayerChangeSupport;
84
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
85
import com.iver.cit.gvsig.fmap.layers.LayerListener;
86
import com.iver.cit.gvsig.fmap.layers.LegendListener;
87
import com.iver.cit.gvsig.fmap.layers.Tiling;
88
import com.iver.cit.gvsig.fmap.layers.XMLException;
89
import com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable;
90
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
91
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
92
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
93
import com.iver.cit.gvsig.fmap.rendering.ILegend;
94
import com.iver.cit.gvsig.project.documents.view.gui.IView;
95
import com.iver.cit.gvsig.project.documents.view.gui.View;
96
import com.iver.utiles.NotExistInXMLEntity;
97
import com.iver.utiles.XMLEntity;
98
import com.iver.utiles.swing.threads.Cancellable;
99
/**
100
 * Capa raster
101
 * @author Nacho Brodin (nachobrodin@gmail.com)
102
 */
103
public class FLyrRasterSE extends FLyrDefault
104
        implements IRasterProperties, IRasterDataset, InfoByPoint, Classifiable,
105
        IRasterOperations, IRasterLayerActions, ILayerState {
106
        public static double             noDataDefault      = -99999;
107
        boolean                          isPrinting         = false;
108
        boolean                          mustTileDraw       = false;
109
        boolean                          mustTilePrint      = true;
110
        private int                      maxTileDrawWidth   = 200;
111
        private int                      maxTileDrawHeight  = 200;
112
        int                              maxTilePrintWidth  = 1500;
113
        int                              maxTilePrintHeight = 1500;
114
        protected IStatusRaster  status             = null;
115
        private boolean                  firstLoad          = false;
116
        private boolean                  removeRasterFlag   = true;
117
        private Object                   params             = null;
118
        protected IRasterDataSource      dataset            = null;
119
        protected Rendering              render             = null;
120
        protected BufferFactory          bufferFactory      = null;
121
        private int                      posX               = 0;
122
        private int                      posY               = 0;
123
        private double                   posXWC             = 0;
124
        private int                      posYWC             = 0;
125
        private int                      r                  = 0;
126
        private int                      g                  = 0;
127
        private int                      b                  = 0;
128
        private LayerChangeSupport       layerChangeSupport = new LayerChangeSupport();
129
        public double                    noDataValue        = -99999;
130
        private FLyrState                state             = new FLyrState();
131
        private ArrayList                filterArguments   = 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
                        ColorTableListManager ctm = new ColorTableListManager(filterManager);
322
                        ctm.addColorTableFilter(p);
323
                } else {
324
                        if (getDataType()[0] != IBuffer.TYPE_BYTE) {
325
                                IStatistics stats = getDataSource().getStatistics();
326
                                EnhancementListManager elm = new EnhancementListManager(filterManager);
327
                                elm.addEnhancedFilter(false, stats, 0.0, getRender().getRenderBands());
328
                        }
329
                }
330

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
690
                return xml;
691
        }
692

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

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

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

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

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

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

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

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

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

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

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

    
790

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1224

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

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

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

    
1250
        ILegend lastLegend = null;
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
                ColorTable ct = null;
1269
                if(getRenderFilterList() == null)
1270
                        return null;
1271
                
1272
                ColorTableFilter colorTableFilter = (ColorTableFilter) getRenderFilterList().getByName(ColorTableFilter.names[0]);
1273
                if (colorTableFilter != null) {
1274
                        ColorTable ct2 = new GridPalette((ColorTable) colorTableFilter.getColorTable());
1275
                        if (ct2.getColorItems() != null)
1276
                                ct = ct2;
1277
                }
1278
                if (ct == null)
1279
                        ct = this.getDataSource().getColorTables()[0];
1280

    
1281
                return ColorTableLegend.createLegend(ct);
1282
        }
1283

    
1284
        /*
1285
         * (non-Javadoc)
1286
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1287
         */
1288
        public void addLegendListener(LegendListener listener) {
1289
                layerChangeSupport.addLayerListener(listener);
1290
        }
1291

    
1292
        /*
1293
         *  (non-Javadoc)
1294
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1295
         */
1296
        public int getShapeType() throws ReadDriverException {
1297
                return FShape.POLYGON;
1298
        }
1299

    
1300
        /*
1301
         * (non-Javadoc)
1302
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1303
         */
1304
        public void removeLegendListener(LegendListener listener) {
1305
                layerChangeSupport.removeLayerListener(listener);
1306
        }
1307

    
1308
        /**
1309
         * Metodo que obtiene si un punto cae dentro de los l?mites de la capa
1310
         * o fuera de ellos.
1311
         * @param p Punto a calcular
1312
         * @return true si est? dentro de los l?mites y false si est? fuera
1313
         */
1314
        public boolean isInside(Point2D p) {
1315
                 return getDataSource().isInside(p);
1316
        }
1317

    
1318
        /**
1319
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1320
         * @return AffineTransform
1321
         */
1322
        public AffineTransform getAffineTransform() {
1323
                return getDataSource().getAffineTransform();
1324
        }
1325

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

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

    
1406
        /**
1407
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1408
         * @return valor de transparencia
1409
         */
1410
        public int getTransparency() {
1411
                return getRenderTransparency().getOpacity();
1412
        }
1413
        
1414
        /**
1415
         * Asigna la transparencia de la siguiente renderizaci?n
1416
         * @param valor de transparencia
1417
         */
1418
        public void setTransparency(int trans) {
1419
                getRenderTransparency().setOpacity(trans);
1420
                getRenderTransparency().activeTransparency();
1421
        }
1422
        
1423
        /*
1424
         * (non-Javadoc)
1425
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#cloneLayer()
1426
         */
1427
        public FLayer cloneLayer() throws Exception {
1428
                FLyrRasterSE newLayer = FLyrRasterSE.createLayer(this.getName(), params, this.getProjection());
1429
                ArrayList filters = getRender().getFilterList().getStatusCloned();
1430
                RasterFilterList filterList = new RasterFilterList();
1431
                filterList.setInitDataType(newLayer.getDataType()[0]);
1432
                filterList.setStatus(filters);
1433
                newLayer.getRender().setFilterList(filterList);
1434
                newLayer.getRender().setLastTransparency(new GridTransparency(getRenderTransparency()));
1435
                return newLayer;
1436
        }
1437
        
1438
        /*****************************************************/
1439
        
1440
        public void disableStopped() {state.disableStopped();}
1441

    
1442
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1443

    
1444
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
1445

    
1446
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1447

    
1448
        public void enableStopped() {state.enableStopped();}
1449

    
1450
        public boolean isAwake() {return state.isAwake();}
1451

    
1452
        public boolean isClosed() {return state.isClosed();}
1453

    
1454
        public boolean isOpen() {return state.isOpen();}
1455

    
1456
        public boolean isStopped() {return state.isStopped();}
1457
}