Statistics
| Revision:

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

History | View | Annotate | Download (52.8 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
import java.util.HashMap;
36

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

    
40
import org.apache.log4j.Logger;
41
import org.cresques.cts.IProjection;
42
import org.gvsig.fmap.raster.legend.ColorTableLegend;
43
import org.gvsig.raster.RasterLibrary;
44
import org.gvsig.raster.buffer.BufferFactory;
45
import org.gvsig.raster.dataset.CompositeDataset;
46
import org.gvsig.raster.dataset.FileNotOpenException;
47
import org.gvsig.raster.dataset.IBuffer;
48
import org.gvsig.raster.dataset.IRasterDataSource;
49
import org.gvsig.raster.dataset.InvalidSetViewException;
50
import org.gvsig.raster.dataset.MosaicNotValidException;
51
import org.gvsig.raster.dataset.MultiRasterDataset;
52
import org.gvsig.raster.dataset.NotSupportedExtensionException;
53
import org.gvsig.raster.dataset.RasterDataset;
54
import org.gvsig.raster.dataset.io.RasterDriverException;
55
import org.gvsig.raster.dataset.properties.DatasetMetadata;
56
import org.gvsig.raster.datastruct.ColorTable;
57
import org.gvsig.raster.datastruct.Extent;
58
import org.gvsig.raster.datastruct.ViewPortData;
59
import org.gvsig.raster.datastruct.serializer.ColorTableLibraryPersistence;
60
import org.gvsig.raster.grid.Grid;
61
import org.gvsig.raster.grid.GridException;
62
import org.gvsig.raster.grid.GridPalette;
63
import org.gvsig.raster.grid.GridTransparency;
64
import org.gvsig.raster.grid.filter.FilterTypeException;
65
import org.gvsig.raster.grid.filter.RasterFilterList;
66
import org.gvsig.raster.grid.filter.RasterFilterListManager;
67
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
68
import org.gvsig.raster.grid.filter.enhancement.EnhancementStretchListManager;
69
import org.gvsig.raster.grid.filter.enhancement.LinearStretchParams;
70
import org.gvsig.raster.grid.render.Rendering;
71
import org.gvsig.raster.hierarchy.IRasterDataset;
72
import org.gvsig.raster.hierarchy.IRasterOperations;
73
import org.gvsig.raster.hierarchy.IRasterProperties;
74
import org.gvsig.raster.hierarchy.IStatistics;
75
import org.gvsig.raster.process.RasterTask;
76
import org.gvsig.raster.process.RasterTaskQueue;
77
import org.gvsig.raster.util.ColorConversion;
78
import org.gvsig.raster.util.Historical;
79
import org.gvsig.raster.util.MathUtils;
80
import org.gvsig.raster.util.RasterToolsUtil;
81

    
82
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
83
import com.iver.andami.PluginServices;
84
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
85
import com.iver.cit.gvsig.fmap.ViewPort;
86
import com.iver.cit.gvsig.fmap.core.FShape;
87
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
88
import com.iver.cit.gvsig.fmap.layers.FLayer;
89
import com.iver.cit.gvsig.fmap.layers.FLyrDefault;
90
import com.iver.cit.gvsig.fmap.layers.LayerChangeSupport;
91
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
92
import com.iver.cit.gvsig.fmap.layers.LayerListener;
93
import com.iver.cit.gvsig.fmap.layers.Tiling;
94
import com.iver.cit.gvsig.fmap.layers.XMLException;
95
import com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable;
96
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
97
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
98
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
99
import com.iver.cit.gvsig.fmap.rendering.ILegend;
100
import com.iver.cit.gvsig.fmap.rendering.LegendListener;
101
import com.iver.cit.gvsig.project.documents.view.gui.IView;
102
import com.iver.cit.gvsig.project.documents.view.gui.View;
103
import com.iver.utiles.NotExistInXMLEntity;
104
import com.iver.utiles.XMLEntity;
105
import com.iver.utiles.swing.threads.Cancellable;
106
/**
107
 * Capa raster
108
 * @author Nacho Brodin (nachobrodin@gmail.com)
109
 */
110
public class FLyrRasterSE extends FLyrDefault implements IRasterProperties, IRasterDataset, InfoByPoint, Classifiable, IRasterOperations, IRasterLayerActions, ILayerState {
111
        boolean                     isPrinting          = false;
112
        boolean                     mustTileDraw        = false;
113
        boolean                     mustTilePrint       = true;
114
        private int                 maxTileDrawWidth    = 200;
115
        private int                 maxTileDrawHeight   = 200;
116
        int                         maxTilePrintWidth   = 1500;
117
        int                         maxTilePrintHeight  = 1500;
118
        protected IStatusRaster     status              = null;
119
        private boolean             firstLoad           = false;
120
        private boolean             removeRasterFlag    = true;
121
        private Object              params              = null;
122
        protected IRasterDataSource dataset             = null;
123
        protected Rendering         render              = null;
124
        protected BufferFactory     bufferFactory       = null;
125
        private int                 posX                = 0;
126
        private int                 posY                = 0;
127
        private double              posXWC              = 0;
128
        private int                 posYWC              = 0;
129
        private int                 r                   = 0;
130
        private int                 g                   = 0;
131
        private int                 b                   = 0;
132
        private LayerChangeSupport  layerChangeSupport  = new LayerChangeSupport();
133
        private FLyrState           state               = new FLyrState();
134
        private ArrayList           filterArguments     = null;
135
        protected ILegend           lastLegend          = null;
136
        private ArrayList           rois                = null;
137
        private RasterDrawStrategy  strategy            = null;
138
        static private IConfiguration configuration = new DefaultLayerConfiguration();
139

    
140
        /**
141
         * Tipo de valor no data asociado a la capa.
142
         * Sirve para diferenciar los estados seleccionados por el usuario. Siendo
143
         * estos estado General, Capa (Por defecto) y Personalizado
144
         */
145
        private int noDataType = 1;
146

    
147
        /**
148
         * Lista de transformaciones afines que son aplicadas. Esta lista es
149
         * simplemente un historico que no se utiliza. Es posible utilizarlo para
150
         * recuperar transformaciones anteriores.
151
         */
152
        private Historical          affineTransformList = new Historical();
153

    
154
        static {
155
                 RasterLibrary.wakeUp();
156
        }
157

    
158
        /**
159
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
160
         * @param layerName Nombre de la capa.
161
         * @param d RasterDriver.
162
         * @param f Fichero.
163
         * @param proj Proyecci?n.
164
         * @return Nueva capa de tipo raster.
165
         * @throws DriverIOException
166
         */
167
        public static FLyrRasterSE createLayer(String layerName, Object params,
168
                        IProjection proj) throws LoadLayerException {
169
                FLyrRasterSE capa = new FLyrRasterSE();
170
                capa.setLoadParams(params);
171
                capa.setName(layerName);
172
                capa.setProjection(proj);
173
                capa.load();
174
                return capa;
175
        }
176

    
177
        /**
178
         * Asigna los par?metros para la carga de la capa
179
         * @param param Par?metros.
180
         */
181
        public void setLoadParams(Object param){
182
                this.params = param;
183

    
184
                //Si la capa tiene nombre acivamos el estado awake
185
                if(params != null && getName() != null) {
186
                        try {
187
                                enableAwake();
188
                        } catch (NotAvailableStateException e) {
189
                                Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
190
                        }
191
                }
192
        }
193

    
194
        /**
195
         * Obtiene los par?metros para la carga de la capa
196
         * @return param Par?metros.
197
         */
198
        public Object getLoadParams() {
199
                return params;
200
        }
201

    
202
        /*
203
         * (non-Javadoc)
204
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setName(java.lang.String)
205
         */
206
        public void setName(String name) {
207
                super.setName(name);
208

    
209
                //Si la capa tiene nombre acivamos el estado awake
210
                if(getLoadParams() != null && name != null) {
211
                        try {
212
                                enableAwake();
213
                        } catch (NotAvailableStateException e) {
214
                                Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
215
                        }
216
                }
217
        }
218

    
219
        /**
220
         * Redefine wakeUp de FLyrDefault
221
         */
222
        public void wakeUp(){
223
        }
224

    
225
        /**
226
         * Asignar el estado del raster
227
         * @param status
228
         */
229
        public void setStatus(IStatusRaster status){
230
                this.status = status;
231
        }
232

    
233
        /**
234
         * Obtiene el estado del raster
235
         * @return
236
         */
237
        public IStatusRaster getStatus(){
238
                return this.status;
239
        }
240

    
241
        /*
242
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
243
         */
244
        public void load() throws LoadLayerException {
245
                if(isStopped())
246
                        return;
247

    
248
                enableStopped(); //Paramos la capa mientras se hace un load
249

    
250
                String fName = null;
251
                int test = -1;
252
                if (params != null && params instanceof File) {
253
                        fName = ((File) params).getAbsolutePath();
254
                        test = fName.indexOf("ecwp:");
255
                }
256

    
257
                if (test != -1) {
258
                        String urlECW = fName.substring(test + 6);
259
                        fName = "ecwp://" + urlECW;
260
                        System.err.println(test + " " + fName);
261
                }
262

    
263
                try {
264
                        if(params instanceof String[][]) {
265
                                String[][] files = (String[][])params;
266
                                MultiRasterDataset[][] dt = new MultiRasterDataset[files.length][files[0].length];
267
                                for (int i = 0; i < files.length; i++)
268
                                        for (int j = 0; j < files[i].length; j++)
269
                                                dt[i][j] = MultiRasterDataset.open(getProjection(), files[i][j]);
270
                                dataset = new CompositeDataset(dt);
271
                        } else if (params == null || params instanceof File) {
272
                                if(fName != null)
273
                                        dataset = MultiRasterDataset.open(getProjection(), fName);
274
                        } else
275
                                dataset = MultiRasterDataset.open(getProjection(), params);
276
                } catch (NotSupportedExtensionException e) {
277
                        throw new LoadLayerException("Formato no valido", e);
278
                } catch (MosaicNotValidException e) {
279
                        throw new LoadLayerException("Error en el mosaico", e);
280
                } catch (Exception e) {
281
                        throw new LoadLayerException("No existe la capa.", e);
282
                }
283
                if(dataset != null)
284
                        this.init();
285
        }
286

    
287
        /**
288
         * Acciones de inicializaci?n despu?s de que la fuente de datos
289
         * de la capa est? asignada. El tipo de fuente de datos es variable
290
         * puede ser MultiRasterDataset, CompositeDataset u otras que existan e
291
         * implementen IRasterDatasource.
292
         */
293
        public void init() throws LoadLayerException {
294
                if (dataset == null)
295
                        throw new LoadLayerException("Formato no valido", new IOException());
296
                bufferFactory = new BufferFactory(dataset);
297
                render = new Rendering(bufferFactory);
298
                initFilters();
299

    
300
                //Inicializaci?n del historico de transformaciones
301
                affineTransformList.clear();
302
                affineTransformList.add(this.getAffineTransform());
303
                try {
304
                        enableOpen();
305
                } catch (NotAvailableStateException e) {
306
                        Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Awake=" + isAwake(), e);
307
                }
308
        }
309

    
310
        /**
311
         * Crea el objeto renderizador de raster
312
         * @return Rendering
313
         */
314
        public Rendering getRender() {
315
                if (render == null)
316
                        render = new Rendering(bufferFactory);
317
                return render;
318
        }
319
        
320
        /**
321
         * Aplica los filtros noData al layer
322
         * @param rasterSE
323
         * @param filterManager
324
         */
325
        public void applyNoData() {
326
                Boolean noDataEnabled = configuration.getValueBoolean("nodata_transparency_enabled", Boolean.FALSE);
327
                if (noDataEnabled.booleanValue()) {
328
                        Double noDataValue = Double.valueOf(getDataSource().getNoDataValue(0));
329
                        getDataSource().getTransparencyFilesStatus().setNoData(noDataValue.doubleValue());
330
                }
331
        }
332

    
333
        /**
334
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
335
         */
336
        private void initFilters() {
337
                RasterFilterList filterList = new RasterFilterList();
338
                filterList.addEnvParam("IStatistics", getDataSource().getStatistics());
339
                filterList.addEnvParam("MultiRasterDataset", getDataSource());
340
                
341
                applyNoData();
342
                GridTransparency gridTransparency = new GridTransparency(getDataSource().getTransparencyFilesStatus());
343

    
344
                filterList.setInitDataType(getDataType()[0]);
345
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
346

    
347
                try {
348
                        if (this.getDataSource().getColorTables()[0] != null) {
349
                                GridPalette p = new GridPalette(getDataSource().getColorTables()[0]);
350
                                setLastLegend(p);
351
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
352
                                ctm.addColorTableFilter(p);
353
                        } else {
354
                                if (getDataType()[0] != IBuffer.TYPE_BYTE) {
355
                                        loadEnhancedOrColorTable(filterManager);
356
                                }
357
                        }
358

    
359
                        getRender().setFilterList(filterList);
360
                        // Inicializo la transparencia para el render
361
                        getRender().setLastTransparency(gridTransparency);
362
                } catch (FilterTypeException e) {
363
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
364
                        RasterToolsUtil.debug("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
365
                }
366
        }
367

    
368
        /**
369
         * Mira la configuracion para saber si debe cargar un realce o una tabla
370
         * de color por defecto
371
         * @param filterManager
372
         * @throws FilterTypeException
373
         */
374
        private void loadEnhancedOrColorTable(RasterFilterListManager filterManager) throws FilterTypeException {
375
                String colorTableName = configuration.getValueString("loadlayer_usecolortable", (String) null);
376

    
377
                String palettesPath = System.getProperty("user.home") +
378
                        File.separator +
379
                        "gvSIG" + // PluginServices.getArguments()[0] +
380
                        File.separator + "colortable";
381

    
382
                IStatistics stats = getDataSource().getStatistics();
383

    
384
                if (colorTableName != null) {
385
                        try {
386
                                stats.calcFullStatistics();
387
                                if (getBandCount() == 1) {
388
                                        ArrayList fileList = ColorTableLibraryPersistence.getPaletteFileList(palettesPath);
389
                                        for (int i = 0; i < fileList.size(); i++) {
390
                                                ArrayList paletteItems = new ArrayList();
391
                                                String paletteName = ColorTableLibraryPersistence.loadPalette(palettesPath, (String) fileList.get(i), paletteItems);
392
                                                if (paletteName.equals(colorTableName)) {
393
                                                        if (paletteItems.size() <= 0)
394
                                                                continue;
395

    
396
                                                        ColorTable colorTable = new ColorTable();
397
                                                        colorTable.setName(paletteName);
398
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
399
                                                        colorTable.setInterpolated(true);
400

    
401
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
402

    
403
                                                        GridPalette p = new GridPalette(colorTable);
404
                                                        setLastLegend(p);
405

    
406
                                                        ColorTableListManager ctm = new ColorTableListManager(filterManager);
407
                                                        ctm.addColorTableFilter(p);
408
                                                        return;
409
                                                }
410
                                        }
411
                                }
412
                        } catch (FileNotOpenException e) {
413
                                // No podemos aplicar el filtro
414
                        } catch (RasterDriverException e) {
415
                                // No podemos aplicar el filtro
416
                        } catch (InterruptedException e) {
417
                                // El usuario ha cancelado el proceso
418
                        }
419
                }
420

    
421
                /*EnhancementListManager elm = new EnhancementListManager(filterManager);
422
                elm.addEnhancedFilter(false, stats, 0.0, getRender().getRenderBands());*/
423
                
424
                EnhancementStretchListManager elm = new EnhancementStretchListManager(filterManager);
425
                try {
426
                        elm.addEnhancedStretchFilter(LinearStretchParams.createStandardParam(getBandCount(), 0.0, stats, this.getDataType()[0]), 
427
                                                                                stats, 
428
                                                                                getRender().getRenderBands(), 
429
                                                                                true);
430
                } catch (FileNotOpenException e) {
431
                        //No podemos aplicar el filtro
432
                } catch (RasterDriverException e) {
433
                        //No podemos aplicar el filtro
434
                }
435
        }
436

    
437
        /**
438
         * @throws ReadDriverException
439
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
440
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
441
         *                 com.iver.utiles.swing.threads.Cancellable)
442
         */
443
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadDriverException {
444
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
445
                task.setEvent(null);
446

    
447
                try {
448
                        if (!isOpen())
449
                                return;
450

    
451
                        enableStopped();
452
                        // callLegendChanged(null);
453

    
454
                        strategy = new RasterDrawStrategy(getMapContext(), this);
455
                        strategy.stackStrategy();
456
                        HashMap tStr = strategy.getStrategy();
457
                        if (tStr != null && tStr.get(this) != null && ((Boolean) (tStr.get(this))).booleanValue() == false) {
458
                                disableStopped();
459
                                return;
460
                        }
461

    
462
                        if (isWithinScale(scale)) {
463
                                if (status != null && firstLoad) {
464
                                        if (mustTileDraw) {
465
                                                Point2D p = vp.getOffset();
466
                                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
467
                                                Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
468
                                                tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
469
                                                for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
470
                                                        // drawing part
471
                                                        try {
472
                                                                ViewPort vport = tiles.getTileViewPort(vp, tileNr);
473
//                                                                g.setClip(tiles.getClip(tileNr).x, tiles.getClip(tileNr).y, tiles.getClip(tileNr).width - 5, tiles.getClip(tileNr).height);
474
                                                                draw(image, g, vport, cancel);
475
                                                        } catch (RasterDriverException e) {
476
                                                                throw new ReadDriverException("", e);
477
                                                        } catch (InvalidSetViewException e) {
478
                                                                throw new ReadDriverException("Error al asignar la vista en el draw.", e);
479
                                                        } catch (InterruptedException e) {
480
                                                                System.out.println("Se ha cancelado el pintado");
481
//                                                                throw new ReadDriverException("Dibujado interrumpido.", e);
482
                                                        } catch (NoninvertibleTransformException e) {
483
                                                                throw new ReadDriverException("Error en la transformaci?n", e);
484
                                                        }
485
                                                }
486
                                        } else {
487
                                                try {
488
                                                        draw(image, g, vp, cancel);
489
                                                } catch (RasterDriverException e) {
490
                                                        throw new ReadDriverException("", e);
491
                                                } catch (InvalidSetViewException e) {
492
                                                        throw new ReadDriverException("Error al asignar la vista en el draw.", e);
493
                                                } catch (InterruptedException e) {
494
                                                        System.out.println("Se ha cancelado el pintado");
495
//                                                throw new ReadDriverException("Dibujado interrumpido.", e);
496
                                                }
497
                                        }
498
                                        try {
499
                                                status.applyStatus(this);
500
                                        } catch (NotSupportedExtensionException e) {
501
                                                throw new ReadDriverException("Error setting filters from a project.", e);
502
                                        } catch (RasterDriverException e) {
503
                                                throw new ReadDriverException("Error reading file from a project.", e);
504
                                        } catch (FilterTypeException e) {
505
                                                throw new ReadDriverException("Error adding filters.", e);
506
                                        }
507
                                        firstLoad = false;
508
                                }
509

    
510
                                if (mustTileDraw) {
511
                                        Point2D p = vp.getOffset();
512
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
513
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
514
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
515
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
516
                                                // drawing part
517
                                                try {
518
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
519
                                                        draw(image, g, vport, cancel);
520
                                                } catch (RasterDriverException e) {
521
                                                        throw new ReadDriverException("", e);
522
                                                } catch (InvalidSetViewException e) {
523
                                                        throw new ReadDriverException("Error al asignar la vista en el draw.", e);
524
                                                } catch (InterruptedException e) {
525
                                                        System.out.println("Se ha cancelado el pintado");
526
//                                                        throw new ReadDriverException("Dibujado interrumpido.", e);
527
                                                } catch (NoninvertibleTransformException e) {
528
                                                        throw new ReadDriverException("Error en la transformaci?n", e);
529
                                                }
530
                                        }
531
                                } else {
532
                                        try {
533
                                                draw(image, g, vp, cancel);
534
                                        } catch (RasterDriverException e) {
535
                                                throw new ReadDriverException("", e);
536
                                        } catch (InvalidSetViewException e) {
537
                                                throw new ReadDriverException("Error al asignar la vista en el draw.", e);
538
                                        } catch (InterruptedException e) {
539
                                                System.out.println("Se ha cancelado el pintado");
540
//                                        throw new ReadDriverException("Dibujado interrumpido.", e);
541
                                        }
542
                                }
543

    
544
                                if (getVirtualLayers() != null) {
545
                                        getVirtualLayers().draw(image, g, vp, cancel, scale);
546
                                }
547
                        }
548
                        //callLegendChanged(null);
549
                } finally {
550
                        disableStopped();
551
                        task.setEvent(null);
552
                }
553
        }
554

    
555
        private void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws RasterDriverException, InvalidSetViewException, InterruptedException {
556
                Extent e = new Extent(vp.getAdjustedExtent());
557
                Dimension imgSz = vp.getImageSize();
558
                ViewPortData vp2 = new ViewPortData(vp.getProjection(), e, imgSz );
559
                vp2.setMat(vp.getAffineTransform());
560
                getRender().draw(g, vp2);
561
        }
562

    
563
        /**
564
         * Inserta la proyecci?n.
565
         *
566
         * @param proj Proyecci?n.
567
         */
568
        public void setProjection(IProjection proj) {
569
                super.setProjection(proj);
570
        }
571

    
572
        /*
573
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
574
         */
575
        public Rectangle2D getFullExtent() {
576
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
577
                //un extent aunque la capa no est? abierta
578
                if(/*!isOpen() || */dataset == null || dataset.getExtent() == null)
579
                        return null;
580
                return dataset.getExtent().toRectangle2D();
581
        }
582

    
583
        /**
584
         * Obtiene el valor del pixel del Image en la posici?n real x,y
585
         * @param x Posici?n x
586
         * @param y Posici?n y
587
         * @return valor de pixel
588
         */
589
        public int[] getPixel(double wcx, double wcy) {
590
                if (!isOpen())
591
                        return null;
592

    
593
                int[] argb = { -1, -1, -1, -1 };
594
                if (wcx <= getMaxX() && wcx >= getMinX() && wcy <= getMaxY() && wcy >= getMinY()) {
595
                        View theView = (View) PluginServices.getMDIManager().getActiveWindow();
596
                        if (theView instanceof IView) {
597
                                // BufferedImage buf = ((IView) theView).getMapControl().getImage();
598
                                Point2D p = ((IView) theView).getMapControl().getViewPort().fromMapPoint(wcx, wcy);
599
                                return getPixel((int) p.getX(), (int) p.getY());
600
                        }
601
                }
602
                return argb;
603
        }
604

    
605
        /**
606
         * Obtiene el valor del pixel del Image en la posici?n x,y
607
         * @param x Posici?n x
608
         * @param y Posici?n y
609
         * @return valor de pixel
610
         */
611
        public int[] getPixel(int pxx, int pxy) {
612
                if (!isOpen())
613
                        return null;
614
                //TODO: Esto hay que rehacerlo ya que es dependiente de la vista
615
                int[] argb = { -1, -1, -1, -1 };
616
                View theView = (View) PluginServices.getMDIManager().getActiveWindow();
617
                BufferedImage buf = null;
618
                if (theView instanceof IView)
619
                        buf = ((IView) theView).getMapControl().getImage();
620
                if (pxx >= 0 && pxx < buf.getWidth() && pxy >= 0 && pxy < buf.getHeight()) {
621
                        if (theView instanceof IView) {
622
                                int value = buf.getRGB(pxx, pxy);
623
                                argb[0] = ((value & 0xff000000) >> 24);
624
                                argb[1] = ((value & 0x00ff0000) >> 16);
625
                                argb[2] = ((value & 0x0000ff00) >> 8);
626
                                argb[3] = (value & 0x000000ff);
627
                        }
628
                }
629
                return argb;
630
        }
631

    
632
        /*
633
         * (non-Javadoc)
634
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
635
         */
636
        public double getMaxX() {
637
                if(getFullExtent() != null)
638
                        return getFullExtent().getMaxX();
639
                return -1;
640
        }
641

    
642
        /*
643
         * (non-Javadoc)
644
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
645
         */
646
        public double getMaxY() {
647
                if(getFullExtent() != null)
648
                        return this.getFullExtent().getMaxY();
649
                return -1;
650
        }
651

    
652
        /*
653
         * (non-Javadoc)
654
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinX()
655
         */
656
        public double getMinX() {
657
                if(getFullExtent() != null)
658
                        return getFullExtent().getMinX();
659
                return -1;
660
        }
661

    
662
        /*
663
         * (non-Javadoc)
664
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinY()
665
         */
666
        public double getMinY() {
667
                if(getFullExtent() != null)
668
                        return getFullExtent().getMinY();
669
                return -1;
670
        }
671

    
672
        /* (non-Javadoc)
673
         * @deprecated. See String getInfo(Point p) throws DriverException
674
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
675
         */
676
        public String queryByPoint(Point p) {
677
                if (!isOpen())
678
                        return null;
679
                ColorConversion conv = new ColorConversion();
680

    
681
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
682

    
683
                ArrayList attr = getAttributes();
684
                data += "  <raster\n";
685
                data += "    File=\"" + getFile() + "\"\n";
686
                for (int i = 0; i < attr.size(); i++) {
687
                        Object[] a = (Object[]) attr.get(i);
688

    
689
                        data += "    " + a[0].toString() + "=";
690
                        if (a[1].toString() instanceof String)
691
                                data += "\"" + a[1].toString() + "\"\n";
692
                        else
693
                                data += a[1].toString() + "\n";
694
                }
695
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
696
                data += "    Point_WC=\"" + MathUtils.format(posXWC, 3) + " , " + MathUtils.format(posYWC, 3) + "\"\n";
697
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
698
                double[] cmyk = conv.RGBtoCMYK(r & 0xff, g & 0xff, b & 0xff, 1D);
699
                data += "    CMYK=\"" + MathUtils.format(cmyk[0], 4) + ", " + MathUtils.format(cmyk[1], 4) + ", " + MathUtils.format(cmyk[2], 4) + "," + MathUtils.format(cmyk[3], 4) + "\"\n";
700
                double[] hsl = conv.RGBtoHSL(r & 0xff, g & 0xff, b & 0xff);
701
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
702
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
703
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
704
                data += "    HSL=\"" + MathUtils.format(hsl[0], 4) + ", " + MathUtils.format(hsl[1], 4) + ", " + MathUtils.format(hsl[2], 4) + "\"\n";
705
                data += "  />\n";
706

    
707
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
708
                return data;
709
        }
710

    
711
        /*
712
         * (non-Javadoc)
713
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo(java.awt.Point, double, com.iver.utiles.swing.threads.Cancellable)
714
         */
715
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException {
716
                if (!isOpen()) {
717
                        StringXMLItem[] item = new StringXMLItem[1];
718
                        String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
719
                        data += "  <raster\n" + "  Layer=\" Not available\"\n" + "  />\n";
720
                        data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
721
                        item[0] = new StringXMLItem(data, this);
722
                        return item;
723
                }
724

    
725
                Point2D pReal = getMapContext().getViewPort().toMapPoint(p);
726
                Point2D px = new Point2D.Double();
727
                if(        pReal.getX() > this.getMinX() &&
728
                        pReal.getX() < this.getMaxX() &&
729
                        pReal.getY() > this.getMinY() &&
730
                        pReal.getY() < this.getMaxY()) {
731

    
732
                        AffineTransform at = this.getDataSource().getAffineTransform();
733
                        px = new Point2D.Double(pReal.getX(), pReal.getY());
734
                        try {
735
                                at.inverseTransform(px, px);
736
                        } catch (NoninvertibleTransformException e) {
737
                                throw new ReadDriverException("Error en la transformaci?n del punto", e);
738
                        }
739
                }
740
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
741
                ColorConversion conv = new ColorConversion();
742

    
743
                StringXMLItem[] item = new StringXMLItem[1];
744
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
745

    
746
                data += "  <raster\n";
747
                data += "    View_Point=\"" + p.getX() + " , " + p.getY() + "\"\n";
748
                data += "    World_Point=\"" + MathUtils.format(pReal.getX(), 3) + " , " + MathUtils.format(pReal.getY(), 3) + "\"\n";
749
                if (px == null)
750
                        data += "    Pixel_Point=\"Out\"\n";
751
                else
752
                        data += "    Pixel_Point=\"" + (int) px.getX() + " , " + (int) px.getY() + "\"\n";
753
                data += "    RGB=\"" + rgb[1] + "  " + rgb[2] + "  " + rgb[3] + "\"\n";
754
                double[] cmyk = conv.RGBtoCMYK(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff, 1D);
755
                data += "    CMYK=\"" + MathUtils.format(cmyk[0], 4) + ", " + MathUtils.format(cmyk[1], 4) + ", " + MathUtils.format(cmyk[2], 4) + "," + MathUtils.format(cmyk[3], 4) + "\"\n";
756
                double[] hsl = conv.RGBtoHSL(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff);
757
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
758
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
759
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
760
                data += "    HSL=\"" + MathUtils.format(hsl[0], 4) + ", " + MathUtils.format(hsl[1], 4) + ", " + MathUtils.format(hsl[2], 4) + "\"\n";
761
                data += "    Band_Value=\"";
762
                try {
763
                        if (px != null) {
764
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3){
765
                                        for(int i = 0; i < getBandCount(); i++)
766
                                                data += ((Integer)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).intValue() + "  ";
767
                                }
768
                                if(getDataType()[0] == 4){
769
                                        for(int i = 0; i < getBandCount(); i++)
770
                                                data += ((Float)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).floatValue() + "  ";
771
                                }
772
                                if(getDataType()[0] == 5){
773
                                        for(int i = 0; i < getBandCount(); i++)
774
                                                data += ((Double)getDataSource().getData((int)px.getX(), (int)px.getY(), i)).doubleValue() + "  ";
775
                                }
776
                        }
777
                } catch (RasterDriverException ex) {
778
                        throw new ReadDriverException("Error en el acceso al dataset", ex);
779
                } catch (InvalidSetViewException ex) {
780
                        throw new ReadDriverException("Error en la asignaci?n de la vista en getData", ex);
781
                } catch (FileNotOpenException ex) {
782
                        throw new ReadDriverException("Fichero no abierto en el dataset", ex);
783
                }
784
                data += "\"\n";
785
                data += "  />\n";
786
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
787

    
788
                item[0] = new StringXMLItem(data, this);
789
                return item;
790
        }
791

    
792
        /**
793
         * Filters a string for being suitable as XML Tag, erasing
794
         * all not alphabetic or numeric characters.
795
         * @param s
796
         * @return string normalized
797
         */
798
        private String normalizeAsXMLTag(String s) {
799
                return s.replaceAll("[^a-zA-Z0-9]", "");
800
        }
801

    
802
        /**
803
         * Obtiene atributos a partir de un georasterfile
804
         * @return
805
         */
806
        public ArrayList getAttributes() {
807
                ArrayList attr = new ArrayList();
808
                if(!isOpen())
809
                        return attr;
810
                Object [][] a = {
811
                        {"Filename", dataset.getDataset(0)[0].getFName()},
812
                        {"Filesize", new Long(dataset.getFileSize())},
813
                        {"Width", new Integer((int)dataset.getWidth())},
814
                        {"Height", new Integer((int)dataset.getHeight())},
815
                        {"Bands", new Integer(dataset.getBandCount())}
816
                };
817
                for (int i = 0; i < a.length; i++)
818
                        attr.add(a[i]);
819
                return attr;
820
        }
821

    
822
        /**
823
         * Escribe en el proyecto la capa actual
824
         * @throws XMLException
825
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
826
         */
827
        public XMLEntity getXMLEntity() throws XMLException {
828
                if(isClosed() || isAwake())
829
                        return null;
830

    
831
                XMLEntity xml = super.getXMLEntity();
832
                if(getFile() != null)
833
                        xml.putProperty("file", getFile());
834
                xml.putProperty("driverName", "gvSIG Raster Driver");
835

    
836
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
837
                if (status == null)
838
                        status = new StatusLayerRaster();
839
                status.getXMLEntity(xml, true, this);
840

    
841
                return xml;
842
        }
843

    
844
        public void setXMLEntity03(XMLEntity xml) throws XMLException {
845
        }
846

    
847
        /**
848
         * Recupera de disco los datos de la capa.
849
         */
850
        public void setXMLEntity(XMLEntity xml) throws XMLException {
851
                super.setXMLEntity(xml);
852

    
853
                try {
854
                        params = new File(xml.getStringProperty("file"));
855

    
856
                        if(params != null && getName() != null && getName().compareTo("") != 0) {
857
                                try {
858
                                        enableAwake();
859
                                } catch (NotAvailableStateException e) {
860
                                        Logger.getLogger(getClass().getName()).debug("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), e);
861
                                }
862
                        }
863
                        if(!super.getFLayerStatus().visible)
864
                                enableStopped();
865

    
866
                        // Para notificar al adapter-driver cual es la proyecci?n.
867
                        setProjection(super.getProjection());
868

    
869
                        //Inicializamos la clase a la que se usa por defecto para
870
                        //compatibilidad con proyectos antiguos
871
                        String claseStr = StatusLayerRaster.defaultClass;
872
                        if (xml.contains("raster.class"))
873
                                claseStr = xml.getStringProperty("raster.class");
874

    
875
                        if (status != null)
876
                                status.setXMLEntity(xml, this);
877
                        else {
878
                                // Cuando cargamos un proyecto
879

    
880
                                if (claseStr != null && !claseStr.equals("")) {
881
                                        try {
882
                                                Class clase = LayerFactory.getLayerClassForLayerClassName(claseStr);
883
                                                Constructor constr = clase.getConstructor(null);
884
                                                status = (IStatusRaster) constr.newInstance(null);
885
                                                if (status != null) {
886
                                                        ((StatusLayerRaster)status).setNameClass(claseStr);
887
                                                        status.setXMLEntity(xml, this);
888
                                                        filterArguments = status.getFilterArguments();
889
                                                        crearColorTable();
890
                                                }
891
                                        } catch (ClassNotFoundException exc) {
892
                                                throw new XMLException(exc);
893
                                        } catch (InstantiationException exc) {
894
                                                throw new XMLException(exc);
895
                                        } catch (IllegalAccessException exc) {
896
                                                throw new XMLException(exc);
897
                                        } catch (NoSuchMethodException exc) {
898
                                                throw new XMLException(exc);
899
                                        } catch (InvocationTargetException exc) {
900
                                                throw new XMLException(exc);
901
                                        }
902
                                }
903
                        }
904
                        firstLoad = true;
905
                } catch (NotExistInXMLEntity e) {
906

    
907
                }
908
        }
909

    
910
        private void crearColorTable() {
911
                ArrayList color = (ArrayList) filterArguments.clone();
912
                setLastLegend(ColorTableListManager.createColorTableFromArray(color));
913
        }
914

    
915
        /* (non-Javadoc)
916
         * @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)
917
         */
918
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet propeties) throws ReadDriverException {
919

    
920
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
921
                        return;
922

    
923
                isPrinting = true;
924
                if (!mustTilePrint) {
925
                        draw(null, g, viewPort, cancel,scale);
926
                } else {
927
                        // Para no pedir imagenes demasiado grandes, vamos
928
                        // a hacer lo mismo que hace EcwFile: chunkear.
929
                        // Llamamos a drawView con cuadraditos m?s peque?os
930
                        // del BufferedImage ni caso, cuando se imprime viene con null
931
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
932
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
933

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

    
937
                        //RasterStats stats = getSource().getFilterStack().getStats();
938
                        //if(stats != null)
939
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
940

    
941

    
942
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
943
                                // Parte que dibuja
944
                                try {
945
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
946
                                        draw(null, g, vp, cancel, scale);
947
                                } catch (NoninvertibleTransformException e) {
948
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
949
                                }
950
                        }
951
                        /*if(stats != null){
952
                                getSource().getFilterStack().getStats().history.clear();
953
                                stats = getSource().getFilterStack().getStats();
954
                        }*/
955
                }
956
                isPrinting = false;
957
        }
958

    
959
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale) throws ReadDriverException {
960
                if(!isOpen())
961
                        return;
962

    
963
                // Para no pedir imagenes demasiado grandes, vamos
964
                // a hacer lo mismo que hace EcwFile: chunkear.
965
                // Llamamos a drawView con cuadraditos m?s peque?os
966
                // del BufferedImage ni caso, cuando se imprime viene con null
967

    
968
                int numW, numH;
969
                int stepX, stepY;
970
                int xProv, yProv;
971
                int A = 1500;
972
                int H = 1500;
973
                int altoAux, anchoAux;
974

    
975
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
976

    
977
                // Vamos a hacerlo en trozos de AxH
978
                Rectangle r = g.getClipBounds();
979
                numW = (int) (r.width) / A;
980
                numH = (int) (r.height) / H;
981

    
982
                double[] srcPts = new double[8];
983
                double[] dstPts = new double[8];
984

    
985
                yProv = (int) r.y;
986
                for (stepY = 0; stepY < numH + 1; stepY++) {
987
                        if ((yProv + H) > r.getMaxY())
988
                                altoAux = (int) r.getMaxY() - yProv;
989
                        else
990
                                altoAux = H;
991

    
992
                        xProv = (int) r.x;
993
                        for (stepX = 0; stepX < numW + 1; stepX++) {
994
                                if ((xProv + A) > r.getMaxX())
995
                                        anchoAux = (int) r.getMaxX() - xProv;
996
                                else
997
                                        anchoAux = A;
998

    
999
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
1000

    
1001
                                // Parte que dibuja
1002
                                srcPts[0] = xProv;
1003
                                srcPts[1] = yProv;
1004
                                srcPts[2] = xProv + anchoAux + 1;
1005
                                srcPts[3] = yProv;
1006
                                srcPts[4] = xProv + anchoAux + 1;
1007
                                srcPts[5] = yProv + altoAux + 1;
1008
                                srcPts[6] = xProv;
1009
                                srcPts[7] = yProv + altoAux + 1;
1010

    
1011
                                try {
1012
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
1013
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
1014
                                        // Extent extent = new Extent(rectCuadricula);
1015

    
1016
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
1017
                                        ViewPort vp = viewPort.cloneViewPort();
1018
                                        vp.setImageSize(tam);
1019
                                        vp.setExtent(rectCuadricula);
1020
                                        vp.setAffineTransform(mat);
1021
                                        draw(null, g, vp, cancel, scale);
1022

    
1023
                                } catch (NoninvertibleTransformException e) {
1024
                                        throw new ReadDriverException("Error en la transformaci?n.", e);
1025
                                }
1026
                                // Fin parte que dibuja
1027
                                xProv = xProv + A;
1028
                        }
1029
                        yProv = yProv + H;
1030
                }
1031
        }
1032

    
1033
        /**
1034
         * Borra de la lista de listeners el que se pasa como par?metro.
1035
         *
1036
         * @param o LayerListener a borrar.
1037
         *
1038
         * @return True si ha sido correcto el borrado del Listener.
1039
         */
1040
        public boolean removeLayerListener(LayerListener o) {
1041
                //Salva a RMF
1042
                try {
1043
                        if(this.getDataSource() != null)
1044
                                this.getDataSource().saveRmfModification();
1045
                } catch (IOException e) {
1046
                        //No se ha salvado nada
1047
                }
1048

    
1049
                if (this.isRemoveRasterFlag()) {
1050
                        if(dataset != null)
1051
                                dataset.close();
1052
                        if(bufferFactory != null)
1053
                                bufferFactory.free();
1054
                        bufferFactory = null;
1055
                        dataset = null;
1056
                        render = null;
1057
                        System.gc();
1058
                        this.setRemoveRasterFlag(true);
1059
                }
1060
                return super.layerListeners.remove(o);
1061
        }
1062

    
1063
        /**
1064
         * @return Returns the removeRasterFlag.
1065
         */
1066
        public boolean isRemoveRasterFlag() {
1067
                return removeRasterFlag;
1068
        }
1069

    
1070
        /**
1071
         * Asigna el valor del flag que dice si destruimos la memoria del raster
1072
         * al eliminarlo del TOC o  no.
1073
         * @param removeRasterFlag The removeRasterFlag to set.
1074
         */
1075
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1076
                this.removeRasterFlag = removeRasterFlag;
1077
        }
1078

    
1079
        /*
1080
         * (non-Javadoc)
1081
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1082
         */
1083
        public ImageIcon getTocImageIcon() {
1084
                /*if(!isOpen())
1085
                        return new ImageIcon(MapControl.class.getResource("images/map_ico_ko.gif"));*/
1086
                return PluginServices.getIconTheme().get("map-ok-ico");
1087
        }
1088

    
1089
        /*
1090
         *  (non-Javadoc)
1091
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1092
         */
1093
        public int[] getTileSize() {
1094
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1095
                return size;
1096
        }
1097

    
1098
        /*
1099
         *  (non-Javadoc)
1100
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1101
         */
1102
        public boolean isTiled() {
1103
                return mustTileDraw;
1104
        }
1105

    
1106
        /**
1107
         * Obtiene el flag que dice si la imagen est? o no georreferenciada
1108
         * @return true si est? georreferenciada y false si no lo est?.
1109
         */
1110
        public boolean isGeoreferenced() {
1111
                return dataset.isGeoreferenced();
1112
        }
1113

    
1114
        /**
1115
         * Get datasource object
1116
         * @return
1117
         */
1118
        public BufferFactory getBufferFactory(){
1119
                return bufferFactory;
1120
        }
1121

    
1122
        /**
1123
         * Obtiene el valor NoData asociado al raster.
1124
         * @return double
1125
         */
1126
        public double getNoDataValue() {
1127
                return dataset.getNoDataValue(0);
1128
        }
1129

    
1130
        /**
1131
         * Obtiene el valor NoData asociado al raster.
1132
         * @return double
1133
         */
1134
        public double getNoDataValue(int n) {
1135
                return dataset.getNoDataValue(n);
1136
        }
1137

    
1138
        /**
1139
         * Asigna el valor no data asociado a la capa
1140
         * @param nd
1141
         */
1142
        public void setNoDataValue(double nd) {
1143
                if (bufferFactory != null)
1144
                        bufferFactory.setNoDataToFill(nd);
1145
                dataset.setNoDataValue(0, nd);
1146
        }
1147

    
1148
        /*
1149
         * (non-Javadoc)
1150
         * @see org.gvsig.fmap.raster.IRasterOperations#getPXHeight()
1151
         */
1152
        public double getPxHeight() {
1153
                return dataset.getHeight();
1154
        }
1155

    
1156
        /*
1157
         * (non-Javadoc)
1158
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
1159
         */
1160
        public double getPxWidth() {
1161
                return dataset.getWidth();
1162
        }
1163

    
1164
        /*
1165
         * (non-Javadoc)
1166
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCHeight()
1167
         */
1168
        public double getWCHeight() {
1169
                return getFullExtent().getHeight();
1170
        }
1171

    
1172
        /*
1173
         * (non-Javadoc)
1174
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
1175
         */
1176
        public double getWCWidth() {
1177
                return getFullExtent().getWidth();
1178
        }
1179

    
1180
        /*
1181
         * (non-Javadoc)
1182
         * @see org.gvsig.fmap.raster.IRasterFile#getFileSize()
1183
         */
1184
        public long[] getFileSize(){
1185
                int nFiles = dataset.getDatasetCount();
1186
                long[] s = new long[nFiles];
1187
                for (int i = 0; i < nFiles; i++)
1188
                        s[i] = dataset.getFileSize();
1189
                return s;
1190
        }
1191

    
1192
        /*
1193
         * (non-Javadoc)
1194
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
1195
         */
1196
        public String[] getFileName(){
1197
                int nFiles = dataset.getDatasetCount();
1198
                String[] s = new String[nFiles];
1199
                for (int i = 0; i < nFiles; i++)
1200
                        s[i] = dataset.getDataset(i)[0].getFName();
1201
                return s;
1202
        }
1203

    
1204
        /*
1205
         * (non-Javadoc)
1206
         * @see org.gvsig.fmap.raster.IRasterFile#getFileCount()
1207
         */
1208
        public int getFileCount() {
1209
                return (dataset != null) ? dataset.getDatasetCount() : 0;
1210
        }
1211

    
1212
        /*
1213
         * (non-Javadoc)
1214
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
1215
         */
1216
        public String getFileFormat() {
1217
                String fName = dataset.getDataset(0)[0].getFName();
1218
                int index = fName.lastIndexOf(".") + 1;
1219
                String ext = null;
1220
                if (index > 0)
1221
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1222
                return ext;
1223
        }
1224

    
1225
        /*
1226
         * (non-Javadoc)
1227
         * @see org.gvsig.fmap.raster.IRasterOperations#getBandCount()
1228
         */
1229
        public int getBandCount() {
1230
                return (dataset != null) ? dataset.getBandCount() : 0;
1231
        }
1232

    
1233
        /*
1234
         * (non-Javadoc)
1235
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1236
         */
1237
        public int[] getDataType() {
1238
                return dataset.getDataType();
1239
        }
1240

    
1241
        /*
1242
         * (non-Javadoc)
1243
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
1244
         */
1245
        public GridTransparency getRenderTransparency() {
1246
                return getRender().getLastTransparency();
1247
        }
1248

    
1249
        /*
1250
         * (non-Javadoc)
1251
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1252
         */
1253
        public RasterFilterList getRenderFilterList() {
1254
                return getRender().getFilterList();
1255
        }
1256

    
1257
        /*
1258
         * (non-Javadoc)
1259
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
1260
         */
1261
        public int[] getRenderBands() {
1262
                return getRender().getRenderBands();
1263
        }
1264

    
1265
        /*
1266
         * (non-Javadoc)
1267
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
1268
         */
1269
        public void setRenderBands(int[] renderBands) {
1270
                getRender().setRenderBands(renderBands);
1271
        }
1272

    
1273
        /*
1274
         * (non-Javadoc)
1275
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
1276
         */
1277
        public void setRenderFilterList(RasterFilterList filterList) {
1278
                getRender().setFilterList(filterList);
1279
        }
1280

    
1281
        /*
1282
         * (non-Javadoc)
1283
         * @see org.gvsig.raster.hierarchy.IRasterDataset#getDataSource()
1284
         */
1285
        public IRasterDataSource getDataSource() {
1286
                return dataset;
1287
        }
1288

    
1289
        /*
1290
         * (non-Javadoc)
1291
         * @see org.gvsig.fmap.raster.IRasterDataset#addFile(java.lang.String)
1292
         */
1293
        public void addFile(String fileName) throws NotSupportedExtensionException, RasterDriverException {
1294
                if (getRender() != null)
1295
                        bufferFactory.addFile(RasterDataset.open(getProjection(), fileName));
1296
        }
1297

    
1298
        /*
1299
         * (non-Javadoc)
1300
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
1301
         */
1302
        public void delFile(String fileName) {
1303
                if (getRender() != null)
1304
                        bufferFactory.removeFile(fileName);
1305
        }
1306

    
1307
        /*
1308
         * (non-Javadoc)
1309
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1310
         */
1311
        public Object getInfo(String key) {
1312
                if (key.equals("DriverName"))
1313
                        return "gvSIG Raster Driver";
1314
                return null;
1315
        }
1316

    
1317
        /*
1318
         * (non-Javadoc)
1319
         * @see org.gvsig.raster.shared.IRasterOperations#getMetadata()
1320
         */
1321
        public DatasetMetadata[] getMetadata() {
1322
                int count = dataset.getDatasetCount();
1323
                DatasetMetadata[] metadata = new DatasetMetadata[count];
1324
                for (int i = 0; i < count; i++) {
1325
                        metadata[i] = dataset.getDataset(i)[0].getMetadata();
1326
                }
1327
                return metadata;
1328
        }
1329

    
1330
        /*
1331
         * (non-Javadoc)
1332
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
1333
         */
1334
        public int[] getBandCountFromDataset() {
1335
                int count = dataset.getDatasetCount();
1336
                int[] bands = new int[count];
1337
                for (int i = 0; i < count; i++)
1338
                        bands[i] = dataset.getDataset(i)[0].getBandCount();
1339
                return bands;
1340
        }
1341

    
1342
        /*
1343
         * (non-Javadoc)
1344
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1345
         */
1346
        public String getColourInterpretation(int band, int dataset) {
1347
                if (this.dataset.getColorInterpretation(dataset) == null)
1348
                        return "Undefined";
1349
                return this.dataset.getColorInterpretation(dataset).get(band);
1350
        }
1351

    
1352
        /*
1353
         * (non-Javadoc)
1354
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
1355
         */
1356
        public String getWktProjection() throws RasterDriverException {
1357
                return dataset.getWktProjection();
1358
        }
1359

    
1360
        /**
1361
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1362
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1363
         * cacheado o no dependiendo del tama?o de esta.
1364
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1365
         * @return Grid.
1366
         * @throws InterruptedException
1367
         */
1368
        public Grid getFullGrid(boolean interpolated) throws GridException, InterruptedException {
1369
                BufferFactory bf = getBufferFactory();
1370
                bf.clearDrawableBand();
1371
                bf.setAllDrawableBands();
1372
                try {
1373
                        bf.setAreaOfInterest();
1374
                } catch (RasterDriverException e) {
1375
                        throw new GridException("Error reading buffer");
1376
                }
1377
                return new Grid(bf, interpolated);
1378
        }
1379
        
1380
        /**
1381
         * Obtiene el tama?o de celda de la fuente de datos
1382
         * @return double con el tama?o de celda
1383
         */
1384
        public double getCellSize() {
1385
                return (getDataSource() != null) ? getDataSource().getCellSize() : 1;
1386
        }
1387
        
1388
        /*
1389
         * (non-Javadoc)
1390
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1391
         */
1392
        public Extent getFullRasterExtent() {
1393
                return this.getDataSource().getExtent();
1394
        }
1395

    
1396

    
1397
        /**
1398
         * Devuelve el fichero asociado a la capa o null si no tiene.
1399
         * @return Fichero.
1400
         */
1401
        public File getFile() {
1402
                return (params instanceof File) ? ((File)params) : null;
1403
        }
1404

    
1405
        /**
1406
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1407
         * @param file Fichero a consultar
1408
         * @return true si es aceptado y false si no lo es.
1409
         */
1410
        public static boolean isFileAccepted(File file) {
1411
                return RasterDataset.fileIsSupported(file.getName());
1412
        }
1413

    
1414
        /*
1415
         * (non-Javadoc)
1416
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1417
         */
1418
        public boolean existColorTable() {
1419
                return getRender().existColorTable();
1420
        }
1421

    
1422
        /**
1423
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1424
         * capa busque una leyenda valida.
1425
         * @param ct
1426
         */
1427
        public void setLastLegend(ColorTable ct) {
1428
                lastLegend = ColorTableLegend.createLegend(ct);
1429
        }
1430

    
1431
        /**
1432
         * Devuelve la Leyenda de la capa.
1433
         * @return Leyenda.
1434
         */
1435
        public ILegend getLegend() {
1436
                if (lastLegend != null)
1437
                        return lastLegend;
1438

    
1439
                return null;
1440
        }
1441

    
1442
        /*
1443
         * (non-Javadoc)
1444
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1445
         */
1446
        public void addLegendListener(LegendListener listener) {
1447
                layerChangeSupport.addLayerListener(listener);
1448
        }
1449

    
1450
        /*
1451
         *  (non-Javadoc)
1452
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1453
         */
1454
        public int getShapeType() throws ReadDriverException {
1455
                return FShape.POLYGON;
1456
        }
1457

    
1458
        /*
1459
         * (non-Javadoc)
1460
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1461
         */
1462
        public void removeLegendListener(LegendListener listener) {
1463
                layerChangeSupport.removeLayerListener(listener);
1464
        }
1465

    
1466
        /**
1467
         * Metodo que obtiene si un punto cae dentro de los l?mites de la capa
1468
         * o fuera de ellos.
1469
         * @param p Punto a calcular
1470
         * @return true si est? dentro de los l?mites y false si est? fuera
1471
         */
1472
        public boolean isInside(Point2D p) {
1473
                 return getDataSource().isInside(p);
1474
        }
1475

    
1476
        /**
1477
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1478
         * @return AffineTransform
1479
         */
1480
        public AffineTransform getAffineTransform() {
1481
                return getDataSource().getAffineTransform();
1482
        }
1483

    
1484
        /**
1485
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista
1486
         * @param transf
1487
         */
1488
        public void setAffineTransform(AffineTransform transf) {
1489
                affineTransformList.add(transf);
1490
                getDataSource().setAffineTransform(transf);
1491
        }
1492

    
1493
        /**
1494
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista.
1495
         * Esta versi?n no guarda en el historico.
1496
         * @param transf
1497
         */
1498
        public void setAT(AffineTransform transf) {
1499
                getDataSource().setAffineTransform(transf);
1500
        }
1501

    
1502
        /**
1503
         * Obtiene la lista de transformaciones que se han ido aplicando al raster.
1504
         * @return Historical. Lista de AffineTransform
1505
         */
1506
        public Historical getAffineTransformHistorical() {
1507
                return this.affineTransformList;
1508
        }
1509

    
1510
        /**
1511
         * Salva la georreferenciaci?n a fichero rmf.
1512
         * @param fName
1513
         * @throws IOException
1514
         */
1515
        public void saveGeoToRmf() throws IOException {
1516
                if(!isOpen())
1517
                        return;
1518
                getDataSource().saveGeoToRmf();
1519
                affineTransformList.clear();
1520
                affineTransformList.add(this.getAffineTransform());
1521
        }
1522

    
1523
        /*
1524
         * (non-Javadoc)
1525
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1526
         */
1527
        public boolean isActionEnabled(int action) {
1528
                switch (action) {
1529
                        case IRasterLayerActions.BANDS_FILE_LIST:
1530
                                if (existColorTable())
1531
                                        return false;
1532
                                break;
1533
                        case IRasterLayerActions.BANDS_RGB:
1534
                                if (existColorTable())
1535
                                        return false;
1536
                                break;
1537
                        case IRasterLayerActions.CREATEOVERVIEWS:
1538
                                if (getDataSource().overviewsSupport())
1539
                                        return true;
1540
                                else
1541
                                        return false;
1542
                        case IRasterLayerActions.OPACITY:
1543
                        case IRasterLayerActions.TRANSPARENCY:
1544
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1545
                        case IRasterLayerActions.ENHANCED:
1546
                        case IRasterLayerActions.PANSHARPENING:
1547
                                return true;
1548
                }
1549
                return true;
1550
        }
1551

    
1552
        /*
1553
         * (non-Javadoc)
1554
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1555
         */
1556
        public void setVisible(boolean visibility) {
1557
                if(visibility)
1558
                        state.disableStopped();
1559
                else
1560
                        enableStopped();
1561

    
1562
                if(isAwake() || isClosed())
1563
                        try {
1564
                                this.load();
1565
                        } catch (LoadLayerException e) {
1566
                                e.printStackTrace();
1567
                        }
1568
                super.setVisible(visibility);
1569
        }
1570

    
1571
        /**
1572
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1573
         * @return valor de transparencia
1574
         */
1575
        public int getTransparency() {
1576
                try {
1577
                        return getRenderTransparency().getOpacity();
1578
                } catch (NullPointerException e) {
1579
                        return super.getTransparency();
1580
                }
1581
        }
1582

    
1583
        /**
1584
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1585
         * o no.
1586
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1587
         */
1588
        public boolean isTransparent() {
1589
                return getRenderTransparency().isTransparencyActive();
1590
        }
1591

    
1592
        /**
1593
         * Asigna la transparencia de la siguiente renderizaci?n
1594
         * @param valor de transparencia
1595
         */
1596
        public void setTransparency(int trans) {
1597
                super.setTransparency(trans);
1598
                try {
1599
                        getRenderTransparency().setOpacity(trans);
1600
                        getRenderTransparency().activeTransparency();
1601
                } catch (NullPointerException e) {
1602
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1603
                }
1604
        }
1605

    
1606
        /*
1607
         * (non-Javadoc)
1608
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getLastRenderBuffer()
1609
         */
1610
        public IBuffer getLastRenderBuffer() {
1611
                return getRender().getLastRenderBuffer();
1612
        }
1613

    
1614
        /*
1615
         * (non-Javadoc)
1616
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#cloneLayer()
1617
         */
1618
        public FLayer cloneLayer() throws Exception {
1619
                FLyrRasterSE newLayer = FLyrRasterSE.createLayer(this.getName(), params, this.getProjection());
1620
                newLayer.setNoDataValue(this.getNoDataValue());
1621
                for (int i = 0; i < dataset.getDatasetCount(); i++) {
1622
                        String name = dataset.getDataset(i)[0].getFName();
1623
                        if (!(dataset instanceof CompositeDataset) && !name.equals(this.getName()))
1624
                                newLayer.addFile(name);
1625
                }
1626
                ArrayList filters = getRender().getFilterList().getStatusCloned();
1627
        
1628
                //Hacemos una copia de las bandas a renderizar
1629
                if(getRenderBands() != null) {
1630
                        int[] rb = new int[getRenderBands().length];
1631
                        for (int i = 0; i < rb.length; i++) 
1632
                                rb[i] = getRenderBands()[i];
1633
                        newLayer.setRenderBands(rb);
1634
                }
1635
                
1636
                //Asignamos el entorno
1637
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());        
1638
                newLayer.getRender().getFilterList().setStatus(filters);
1639

    
1640
                return newLayer;
1641
        }
1642

    
1643
        /**
1644
         *
1645
         * @return ROIs asociadas a la capa raster.
1646
         */
1647
        public ArrayList getRois() {
1648
                return rois;
1649
        }
1650

    
1651
        /**
1652
         * Establece las ROI asociadas a la capa raster.
1653
         *
1654
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1655
         */
1656
        public void setRois(ArrayList rois) {
1657
                this.rois = rois;
1658
        }
1659

    
1660
        /**
1661
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1662
         * devolver? null.
1663
         * @return TreeMap con la lista de capas a dibujar
1664
         */
1665
        public HashMap getRasterStrategy() {
1666
                if(strategy != null)
1667
                        return strategy.getStrategy();
1668
                return null;
1669
        }
1670
        
1671
        /**
1672
         * @return the noDataType
1673
         */
1674
        public int getNoDataType() {
1675
                return noDataType;
1676
        }
1677

    
1678
        /**
1679
         * @param noDataType the noDataType to set
1680
         */
1681
        public void setNoDataType(int noDataType) {
1682
                this.noDataType = noDataType;
1683
        }
1684

    
1685
        /**
1686
         * @return the configuration
1687
         */
1688
        static public IConfiguration getConfiguration() {
1689
                return configuration;
1690
        }
1691

    
1692
        /**
1693
         * @param configuration the configuration to set
1694
         */
1695
        static public void setConfiguration(IConfiguration configuration) {
1696
                FLyrRasterSE.configuration = configuration;
1697
        }
1698

    
1699
        /*****************************************************/
1700

    
1701
        public void disableStopped() {state.disableStopped();}
1702

    
1703
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
1704

    
1705
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
1706

    
1707
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
1708

    
1709
        public void enableStopped() {state.enableStopped();}
1710

    
1711
        public boolean isAwake() {return state.isAwake();}
1712

    
1713
        public boolean isClosed() {return state.isClosed();}
1714

    
1715
        public boolean isOpen() {return state.isOpen();}
1716

    
1717
        public boolean isStopped() {return state.isStopped();}
1718
}