Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / extensions / extRasterTools-SE / src / org / gvsig / fmap / raster / layers / FLyrRasterSE.java @ 28502

History | View | Annotate | Download (64.2 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
import java.util.Set;
37

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

    
41
import org.cresques.cts.IProjection;
42
import org.gvsig.fmap.crs.CRSFactory;
43
import org.gvsig.fmap.dal.DataStore;
44
import org.gvsig.fmap.dal.coverage.dataset.io.DefaultRasterIOLibrary;
45
import org.gvsig.fmap.dal.exception.ReadException;
46
import org.gvsig.fmap.dal.raster.CoverageStore;
47
import org.gvsig.fmap.dal.store.raster.RasterStoreParameters;
48
import org.gvsig.fmap.geom.GeometryLocator;
49
import org.gvsig.fmap.geom.GeometryManager;
50
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
51
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
52
import org.gvsig.fmap.geom.primitive.Envelope;
53
import org.gvsig.fmap.geom.primitive.FShape;
54
import org.gvsig.fmap.mapcontext.ViewPort;
55
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
56
import org.gvsig.fmap.mapcontext.exceptions.ReloadLayerException;
57
import org.gvsig.fmap.mapcontext.exceptions.XMLLayerException;
58
import org.gvsig.fmap.mapcontext.layers.FLayer;
59
import org.gvsig.fmap.mapcontext.layers.FLyrDefault;
60
import org.gvsig.fmap.mapcontext.layers.LayerChangeSupport;
61
import org.gvsig.fmap.mapcontext.layers.LayerListener;
62
import org.gvsig.fmap.mapcontext.layers.Tiling;
63
import org.gvsig.fmap.mapcontext.layers.operations.Classifiable;
64
import org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint;
65
import org.gvsig.fmap.mapcontext.layers.operations.SingleLayer;
66
import org.gvsig.fmap.mapcontext.layers.operations.StringXMLItem;
67
import org.gvsig.fmap.mapcontext.layers.operations.XMLItem;
68
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
69
import org.gvsig.fmap.mapcontext.rendering.legend.events.listeners.LegendListener;
70
import org.gvsig.fmap.raster.legend.ColorTableLegend;
71
import org.gvsig.raster.RasterLibrary;
72
import org.gvsig.raster.buffer.BufferFactory;
73
import org.gvsig.raster.dataset.CompositeDataset;
74
import org.gvsig.raster.dataset.FileNotOpenException;
75
import org.gvsig.raster.dataset.IBuffer;
76
import org.gvsig.raster.dataset.IRasterDataSource;
77
import org.gvsig.raster.dataset.InvalidSetViewException;
78
import org.gvsig.raster.dataset.MosaicNotValidException;
79
import org.gvsig.raster.dataset.MultiRasterDataset;
80
import org.gvsig.raster.dataset.NotSupportedExtensionException;
81
import org.gvsig.raster.dataset.RasterDataset;
82
import org.gvsig.raster.dataset.RasterDriverException;
83
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
84
import org.gvsig.raster.dataset.properties.DatasetMetadata;
85
import org.gvsig.raster.dataset.serializer.RmfSerializerException;
86
import org.gvsig.raster.datastruct.ColorTable;
87
import org.gvsig.raster.datastruct.Extent;
88
import org.gvsig.raster.datastruct.ViewPortData;
89
import org.gvsig.raster.datastruct.persistence.ColorTableLibraryPersistence;
90
import org.gvsig.raster.grid.Grid;
91
import org.gvsig.raster.grid.GridException;
92
import org.gvsig.raster.grid.GridPalette;
93
import org.gvsig.raster.grid.GridTransparency;
94
import org.gvsig.raster.grid.filter.FilterTypeException;
95
import org.gvsig.raster.grid.filter.RasterFilterList;
96
import org.gvsig.raster.grid.filter.RasterFilterListManager;
97
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
98
import org.gvsig.raster.grid.filter.enhancement.EnhancementStretchListManager;
99
import org.gvsig.raster.grid.filter.enhancement.LinearStretchParams;
100
import org.gvsig.raster.grid.render.Rendering;
101
import org.gvsig.raster.grid.render.VisualPropertyEvent;
102
import org.gvsig.raster.grid.render.VisualPropertyListener;
103
import org.gvsig.raster.grid.roi.ROI;
104
import org.gvsig.raster.hierarchy.IRasterDataset;
105
import org.gvsig.raster.hierarchy.IRasterOperations;
106
import org.gvsig.raster.hierarchy.IRasterProperties;
107
import org.gvsig.raster.hierarchy.IStatistics;
108
import org.gvsig.raster.process.RasterTask;
109
import org.gvsig.raster.process.RasterTaskQueue;
110
import org.gvsig.raster.projection.CRS;
111
import org.gvsig.raster.util.ColorConversion;
112
import org.gvsig.raster.util.Historical;
113
import org.gvsig.raster.util.MathUtils;
114
import org.gvsig.raster.util.RasterToolsUtil;
115
import org.gvsig.tools.task.Cancellable;
116
import org.slf4j.Logger;
117
import org.slf4j.LoggerFactory;
118

    
119
import com.iver.utiles.NotExistInXMLEntity;
120
import com.iver.utiles.XMLEntity;
121
import com.iver.utiles.XMLException;
122

    
123
/**
124
 * Capa raster
125
 * @author Nacho Brodin (nachobrodin@gmail.com)
126
 */
127
public class FLyrRasterSE extends FLyrDefault implements IRasterProperties,
128
                IRasterDataset, InfoByPoint, Classifiable, IRasterOperations,
129
                IRasterLayerActions, ILayerState, VisualPropertyListener, SingleLayer {
130
        private boolean                mustTileDraw        = false;
131
        private boolean                mustTilePrint       = true;
132
        private int                    maxTileDrawWidth    = 200;
133
        private int                    maxTileDrawHeight   = 200;
134
        private int                    maxTilePrintWidth   = 1500;
135
        private int                    maxTilePrintHeight  = 1500;
136
        protected IStatusRaster        status              = null;
137
        private boolean                firstLoad           = false;
138
        private boolean                removeRasterFlag    = true;
139
        private Object                 params              = null;
140
        protected IRasterDataSource    dataset             = null;
141
        protected Rendering            render              = null;
142
        protected BufferFactory        bufferFactory       = null;
143
        private int                    posX                = 0;
144
        private int                    posY                = 0;
145
        private double                 posXWC              = 0;
146
        private int                    posYWC              = 0;
147
        private int                    r                   = 0;
148
        private int                    g                   = 0;
149
        private int                    b                   = 0;
150
        private LayerChangeSupport     layerChangeSupport  = new LayerChangeSupport();
151
        private FLyrState              state               = new FLyrState();
152
        private ArrayList              filterArguments     = null;
153
        protected ILegend              lastLegend          = null;
154
        protected ColorTable           loadedFromProject   = null;
155
        private ArrayList              rois                = null;
156
        private RasterDrawStrategy     strategy            = null;
157
        static private IConfiguration  configuration       = new DefaultLayerConfiguration();
158

    
159
        private BufferedImage          image               = null;
160
        private static GeometryManager geomManager              = GeometryLocator.getGeometryManager();
161
        private static final Logger    logger              = LoggerFactory.getLogger(FLyrRasterSE.class);
162

    
163
        /**
164
         * Tipo de valor no data asociado a la capa.
165
         * Sirve para diferenciar los estados seleccionados por el usuario. Siendo
166
         * estos 'Sin Valor NoData', 'NoData de Capa'(Por defecto) y 'Personalizado'
167
         */
168
        private int                    noDataType          = RasterLibrary.NODATATYPE_LAYER;
169

    
170
        /**
171
         * Lista de transformaciones afines que son aplicadas. Esta lista es
172
         * simplemente un historico que no se utiliza. Es posible utilizarlo para
173
         * recuperar transformaciones anteriores.
174
         */
175
        private Historical             affineTransformList = new Historical();
176
        private CoverageStore          store               = null;
177

    
178
        static {
179
                 RasterLibrary.wakeUp();
180
                 try {
181
                         new DefaultRasterIOLibrary().initialize();
182
                 } catch (NoClassDefFoundError e) {
183
                         RasterToolsUtil.debug("There was not possible to load drivers", e, null);
184
                 }
185
        }
186

    
187
        /**
188
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
189
         *
190
         * @param layerName
191
         *            Nombre de la capa..
192
         * @param params
193
         *            Par?metros de carga del formato. El caso m?s simple es la ruta
194
         *            de la capa en disco.
195
         * @param d
196
         *            RasterDriver.
197
         * @param f
198
         *            Fichero.
199
         * @param proj
200
         *            Proyecci?n.
201
         * @return Nueva capa de tipo raster.
202
         * @throws DriverIOException
203
         *
204
         * @deprecated
205
         */
206
        public static FLyrRasterSE createLayer(String layerName, Object params,
207
                        IProjection proj) throws LoadLayerException {
208
                FLyrRasterSE capa = new FLyrRasterSE();
209
                capa.setLoadParams(params);
210
                capa.setName(layerName);
211
                capa.setProjection(proj);
212
                capa.load();
213
                return capa;
214
        }
215

    
216
        /**
217
         * Asigna los par?metros para la carga de la capa
218
         *
219
         * @param param
220
         *            Par?metros.
221
         *
222
         * @deprecated
223
         */
224
        public void setLoadParams(Object param){
225
                this.params = param;
226

    
227
                //Si la capa tiene nombre acivamos el estado awake
228
                if(params != null && getName() != null)
229
                        try {
230
                                enableAwake();
231
                        } catch (NotAvailableStateException e) {
232
                                RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
233
                        }
234
        }
235

    
236
        /**
237
         * Obtiene los par?metros para la carga de la capa
238
         *
239
         * @return param Par?metros.
240
         *
241
         * @deprecated
242
         */
243
        public Object getLoadParams() {
244
                return params;
245
        }
246

    
247
        /*
248
         * (non-Javadoc)
249
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setName(java.lang.String)
250
         */
251
        public void setName(String name) {
252
                super.setName(name);
253

    
254
                //Si la capa tiene nombre acivamos el estado awake
255
                if(getLoadParams() != null && name != null)
256
                        try {
257
                                if(isClosed())
258
                                        enableAwake();
259
                        } catch (NotAvailableStateException e) {
260
                                RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
261
                        }
262
        }
263

    
264
        /*
265
         * (non-Javadoc)
266
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#wakeUp()
267
         */
268
        public void wakeUp(){
269
                if (bufferFactory == null)
270
                        try {
271
                                reload();
272
                        } catch (ReloadLayerException e) {
273
                                // No se ha podido recuperar la capa con exito
274
                        }
275
        }
276

    
277
        /**
278
         * Asignar el estado del raster
279
         * @param status
280
         */
281
        public void setStatus(IStatusRaster status){
282
                this.status = status;
283
        }
284

    
285
        /**
286
         * Obtiene el estado del raster
287
         * @return
288
         */
289
        public IStatusRaster getStatus(){
290
                return this.status;
291
        }
292

    
293
        /*
294
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
295
         */
296
        public void load() throws LoadLayerException {
297
                if (isStopped())
298
                        return;
299

    
300
                enableStopped(); // Paramos la capa mientras se hace un load
301

    
302
                String fName = null;
303
                int test = -1;
304
                if (params != null && params instanceof File) {
305
                        fName = ((File) params).getAbsolutePath();
306
                        test = fName.indexOf("ecwp:");
307
                }
308

    
309
                if (test != -1) {
310
                        String urlECW = fName.substring(test + 6);
311
                        fName = "ecwp://" + urlECW;
312
                        System.err.println(test + " " + fName);
313
                }
314

    
315
                try {
316
                        if (params instanceof String[][]) {
317
                                String[][] files = (String[][]) params;
318
                                MultiRasterDataset[][] dt = new MultiRasterDataset[files.length][files[0].length];
319
                                for (int i = 0; i < files.length; i++)
320
                                        for (int j = 0; j < files[i].length; j++)
321
                                                dt[i][j] = MultiRasterDataset.open(getProjection(), files[i][j]);
322
                                dataset = new CompositeDataset(dt);
323
                        } else
324
                                if (params == null || params instanceof File) {
325
                                        if (fName != null)
326
                                                dataset = MultiRasterDataset.open(getProjection(), fName);
327
                                } else
328
                                        dataset = MultiRasterDataset.open(getProjection(), params);
329
                } catch (NotSupportedExtensionException e) {
330
                        throw new LoadLayerException("Formato no valido", e);
331
                } catch (MosaicNotValidException e) {
332
                        throw new LoadLayerException("Error en el mosaico", e);
333
                } catch (Exception e) {
334
                        throw new LoadLayerException("No existe la capa.", e);
335
                }
336
                if (dataset != null)
337
                        this.init();
338
        }
339

    
340
        /**
341
         * Acciones de inicializaci?n despu?s de que la fuente de datos
342
         * de la capa est? asignada. El tipo de fuente de datos es variable
343
         * puede ser MultiRasterDataset, CompositeDataset u otras que existan e
344
         * implementen IRasterDatasource.
345
         */
346
        public void init() throws LoadLayerException {
347
                if (dataset == null)
348
                        throw new LoadLayerException("Formato no valido", new IOException());
349

    
350
                bufferFactory = new BufferFactory(dataset);
351
                render = new Rendering(bufferFactory);
352
                render.addVisualPropertyListener(this);
353
                initFilters();
354

    
355
                //Inicializaci?n del historico de transformaciones
356
                affineTransformList.clear();
357
                affineTransformList.add(this.getAffineTransform());
358

    
359
                try {
360
                        enableOpen();
361
                } catch (NotAvailableStateException e) {
362
                        RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Awake=" + isAwake(), this, e);
363
                }
364
        }
365

    
366
        /**
367
         * Obtiene la proyecci?n del fichero.
368
         * @return IProjection
369
         */
370
        public IProjection readProjection() {
371
                try {
372
                        CRS.setCRSFactory(CRSFactory.cp);
373
                        if( dataset == null )
374
                                return null;
375
                        return CRS.convertWktToIProjection(dataset.getWktProjection());
376
                } catch (RasterDriverException e) {
377
                        RasterToolsUtil.messageBoxError("Problemas accediendo a getWktProjection. Driver no inicializado", this, e);
378
                }
379
                return null;
380
        }
381

    
382
        /**
383
         * Crea el objeto renderizador de raster
384
         * @return Rendering
385
         */
386
        public Rendering getRender() {
387
                if (render == null) {
388
                        render = new Rendering(bufferFactory);
389
                        render.addVisualPropertyListener(this);
390
                }
391
                return render;
392
        }
393

    
394
        /**
395
         * Aplica los filtros noData al layer
396
         * @param rasterSE
397
         * @param filterManager
398
         */
399
        public void applyNoData() {
400
                Boolean noDataEnabled = configuration.getValueBoolean("nodata_transparency_enabled", Boolean.FALSE);
401
                if (noDataEnabled.booleanValue() && getDataSource().isNoDataEnabled()) {
402
                        noDataType = RasterLibrary.NODATATYPE_LAYER;
403
                        Double noDataValue = Double.valueOf(getNoDataValue());
404
                        getDataSource().getTransparencyFilesStatus().setNoData(noDataValue.doubleValue());
405
                } else {
406
                        getDataSource().getTransparencyFilesStatus().activeNoData(false);
407
                        noDataType = RasterLibrary.NODATATYPE_DISABLED;
408
                }
409
        }
410

    
411
        /**
412
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
413
         */
414
        private void initFilters() {
415
                RasterFilterList filterList = new RasterFilterList();
416
                filterList.addEnvParam("IStatistics", getDataSource().getStatistics());
417
                filterList.addEnvParam("MultiRasterDataset", getDataSource());
418

    
419
                getDataSource().resetNoDataValue();
420
                applyNoData();
421
                GridTransparency gridTransparency = new GridTransparency(getDataSource().getTransparencyFilesStatus());
422

    
423
                filterList.setInitDataType(getDataType()[0]);
424
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
425

    
426
                // Quitamos la leyenda
427
                lastLegend = null;
428

    
429
                try {
430
                        //Si en la carga del proyecto se carg? una tabla de color asignamos esta
431
                        if(loadedFromProject != null) {
432
                                GridPalette p = new GridPalette(loadedFromProject);
433
                                setLastLegend(p);
434
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
435
                                ctm.addColorTableFilter(p);
436
                        } else
437
                                //sino ponemos la tabla asociada al raster
438
                                if (this.getDataSource().getColorTables()[0] != null) {
439
                                GridPalette p = new GridPalette(getDataSource().getColorTables()[0]);
440
                                setLastLegend(p);
441
                                ColorTableListManager ctm = new ColorTableListManager(filterManager);
442
                                ctm.addColorTableFilter(p);
443
                        } else //sino hace lo que dice en las preferencias
444
                                if (getDataType()[0] != IBuffer.TYPE_BYTE)
445
                                        loadEnhancedOrColorTable(filterManager);
446
                        loadedFromProject = null;
447

    
448
                        getRender().setFilterList(filterList);
449
                        // Inicializo la transparencia para el render
450
                        getRender().setLastTransparency(gridTransparency);
451
                } catch (FilterTypeException e) {
452
                        //Ha habido un error en la asignaci?n de filtros por los que no se a?ade ninguno.
453
                        RasterToolsUtil.debug("Error a?adiendo filtros en la inicializaci?n de capa " + this.getName() + " Datatype=" + this.getDataType(), null, e);
454
                }
455
        }
456

    
457
        /**
458
         * Mira la configuracion para saber si debe cargar un realce o una tabla
459
         * de color por defecto
460
         * @param filterManager
461
         * @throws FilterTypeException
462
         */
463
        private void loadEnhancedOrColorTable(RasterFilterListManager filterManager) throws FilterTypeException {
464
                String colorTableName = configuration.getValueString("loadlayer_usecolortable", (String) null);
465

    
466
                String palettesPath = System.getProperty("user.home") +
467
                        File.separator +
468
                        "gvSIG" + // PluginServices.getArguments()[0] +
469
                        File.separator + "colortable";
470

    
471
                IStatistics stats = getDataSource().getStatistics();
472

    
473
                if (colorTableName != null)
474
                        try {
475
                                stats.calcFullStatistics();
476
                                if (getBandCount() == 1) {
477
                                        ArrayList fileList = ColorTableLibraryPersistence.getPaletteFileList(palettesPath);
478
                                        for (int i = 0; i < fileList.size(); i++) {
479
                                                ArrayList paletteItems = new ArrayList();
480
                                                String paletteName = ColorTableLibraryPersistence.loadPalette(palettesPath, (String) fileList.get(i), paletteItems);
481
                                                if (paletteName.equals(colorTableName)) {
482
                                                        if (paletteItems.size() <= 0)
483
                                                                continue;
484

    
485
                                                        ColorTable colorTable = new ColorTable();
486
                                                        colorTable.setName(paletteName);
487
                                                        colorTable.createPaletteFromColorItems(paletteItems, true);
488
                                                        colorTable.setInterpolated(true);
489

    
490
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
491

    
492
                                                        GridPalette p = new GridPalette(colorTable);
493
                                                        setLastLegend(p);
494

    
495
                                                        ColorTableListManager ctm = new ColorTableListManager(filterManager);
496
                                                        ctm.addColorTableFilter(p);
497
                                                        return;
498
                                                }
499
                                        }
500
                                }
501
                        } catch (FileNotOpenException e) {
502
                                // No podemos aplicar el filtro
503
                        } catch (RasterDriverException e) {
504
                                // No podemos aplicar el filtro
505
                        } catch (InterruptedException e) {
506
                                // El usuario ha cancelado el proceso
507
                        }
508

    
509
                /*EnhancementListManager elm = new EnhancementListManager(filterManager);
510
                elm.addEnhancedFilter(false, stats, 0.0, getRender().getRenderBands());*/
511

    
512
                EnhancementStretchListManager elm = new EnhancementStretchListManager(filterManager);
513
                try {
514
                        elm.addEnhancedStretchFilter(LinearStretchParams.createStandardParam(getRenderBands(), 0.0, stats, false),
515
                                                                                stats,
516
                                                                                getRender().getRenderBands(),
517
                                                                                false);
518
                } catch (FileNotOpenException e) {
519
                        //No podemos aplicar el filtro
520
                } catch (RasterDriverException e) {
521
                        //No podemos aplicar el filtro
522
                }
523
        }
524

    
525
        /**
526
         * Devuelve si es reproyectable o no la capa
527
         * @return
528
         */
529
        public boolean isReproyectable() {
530
                if (dataset == null)
531
                        return false;
532

    
533
                int nFiles = dataset.getDatasetCount();
534
                for (int i = 0; i < nFiles; i++)
535
                        if (!dataset.getDataset(i)[0].isReproyectable())
536
                                return false;
537
                return true;
538
        }
539

    
540
        /**
541
         * @throws ReadException
542
         * @throws ReadDriverException
543
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
544
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
545
         *                 com.iver.utiles.swing.threads.Cancellable)
546
         */
547
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) throws ReadException {
548
                this.image = image;
549
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
550
                task.setEvent(null);
551

    
552
                try {
553
                        if (!isOpen())
554
                                return;
555

    
556
                        enableStopped();
557
                        // callLegendChanged(null);
558

    
559
                        strategy = new RasterDrawStrategy(getMapContext(), this);
560
                        strategy.stackStrategy();
561
                        HashMap tStr = strategy.getStrategy();
562
                        if (tStr != null &&
563
                                tStr.get(this) != null &&
564
                                ((Boolean) (tStr.get(this))).booleanValue() == false) {
565
                                disableStopped();
566
                                return;
567
                        }
568

    
569
                        if (isWithinScale(scale)) {
570
                                if (status != null && firstLoad) {
571
                                        if (mustTileDraw) {
572
                                                Point2D p = vp.getOffset();
573
                                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
574
                                                Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
575
                                                tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
576
                                                for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
577
                                                        // drawing part
578
                                                        try {
579
                                                                ViewPort vport = tiles.getTileViewPort(vp, tileNr);
580
//                                                                g.setClip(tiles.getClip(tileNr).x, tiles.getClip(tileNr).y, tiles.getClip(tileNr).width - 5, tiles.getClip(tileNr).height);
581
                                                                draw(image, g, vport, cancel);
582
                                                        } catch (InterruptedException e) {
583
                                                                System.out.println("Se ha cancelado el pintado");
584
                                                        } catch (InvalidSetViewException e) {
585
                                                                throw new ReadException("Error reading file.", e);
586
                                                        } catch (RasterDriverException e) {
587
                                                                throw new ReadException("Error reading file.", e);
588
                                                        }  catch (NoninvertibleTransformException e) {
589
                                                                throw new ReadException("Error in the transformation.", e);
590
                                                        }
591
                                        } else
592
                                                try {
593
                                                        draw(image, g, vp, cancel);
594
                                                } catch (InterruptedException e) {
595
                                                        System.out.println("Se ha cancelado el pintado");
596
                                                } catch (InvalidSetViewException e) {
597
                                                        throw new ReadException("Error reading file.", e);
598
                                                } catch (RasterDriverException e) {
599
                                                        throw new ReadException("Error reading file.", e);
600
                                                }
601
                                        try {
602
                                                status.applyStatus(this);
603
                                        } catch (NotSupportedExtensionException e) {
604
                                                throw new ReadException("Error in input file", e);
605
                                        } catch (FilterTypeException e) {
606
                                                throw new ReadException("Error setting filters from a project.", e);
607
                                        } catch (RasterDriverException e) {
608
                                                throw new ReadException("Error reading file.", e);
609
                                        }
610
                                        firstLoad = false;
611
                                }
612

    
613
                                if (mustTileDraw) {
614
                                        Point2D p = vp.getOffset();
615
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
616
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
617
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
618
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
619
                                                // drawing part
620
                                                try {
621
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
622
                                                        draw(image, g, vport, cancel);
623
                                                } catch (InterruptedException e) {
624
                                                        System.out.println("Se ha cancelado el pintado");
625
                                                } catch (InvalidSetViewException e) {
626
                                                        throw new ReadException("Error reading file.", e);
627
                                                } catch (RasterDriverException e) {
628
                                                        throw new ReadException("Error reading file.", e);
629
                                                }  catch (NoninvertibleTransformException e) {
630
                                                        throw new ReadException("Error in the transformation.", e);
631
                                                }
632
                                } else
633
                                        try {
634
                                                draw(image, g, vp, cancel);
635
                                        } catch (InterruptedException e) {
636
                                                System.out.println("Se ha cancelado el pintado");
637
                                        } catch (InvalidSetViewException e) {
638
                                                throw new ReadException("Error reading file.", e);
639
                                        } catch (RasterDriverException e) {
640
                                                throw new ReadException("Error reading file.", e);
641
                                        }
642

    
643
                        }
644
                        //callLegendChanged(null);
645
                } finally {
646
                        disableStopped();
647
                        task.setEvent(null);
648
                }
649
        }
650

    
651
        private void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) throws RasterDriverException, InvalidSetViewException, InterruptedException {
652
                Envelope adjustedExtent = vp.getAdjustedExtent();
653
                if (adjustedExtent == null)
654
                        return;
655
                Extent e = new Extent(adjustedExtent.getLowerCorner().getX(),
656
                                adjustedExtent.getUpperCorner().getY(), adjustedExtent
657
                                                .getUpperCorner().getX(),
658
                                adjustedExtent
659
                                                .getLowerCorner().getY());
660
                Dimension imgSz = vp.getImageSize();
661
                ViewPortData vp2 = new ViewPortData(vp.getProjection(), e, imgSz );
662
                vp2.setMat(vp.getAffineTransform());
663
                getRender().draw(g, vp2);
664
        }
665

    
666
        /**
667
         * Inserta la proyecci?n.
668
         *
669
         * @param proj Proyecci?n.
670
         */
671
        public void setProjection(IProjection proj) {
672
                super.setProjection(proj);
673
        }
674

    
675
        /*
676
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
677
         */
678
        public Envelope getFullEnvelope() {
679
                //TODO:DEPURACION Comentamos !isOpen porque getFullExtent de FLayers da una excepci?n ya que siempre espera
680
                //un extent aunque la capa no est? abierta
681
                if(/*!isOpen() || */dataset == null || dataset.getExtent() == null)
682
                        return null;
683

    
684
                Rectangle2D e = dataset.getExtent().toRectangle2D();
685
                try {
686
                        return geomManager.createEnvelope(e.getX(), e.getY(), e.getMaxX(), e
687
                                        .getMaxY(), SUBTYPES.GEOM2D);
688
                } catch (CreateEnvelopeException e1) {
689
                        logger.error("Error creating the envelope", e);
690
                        return null;
691
                }
692
        }
693

    
694
        /**
695
         * Obtiene el valor del pixel del Image en la posici?n x,y
696
         * @param x Posici?n x
697
         * @param y Posici?n y
698
         * @return valor de pixel
699
         */
700
        public int[] getPixel(int pxx, int pxy) {
701
                int[] argb = { -1, -1, -1, -1 };
702
                if (!isOpen() || (image == null))
703
                        return argb;
704
                if (pxx >= 0 && pxx < image.getWidth() && pxy >= 0 && pxy < image.getHeight()) {
705
                        int value = image.getRGB(pxx, pxy);
706
                        argb[0] = ((value & 0xff000000) >> 24);
707
                        argb[1] = ((value & 0x00ff0000) >> 16);
708
                        argb[2] = ((value & 0x0000ff00) >> 8);
709
                        argb[3] = (value & 0x000000ff);
710
                }
711
                return argb;
712
        }
713

    
714
        /*
715
         * (non-Javadoc)
716
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
717
         */
718
        public double getMaxX() {
719
                if(getFullEnvelope() != null)
720
                        return getFullEnvelope().getMaximum(0);
721
                return -1;
722
        }
723

    
724
        /*
725
         * (non-Javadoc)
726
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
727
         */
728
        public double getMaxY() {
729
                if(getFullEnvelope() != null)
730
                        return this.getFullEnvelope().getMaximum(1);
731
                return -1;
732
        }
733

    
734
        /*
735
         * (non-Javadoc)
736
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinX()
737
         */
738
        public double getMinX() {
739
                if(getFullEnvelope() != null)
740
                        return getFullEnvelope().getMinimum(0);
741
                return -1;
742
        }
743

    
744
        /*
745
         * (non-Javadoc)
746
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinY()
747
         */
748
        public double getMinY() {
749
                if(getFullEnvelope() != null)
750
                        return getFullEnvelope().getMinimum(1);
751
                return -1;
752
        }
753

    
754
        /* (non-Javadoc)
755
         * @deprecated. See String getInfo(Point p) throws DriverException
756
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
757
         */
758
        public String queryByPoint(Point p) {
759
                if (!isOpen())
760
                        return null;
761
                ColorConversion conv = new ColorConversion();
762

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

    
765
                ArrayList attr = getAttributes();
766
                data += "  <raster\n";
767
                data += "    File=\"" + getFile() + "\"\n";
768
                for (int i = 0; i < attr.size(); i++) {
769
                        Object[] a = (Object[]) attr.get(i);
770

    
771
                        data += "    " + a[0].toString() + "=";
772
                        if (a[1].toString() instanceof String)
773
                                data += "\"" + a[1].toString() + "\"\n";
774
                        else
775
                                data += a[1].toString() + "\n";
776
                }
777
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
778
                data += "    Point_WC=\"" + MathUtils.format(posXWC, 3) + " , " + MathUtils.format(posYWC, 3) + "\"\n";
779
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
780
                double[] cmyk = conv.RGBtoCMYK(r & 0xff, g & 0xff, b & 0xff, 1D);
781
                data += "    CMYK=\"" + MathUtils.format(cmyk[0], 4) + ", " + MathUtils.format(cmyk[1], 4) + ", " + MathUtils.format(cmyk[2], 4) + "," + MathUtils.format(cmyk[3], 4) + "\"\n";
782
                double[] hsl = conv.RGBtoHSL(r & 0xff, g & 0xff, b & 0xff);
783
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
784
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
785
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
786
                data += "    HSL=\"" + MathUtils.format(hsl[0], 4) + ", " + MathUtils.format(hsl[1], 4) + ", " + MathUtils.format(hsl[2], 4) + "\"\n";
787
                data += "  />\n";
788

    
789
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
790
                return data;
791
        }
792

    
793
        /**
794
         * Transforma un punto real a coordenadas pixel indicando la banda que es usada para la
795
         * transformaci?n. Hay que tener en cuenta que es posible que todas las transformaciones no
796
         * sean iguales en todas la bandas porque puede haber bandas de distinta resoluci?n.
797
         *
798
         * @param numberBand
799
         * @param pReal
800
         * @return
801
         * @throws ReadDriverException
802
         */
803
        private Point2D transformPoint(int numberBand, Point2D pReal) throws NoninvertibleTransformException {
804
                AffineTransform at = this.getDataSource().getAffineTransform(numberBand);
805
                Point2D px = new Point2D.Double();
806
                //px = new Point2D.Double(pReal.getX(), pReal.getY());
807
                at.inverseTransform(pReal, px);
808
                return px;
809
        }
810

    
811
        /*
812
         * (non-Javadoc)
813
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo(java.awt.Point, double, com.iver.utiles.swing.threads.Cancellable)
814
         */
815
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel)
816
                        throws ReadException {
817
                if (!isOpen()) {
818
                        StringXMLItem[] item = new StringXMLItem[1];
819
                        String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
820
                        data += "  <raster\n" + "  Layer=\" Not available\"\n" + "  />\n";
821
                        data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
822
                        item[0] = new StringXMLItem(data, this);
823
                        return item;
824
                }
825

    
826
                Point2D pReal = getMapContext().getViewPort().toMapPoint(p);
827
                Point2D px = new Point2D.Double();
828
                if(        pReal.getX() > this.getMinX() &&
829
                        pReal.getX() < this.getMaxX() &&
830
                        pReal.getY() > this.getMinY() &&
831
                        pReal.getY() < this.getMaxY())
832
                        try {
833
                                px = transformPoint(0, pReal);
834
                        } catch (NoninvertibleTransformException e) {
835
                                throw new ReadException("Error in the transformation", e);
836
                        }
837
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
838
                ColorConversion conv = new ColorConversion();
839

    
840
                StringXMLItem[] item = new StringXMLItem[1];
841
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
842

    
843
                data += "  <raster\n";
844
                data += "    View_Point=\"" + p.getX() + " , " + p.getY() + "\"\n";
845
                data += "    World_Point=\"" + MathUtils.format(pReal.getX(), 3) + " , " + MathUtils.format(pReal.getY(), 3) + "\"\n";
846
                if (px == null)
847
                        data += "    Pixel_Point=\"Out\"\n";
848
                else
849
                        data += "    Pixel_Point=\"" + (int) px.getX() + " , " + (int) px.getY() + "\"\n";
850
                data += "    RGB=\"" + rgb[1] + "  " + rgb[2] + "  " + rgb[3] + "\"\n";
851
                double[] cmyk = conv.RGBtoCMYK(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff, 1D);
852
                data += "    CMYK=\"" + MathUtils.format(cmyk[0], 4) + ", " + MathUtils.format(cmyk[1], 4) + ", " + MathUtils.format(cmyk[2], 4) + "," + MathUtils.format(cmyk[3], 4) + "\"\n";
853
                double[] hsl = conv.RGBtoHSL(rgb[1] & 0xff, rgb[2] & 0xff, rgb[3] & 0xff);
854
                hsl[0] = (int)(255.0 * hsl[0] / 360.0 + 0.5);
855
                hsl[2] = (int) (hsl[2] * 255. + 0.5);
856
                hsl[1] = (int) (hsl[1] * 255. + 0.5);
857
                data += "    HSL=\"" + MathUtils.format(hsl[0], 4) + ", " + MathUtils.format(hsl[1], 4) + ", " + MathUtils.format(hsl[2], 4) + "\"\n";
858
                data += "    Band_Value=\"";
859
                try {
860
                        if (px != null) {
861
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3)
862
                                        for(int i = 0; i < getBandCount(); i++)
863
                                                if(getDataSource().isInside(pReal)) {
864
                                                        Point2D pxAux = transformPoint(i, pReal);
865
                                                        data += ((Integer)getDataSource().getData((int)pxAux.getX(), (int)pxAux.getY(), i)).intValue() + "  ";
866
                                                }
867
                                if(getDataType()[0] == 4)
868
                                        for(int i = 0; i < getBandCount(); i++)
869
                                                if(getDataSource().isInside(pReal)) {
870
                                                        Point2D pxAux = transformPoint(i, pReal);
871
                                                        data += ((Float)getDataSource().getData((int)pxAux.getX(), (int)pxAux.getY(), i)).floatValue() + "  ";
872
                                                }
873
                                if(getDataType()[0] == 5)
874
                                        for(int i = 0; i < getBandCount(); i++)
875
                                                if(getDataSource().isInside(pReal)) {
876
                                                        Point2D pxAux = transformPoint(i, pReal);
877
                                                        data += ((Double)getDataSource().getData((int)pxAux.getX(), (int)pxAux.getY(), i)).doubleValue() + "  ";
878
                                                }
879
                        }
880
                } catch (RasterDriverException ex) {
881
                        throw new ReadException("Error en el acceso al dataset", ex);
882
                } catch (InvalidSetViewException ex) {
883
                        throw new ReadException(
884
                                        "Error en la asignaci?n de la vista en getData", ex);
885
                } catch (FileNotOpenException ex) {
886
                        throw new ReadException("Fichero no abierto en el dataset", ex);
887
                } catch (NoninvertibleTransformException ex) {
888
                        throw new ReadException("Error in the transformation", ex);
889
                }
890
                data += "\"\n";
891
                data += "  />\n";
892
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
893

    
894
                item[0] = new StringXMLItem(data, this);
895
                return item;
896
        }
897

    
898
        /**
899
         * Filters a string for being suitable as XML Tag, erasing
900
         * all not alphabetic or numeric characters.
901
         * @param s
902
         * @return string normalized
903
         */
904
        private String normalizeAsXMLTag(String s) {
905
                return s.replaceAll("[^a-zA-Z0-9]", "");
906
        }
907

    
908
        /**
909
         * Obtiene atributos a partir de un georasterfile
910
         * @return
911
         */
912
        public ArrayList getAttributes() {
913
                ArrayList attr = new ArrayList();
914
                if(!isOpen())
915
                        return attr;
916
                Object [][] a = {
917
                        {"Filename", dataset.getDataset(0)[0].getFName()},
918
                        {"Filesize", new Long(dataset.getFileSize())},
919
                        {"Width", new Integer((int)dataset.getWidth())},
920
                        {"Height", new Integer((int)dataset.getHeight())},
921
                        {"Bands", new Integer(dataset.getBandCount())}
922
                };
923
                for (int i = 0; i < a.length; i++)
924
                        attr.add(a[i]);
925
                return attr;
926
        }
927

    
928
        /**
929
         * Escribe en el proyecto la capa actual
930
         * @throws XMLException
931
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
932
         */
933
        public XMLEntity getXMLEntity() throws XMLException {
934
                if(isClosed() || isAwake())
935
                        return null;
936

    
937
                XMLEntity xml = super.getXMLEntity();
938
                if(getFile() != null)
939
                        xml.putProperty("file", getFile());
940
                xml.putProperty("driverName", "gvSIG Raster Driver");
941

    
942
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
943
                if (status == null)
944
                        status = new StatusLayerRaster();
945
                status.getXMLEntity(xml, true, this);
946

    
947
                return xml;
948
        }
949

    
950
        /**
951
         * Recupera de disco los datos de la capa.
952
         */
953
        public void setXMLEntity(XMLEntity xml) throws XMLException {
954
                for (int i = 0; i < xml.getPropertyCount(); i++) {
955
                        String key = xml.getPropertyName(i);
956
                        if(key.startsWith("raster.file")) {
957
                                if(xml.getPropertyValue(i).startsWith(RasterLibrary.getTemporalPath()))
958
                                        throw new XMLLayerException("Trying to load temporary layer", null);
959
                        }
960
                }
961
                super.setXMLEntity(xml);
962

    
963
                try {
964
                        params = new File(xml.getStringProperty("file"));
965

    
966
                        if(params != null && getName() != null && getName().compareTo("") != 0)
967
                                try {
968
                                        enableAwake();
969
                                } catch (NotAvailableStateException e) {
970
                                        RasterToolsUtil.messageBoxError("Fallo el estado de open. Closed=" + isClosed() + " Active=" + isOpen(), this, e);
971
                                }
972
                        if(!super.getFLayerStatus().visible)
973
                                enableStopped();
974

    
975
                        // Para notificar al adapter-driver cual es la proyecci?n.
976
                        setProjection(super.getProjection());
977

    
978
                        //Inicializamos la clase a la que se usa por defecto para
979
                        //compatibilidad con proyectos antiguos
980
                        String claseStr = StatusLayerRaster.defaultClass;
981
                        if (xml.contains("raster.class"))
982
                                claseStr = xml.getStringProperty("raster.class");
983

    
984
                        if (status != null)
985
                                status.setXMLEntity(xml, this);
986
                        else if (claseStr != null && !claseStr.equals(""))
987
                                try {
988
                                        // Class clase =
989
                                        // LayerFactory.getLayerClassForLayerClassName(claseStr);
990
                                        Class clase = this.getClass();
991
                                        Constructor constr = clase.getConstructor(null);
992
                                        status = (IStatusRaster) constr.newInstance(null);
993
                                        if (status != null) {
994
                                                ((StatusLayerRaster)status).setNameClass(claseStr);
995
                                                status.setXMLEntity(xml, this);
996
                                                filterArguments = status.getFilterArguments();
997

    
998
                                                //Creamos la tabla de color
999
                                                ArrayList color = (ArrayList) filterArguments.clone();
1000
                                                loadedFromProject = ColorTableListManager.createColorTableFromArray(color);
1001
                                        }
1002
                                        // } catch (ClassNotFoundException exc) {
1003
                                        // throw new XMLLayerException("", exc);
1004
                                } catch (InstantiationException exc) {
1005
                                        throw new XMLLayerException("", exc);
1006
                                } catch (IllegalAccessException exc) {
1007
                                        throw new XMLLayerException("", exc);
1008
                                } catch (NoSuchMethodException exc) {
1009
                                        throw new XMLLayerException("", exc);
1010
                                } catch (InvocationTargetException exc) {
1011
                                        throw new XMLLayerException("", exc);
1012
                                }
1013
                        firstLoad = true;
1014
                } catch (NotExistInXMLEntity e) {
1015

    
1016
                }
1017
        }
1018

    
1019
        /* (non-Javadoc)
1020
         * @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)
1021
         */
1022
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet propeties) throws ReadException {
1023

    
1024
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
1025
                        return;
1026

    
1027
                if (!mustTilePrint)
1028
                        draw(null, g, viewPort, cancel,scale);
1029
                else {
1030
                        // Para no pedir imagenes demasiado grandes, vamos
1031
                        // a hacer lo mismo que hace EcwFile: chunkear.
1032
                        // Llamamos a drawView con cuadraditos m?s peque?os
1033
                        // del BufferedImage ni caso, cuando se imprime viene con null
1034
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
1035
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
1036

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

    
1040
                        //RasterStats stats = getSource().getFilterStack().getStats();
1041
                        //if(stats != null)
1042
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
1043

    
1044

    
1045
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++)
1046
                                // Parte que dibuja
1047
                                try {
1048
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
1049
                                        draw(null, g, vp, cancel, scale);
1050
                                } catch (NoninvertibleTransformException e) {
1051
                                        throw new ReadException("Error en la transformaci?n.", e);
1052
                                }
1053
                }
1054
        }
1055

    
1056
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
1057
                        double scale) throws ReadException {
1058
                if(!isOpen())
1059
                        return;
1060

    
1061
                // Para no pedir imagenes demasiado grandes, vamos
1062
                // a hacer lo mismo que hace EcwFile: chunkear.
1063
                // Llamamos a drawView con cuadraditos m?s peque?os
1064
                // del BufferedImage ni caso, cuando se imprime viene con null
1065

    
1066
                int numW, numH;
1067
                int stepX, stepY;
1068
                int xProv, yProv;
1069
                int A = 1500;
1070
                int H = 1500;
1071
                int altoAux, anchoAux;
1072

    
1073
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
1074

    
1075
                // Vamos a hacerlo en trozos de AxH
1076
                Rectangle r = g.getClipBounds();
1077
                numW = (r.width) / A;
1078
                numH = (r.height) / H;
1079

    
1080
                double[] srcPts = new double[8];
1081
                double[] dstPts = new double[8];
1082

    
1083
                yProv = r.y;
1084
                for (stepY = 0; stepY < numH + 1; stepY++) {
1085
                        if ((yProv + H) > r.getMaxY())
1086
                                altoAux = (int) r.getMaxY() - yProv;
1087
                        else
1088
                                altoAux = H;
1089

    
1090
                        xProv = r.x;
1091
                        for (stepX = 0; stepX < numW + 1; stepX++) {
1092
                                if ((xProv + A) > r.getMaxX())
1093
                                        anchoAux = (int) r.getMaxX() - xProv;
1094
                                else
1095
                                        anchoAux = A;
1096

    
1097
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
1098

    
1099
                                // Parte que dibuja
1100
                                srcPts[0] = xProv;
1101
                                srcPts[1] = yProv;
1102
                                srcPts[2] = xProv + anchoAux + 1;
1103
                                srcPts[3] = yProv;
1104
                                srcPts[4] = xProv + anchoAux + 1;
1105
                                srcPts[5] = yProv + altoAux + 1;
1106
                                srcPts[6] = xProv;
1107
                                srcPts[7] = yProv + altoAux + 1;
1108

    
1109
                                try {
1110
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
1111
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
1112
                                        // Extent extent = new Extent(rectCuadricula);
1113

    
1114
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
1115
                                        ViewPort vp = viewPort.cloneViewPort();
1116
                                        vp.setImageSize(tam);
1117
                                        Envelope env = geomManager.createEnvelope(rectCuadricula
1118
                                                        .getMinX(), rectCuadricula.getMinY(),
1119
                                                        rectCuadricula.getMaxX(), rectCuadricula.getMaxY(),
1120
                                                        SUBTYPES.GEOM2D);
1121
                                        vp.setEnvelope(env);
1122
                                        vp.setAffineTransform(mat);
1123
                                        draw(null, g, vp, cancel, scale);
1124

    
1125
                                } catch (NoninvertibleTransformException e) {
1126
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
1127
                                } catch (ReadException e) {
1128
                                        //throw new ReadDriverException("Error en la transformaci?n.", e);
1129
                                } catch (CreateEnvelopeException e) {                                
1130
                                        logger.error("Error creating the envelope", e);
1131
                                }
1132
                                // Fin parte que dibuja
1133
                                xProv = xProv + A;
1134
                        }
1135
                        yProv = yProv + H;
1136
                }
1137
        }
1138

    
1139
        /**
1140
         * Borra de la lista de listeners el que se pasa como par?metro.
1141
         *
1142
         * @param o LayerListener a borrar.
1143
         *
1144
         * @return True si ha sido correcto el borrado del Listener.
1145
         */
1146
        public boolean removeLayerListener(LayerListener o) {
1147
                // Salva a RMF
1148
                if (this.getDataSource() != null)
1149
                        // Guardamos la GeoReferenciacion de cada dataset
1150
                        try {
1151
                                for (int i = 0; i < getDataSource().getDatasetCount(); i++)
1152
                                        getDataSource().saveObjectToRmf(i, RasterDataset.class, getDataSource().getDataset(i)[0]);
1153
                        } catch (RmfSerializerException e) {
1154
                                RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
1155
                        }
1156

    
1157
                if (this.isRemoveRasterFlag()) {
1158
                        String[] files = getFileName().clone();
1159
                        if (dataset != null)
1160
                                dataset.close();
1161
                        if (bufferFactory != null)
1162
                                bufferFactory.free();
1163
                        bufferFactory = null;
1164
                        dataset = null;
1165
                        render = null;
1166
                        try {
1167
                                enableClosed();
1168
                        } catch (NotAvailableStateException e1) {
1169
                                // No se ha podido cambiar el estado de la capa a cerrado
1170
                        }
1171

    
1172
                        // System.gc();
1173
                        this.setRemoveRasterFlag(true);
1174

    
1175
                        for (int i = 0; i < files.length; i++) {
1176
                                File file = new File(files[i]);
1177
                                File dirTemp = RasterLibrary.getTemporalFile();
1178
                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
1179
                                        file.delete();
1180

    
1181
                                        // Borramos todos los ficheros que puedan tener relacion con el fichero actual
1182
                                        String basefile = file.getName();
1183
                                        File basepath = file.getParentFile();
1184
                                        int last = basefile.lastIndexOf(".");
1185
                                        if (last != -1)
1186
                                                basefile = basefile.substring(0, last + 1);
1187
                                        File[] list = basepath.listFiles();
1188
                                        for (int j = 0; j < list.length; j++)
1189
                                                if (list[j].getName().startsWith(basefile))
1190
                                                        list[j].delete();
1191
                                }
1192
                        }
1193
                }
1194
                updateDrawVersion();
1195
                return super.layerListeners.remove(o);
1196
        }
1197

    
1198
        /**
1199
         * @return Returns the removeRasterFlag.
1200
         */
1201
        public boolean isRemoveRasterFlag() {
1202
                return removeRasterFlag;
1203
        }
1204

    
1205
        /**
1206
         * Asigna el valor del flag que dice si destruimos la memoria del raster
1207
         * al eliminarlo del TOC o  no.
1208
         * @param removeRasterFlag The removeRasterFlag to set.
1209
         */
1210
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
1211
                this.removeRasterFlag = removeRasterFlag;
1212
        }
1213

    
1214
        /*
1215
         * (non-Javadoc)
1216
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1217
         */
1218
        public ImageIcon getTocImageIcon() {
1219
                return new ImageIcon(getClass().getResource("images/map_ico_ok.gif"));
1220
        }
1221

    
1222
        /*
1223
         *  (non-Javadoc)
1224
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
1225
         */
1226
        public int[] getTileSize() {
1227
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
1228
                return size;
1229
        }
1230

    
1231
        /*
1232
         *  (non-Javadoc)
1233
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1234
         */
1235
        public boolean isTiled() {
1236
                return mustTileDraw;
1237
        }
1238

    
1239
        /**
1240
         * Obtiene el flag que dice si la imagen est? o no georreferenciada
1241
         * @return true si est? georreferenciada y false si no lo est?.
1242
         */
1243
        public boolean isGeoreferenced() {
1244
                return dataset.isGeoreferenced();
1245
        }
1246

    
1247
        /**
1248
         * Get datasource object
1249
         * @return
1250
         */
1251
        public BufferFactory getBufferFactory(){
1252
                return bufferFactory;
1253
        }
1254

    
1255
        /**
1256
         * Obtiene el valor NoData asociado al raster.
1257
         * @return double
1258
         */
1259
        public double getNoDataValue() {
1260
                if (dataset == null)
1261
                        return RasterLibrary.defaultNoDataValue;
1262
                return dataset.getNoDataValue();
1263
        }
1264

    
1265
        /**
1266
         * Asigna el valor no data asociado a la capa
1267
         * @param nd
1268
         */
1269
        public void setNoDataValue(double nd) {
1270
                if (bufferFactory != null)
1271
                        bufferFactory.setNoDataToFill(nd);
1272
                if (dataset != null)
1273
                        dataset.setNoDataValue(nd);
1274
        }
1275

    
1276
        /*
1277
         * (non-Javadoc)
1278
         * @see org.gvsig.fmap.raster.IRasterOperations#getPXHeight()
1279
         */
1280
        public double getPxHeight() {
1281
                return dataset.getHeight();
1282
        }
1283

    
1284
        /*
1285
         * (non-Javadoc)
1286
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
1287
         */
1288
        public double getPxWidth() {
1289
                return dataset.getWidth();
1290
        }
1291

    
1292
        /*
1293
         * (non-Javadoc)
1294
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCHeight()
1295
         */
1296
        public double getWCHeight() {
1297
                return getFullEnvelope().getMaximum(1);
1298
        }
1299

    
1300
        /*
1301
         * (non-Javadoc)
1302
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
1303
         */
1304
        public double getWCWidth() {
1305
                return getFullEnvelope().getMaximum(0);
1306
        }
1307

    
1308
        /*
1309
         * (non-Javadoc)
1310
         * @see org.gvsig.fmap.raster.IRasterFile#getFileSize()
1311
         */
1312
        public long[] getFileSize(){
1313
                int nFiles = dataset.getDatasetCount();
1314
                long[] s = new long[nFiles];
1315
                for (int i = 0; i < nFiles; i++)
1316
                        s[i] = dataset.getDataset(i)[0].getFileSize();
1317
                return s;
1318
        }
1319

    
1320
        /*
1321
         * (non-Javadoc)
1322
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
1323
         */
1324
        public String[] getFileName(){
1325
                int nFiles = 0;
1326
                if (dataset != null)
1327
                        nFiles = dataset.getDatasetCount();
1328
                String[] s = new String[nFiles];
1329
                for (int i = 0; i < nFiles; i++)
1330
                        s[i] = dataset.getDataset(i)[0].getFName();
1331
                return s;
1332
        }
1333

    
1334
        /*
1335
         * (non-Javadoc)
1336
         * @see org.gvsig.fmap.raster.IRasterFile#getFileCount()
1337
         */
1338
        public int getFileCount() {
1339
                return (dataset != null) ? dataset.getDatasetCount() : 0;
1340
        }
1341

    
1342
        /*
1343
         * (non-Javadoc)
1344
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
1345
         */
1346
        public String getFileFormat() {
1347
                String fName = dataset.getDataset(0)[0].getFName();
1348
                int index = fName.lastIndexOf(".") + 1;
1349
                String ext = null;
1350
                if (index > 0)
1351
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
1352
                return ext;
1353
        }
1354

    
1355
        /*
1356
         * (non-Javadoc)
1357
         * @see org.gvsig.fmap.raster.IRasterOperations#getBandCount()
1358
         */
1359
        public int getBandCount() {
1360
                return (dataset != null) ? dataset.getBandCount() : 0;
1361
        }
1362

    
1363
        /*
1364
         * (non-Javadoc)
1365
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1366
         */
1367
        public int[] getDataType() {
1368
                return dataset.getDataType();
1369
        }
1370

    
1371
        /*
1372
         * (non-Javadoc)
1373
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
1374
         */
1375
        public GridTransparency getRenderTransparency() {
1376
                return getRender().getLastTransparency();
1377
        }
1378

    
1379
        /*
1380
         * (non-Javadoc)
1381
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1382
         */
1383
        public RasterFilterList getRenderFilterList() {
1384
                return getRender().getFilterList();
1385
        }
1386

    
1387
        /*
1388
         * (non-Javadoc)
1389
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
1390
         */
1391
        public int[] getRenderBands() {
1392
                return getRender().getRenderBands();
1393
        }
1394

    
1395
        /*
1396
         * (non-Javadoc)
1397
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
1398
         */
1399
        public void setRenderBands(int[] renderBands) {
1400
                getRender().setRenderBands(renderBands);
1401
        }
1402

    
1403
        /*
1404
         * (non-Javadoc)
1405
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderFilterList(org.gvsig.raster.grid.filter.RasterFilterList)
1406
         */
1407
        public void setRenderFilterList(RasterFilterList filterList) {
1408
                getRender().setFilterList(filterList);
1409
        }
1410

    
1411
        /*
1412
         * (non-Javadoc)
1413
         * @see org.gvsig.raster.hierarchy.IRasterDataset#getDataSource()
1414
         */
1415
        public IRasterDataSource getDataSource() {
1416
                return dataset;
1417
        }
1418

    
1419
        /*
1420
         * (non-Javadoc)
1421
         * @see org.gvsig.fmap.raster.IRasterDataset#addFile(java.lang.String)
1422
         */
1423
        public void addFile(String fileName) throws NotSupportedExtensionException, RasterDriverException {
1424
                if (getRender() != null)
1425
                        bufferFactory.addFile(RasterDataset.open(getProjection(), fileName));
1426
        }
1427

    
1428
        /*
1429
         * (non-Javadoc)
1430
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
1431
         */
1432
        public void delFile(String fileName) {
1433
                if (getRender() != null)
1434
                        bufferFactory.removeFile(fileName);
1435
        }
1436

    
1437
        /*
1438
         * (non-Javadoc)
1439
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
1440
         */
1441
        public Object getInfo(String key) {
1442
                if (key.equals("DriverName"))
1443
                        return "gvSIG Raster Driver";
1444
                return null;
1445
        }
1446

    
1447
        /*
1448
         * (non-Javadoc)
1449
         * @see org.gvsig.raster.shared.IRasterOperations#getMetadata()
1450
         */
1451
        public DatasetMetadata[] getMetadata() {
1452
                int count = dataset.getDatasetCount();
1453
                DatasetMetadata[] metadata = new DatasetMetadata[count];
1454
                for (int i = 0; i < count; i++)
1455
                        metadata[i] = dataset.getDataset(i)[0].getMetadata();
1456
                return metadata;
1457
        }
1458

    
1459
        /*
1460
         * (non-Javadoc)
1461
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
1462
         */
1463
        public int[] getBandCountFromDataset() {
1464
                int count = dataset.getDatasetCount();
1465
                int[] bands = new int[count];
1466
                for (int i = 0; i < count; i++)
1467
                        bands[i] = dataset.getDataset(i)[0].getBandCount();
1468
                return bands;
1469
        }
1470

    
1471
        /*
1472
         * (non-Javadoc)
1473
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1474
         */
1475
        public String getColorInterpretation(int band, int dataset) {
1476
                if (this.dataset.getDataset(dataset)[0].getColorInterpretation().get(band) == null)
1477
                        return "Undefined";
1478
                return this.dataset.getDataset(dataset)[0].getColorInterpretation().get(band);
1479
        }
1480

    
1481
        /*
1482
         * (non-Javadoc)
1483
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
1484
         */
1485
        public String getWktProjection() throws RasterDriverException {
1486
                return dataset.getWktProjection();
1487
        }
1488

    
1489
        /**
1490
         * Metodo para consultar si una capa puede ser un RGB. Suponemos que es un RGB
1491
         * si el tipo de datos es de tipo byte y su interpretacion de color tiene
1492
         * asignada los tres colores.
1493
         * @return boolean
1494
         */
1495
        public boolean isRGB() {
1496
                if ((dataset == null) || (render == null))
1497
                        return false;
1498

    
1499
// Quitado pq no necesariamente tiene pq tener 3 bandas para ser RGB
1500
//                if (dataset.getBandCount() < 3)
1501
//                        return false;
1502

    
1503
                if (dataset.getDataType()[0] != IBuffer.TYPE_BYTE)
1504
                        return false;
1505

    
1506
                boolean R = false;
1507
                boolean G = false;
1508
                boolean B = false;
1509

    
1510
                int[] renderBands = render.getRenderBands();
1511
                for (int i = 0; i < renderBands.length; i++)
1512
                        if (renderBands[i] >= 0)
1513
                                switch (i) {
1514
                                        case 0:
1515
                                                R = true;
1516
                                                break;
1517
                                        case 1:
1518
                                                G = true;
1519
                                                break;
1520
                                        case 2:
1521
                                                B = true;
1522
                                                break;
1523
                                }
1524

    
1525
                if (R && G && B)
1526
                        return true;
1527

    
1528
                return false;
1529
        }
1530

    
1531
        /**
1532
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1533
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1534
         * cacheado o no dependiendo del tama?o de esta.
1535
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1536
         * @return Grid.
1537
         * @throws InterruptedException
1538
         */
1539
        public Grid getFullGrid(boolean interpolated) throws GridException, InterruptedException {
1540
                BufferFactory bf = getBufferFactory();
1541
                bf.clearDrawableBand();
1542
                bf.setAllDrawableBands();
1543
                try {
1544
                        bf.setAreaOfInterest();
1545
                } catch (RasterDriverException e) {
1546
                        throw new GridException("Error reading buffer");
1547
                }
1548
                return new Grid(bf, interpolated);
1549
        }
1550

    
1551
        /**
1552
         * Obtiene el grid de la capa completa. Esta llamada devuelve un buffer de solo lectura
1553
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1554
         * @return Grid.
1555
         * @throws InterruptedException
1556
         */
1557
        public Grid getReadOnlyFullGrid(boolean interpolated) throws GridException, InterruptedException {
1558
                BufferFactory bf = getBufferFactory();
1559
                bf.setReadOnly(true);
1560
                bf.clearDrawableBand();
1561
                bf.setAllDrawableBands();
1562
                try {
1563
                        bf.setAreaOfInterest();
1564
                } catch (RasterDriverException e) {
1565
                        throw new GridException("Error reading buffer");
1566
                }
1567
                return new Grid(bf, interpolated);
1568
        }
1569

    
1570
        /**
1571
         * Obtiene el tama?o de celda de la fuente de datos
1572
         * @return double con el tama?o de celda
1573
         */
1574
        public double getCellSize() {
1575
                return (getDataSource() != null) ? getDataSource().getCellSize() : 1;
1576
        }
1577

    
1578
        /*
1579
         * (non-Javadoc)
1580
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1581
         */
1582
        public Extent getFullRasterExtent() {
1583
                return this.getDataSource().getExtent();
1584
        }
1585

    
1586

    
1587
        /**
1588
         * Devuelve el fichero asociado a la capa o null si no tiene.
1589
         * @return Fichero.
1590
         */
1591
        public File getFile() {
1592
                return (params instanceof File) ? ((File)params) : null;
1593
        }
1594

    
1595
        /**
1596
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1597
         * @param file Fichero a consultar
1598
         * @return true si es aceptado y false si no lo es.
1599
         */
1600
        public static boolean isFileAccepted(File file) {
1601
                return RasterDataset.fileIsSupported(file.getName());
1602
        }
1603

    
1604
        /*
1605
         * (non-Javadoc)
1606
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1607
         */
1608
        public boolean existColorTable() {
1609
                return getRender().existColorTable();
1610
        }
1611

    
1612
        /*
1613
         * (non-Javadoc)
1614
         * @see org.gvsig.raster.hierarchy.IRasterRendering#existsAlphaBand()
1615
         */
1616
        public boolean existsAlphaBand() {
1617
                if(getDataSource().getColorInterpretation() != null)
1618
                        return getDataSource().getColorInterpretation().isAlphaBand();
1619
                else
1620
                        return false;
1621
        }
1622

    
1623
        /*
1624
         * (non-Javadoc)
1625
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getAlphaBandNumber()
1626
         */
1627
        public int getAlphaBandNumber() {
1628
                if(getDataSource().getColorInterpretation() != null)
1629
                        return getDataSource().getColorInterpretation().getBand(DatasetColorInterpretation.ALPHA_BAND);
1630
                return -1;
1631
        }
1632

    
1633
        /**
1634
         * Define la ultima leyenda valida de la capa o se pone a null para que la
1635
         * capa busque una leyenda valida.
1636
         * @param ct
1637
         */
1638
        public void setLastLegend(ColorTable ct) {
1639
                lastLegend = ColorTableLegend.createLegend(ct);
1640
        }
1641

    
1642
        /**
1643
         * Devuelve la Leyenda de la capa.
1644
         * @return Leyenda.
1645
         */
1646
        public ILegend getLegend() {
1647
                if (lastLegend != null)
1648
                        return lastLegend;
1649

    
1650
                return null;
1651
        }
1652

    
1653
        /*
1654
         * (non-Javadoc)
1655
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1656
         */
1657
        public void addLegendListener(LegendListener listener) {
1658
                layerChangeSupport.addLayerListener(listener);
1659
        }
1660

    
1661
        /*
1662
         *  (non-Javadoc)
1663
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1664
         */
1665
        public int getShapeType() {
1666
                return FShape.POLYGON;
1667
        }
1668

    
1669
        /*
1670
         * (non-Javadoc)
1671
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1672
         */
1673
        public void removeLegendListener(LegendListener listener) {
1674
                layerChangeSupport.removeLayerListener(listener);
1675
        }
1676

    
1677
        /**
1678
         * Metodo que obtiene si un punto cae dentro de los l?mites de la capa
1679
         * o fuera de ellos.
1680
         * @param p Punto a calcular
1681
         * @return true si est? dentro de los l?mites y false si est? fuera
1682
         */
1683
        public boolean isInside(Point2D p) {
1684
                 return getDataSource().isInside(p);
1685
        }
1686

    
1687
        /**
1688
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1689
         * @return AffineTransform
1690
         */
1691
        public AffineTransform getAffineTransform(int band) {
1692
                return getDataSource().getAffineTransform(band);
1693
        }
1694

    
1695
        /**
1696
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1697
         * @return AffineTransform
1698
         */
1699
        public AffineTransform getAffineTransform() {
1700
                return getDataSource().getAffineTransform(0);
1701
        }
1702

    
1703
        /**
1704
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista
1705
         * @param transf
1706
         */
1707
        public void setAffineTransform(AffineTransform transf) {
1708
                if(transf == null)
1709
                        return;
1710
                affineTransformList.add(transf);
1711
                getDataSource().setAffineTransform(transf);
1712
                updateDrawVersion();
1713
        }
1714

    
1715
        /**
1716
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista.
1717
         * Esta versi?n no guarda en el historico.
1718
         * @param transf
1719
         */
1720
        public void setAT(AffineTransform transf) {
1721
                getDataSource().setAffineTransform(transf);
1722
                updateDrawVersion();
1723
        }
1724

    
1725
        /**
1726
         * Obtiene la lista de transformaciones que se han ido aplicando al raster.
1727
         * @return Historical. Lista de AffineTransform
1728
         */
1729
        public Historical getAffineTransformHistorical() {
1730
                return this.affineTransformList;
1731
        }
1732

    
1733
        /**
1734
         * Salva la georreferenciaci?n a fichero rmf.
1735
         * @param fName
1736
         * @throws RmfSerializerException
1737
         */
1738
        public void saveGeoToRmf() throws RmfSerializerException {
1739
                if (!isOpen())
1740
                        return;
1741

    
1742
                // Guardamos la GeoReferenciacion de cada dataset
1743
                for (int i = 0; i < getDataSource().getDatasetCount(); i++)
1744
                        getDataSource().saveObjectToRmf(i, RasterDataset.class, getDataSource().getDataset(i)[0]);
1745

    
1746
                affineTransformList.clear();
1747
                affineTransformList.add(this.getAffineTransform());
1748
        }
1749

    
1750
        /*
1751
         * (non-Javadoc)
1752
         * @see org.gvsig.fmap.raster.layers.IRasterLayerActions#isActionEnabled(int)
1753
         */
1754
        public boolean isActionEnabled(int action) {
1755
                switch (action) {
1756
                        case IRasterLayerActions.BANDS_FILE_LIST:
1757
                                if (existColorTable())
1758
                                        return false;
1759
                                break;
1760
                        case IRasterLayerActions.BANDS_RGB:
1761
                                if (existColorTable())
1762
                                        return false;
1763
                                break;
1764
                        case IRasterLayerActions.REPROJECT:
1765
                                if (!isReproyectable())
1766
                                        return false;
1767
                                break;
1768
                        case IRasterLayerActions.CREATEOVERVIEWS:
1769
                                return overviewsSupport();
1770
                        case IRasterLayerActions.OPACITY:
1771
                        case IRasterLayerActions.TRANSPARENCY:
1772
                        case IRasterLayerActions.BRIGHTNESSCONTRAST:
1773
                        case IRasterLayerActions.ENHANCED:
1774
                        case IRasterLayerActions.PANSHARPENING:
1775
                        case IRasterLayerActions.SELECT_LAYER:
1776
                        case IRasterLayerActions.SAVE_COLORINTERP:
1777
                                return true;
1778
                }
1779
                return true;
1780
        }
1781

    
1782
        /*
1783
         * (non-Javadoc)
1784
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1785
         */
1786
        public void setVisible(boolean visibility) {
1787
                if(visibility)
1788
                        state.disableStopped();
1789
                else
1790
                        enableStopped();
1791

    
1792
                if(isAwake() || isClosed())
1793
                        try {
1794
                                this.load();
1795
                        } catch (LoadLayerException e) {
1796
                                e.printStackTrace();
1797
                        }
1798

    
1799
                /*
1800
                 * Cuando se modifica la visibilidad de una capa raster se hace un updateDrawVersion de todas las
1801
                 * capas raster de ese MapContext. Esto es porque la estrategia utilizada por RasterDrawStrategy hace
1802
                 * que se cacheen en blanco las capas raster que est?n ocultas debajo de otras. Al hacer invisibles las
1803
                 * de arriba la cache que estaba en blanco hace que no se pinte nada. Para evitar esto las marcamos todas
1804
                 * como que han sido modificadas para que se vuelvan a leer.
1805
                 */
1806
                if(getMapContext() != null) {
1807
                        ArrayList listLayers = new ArrayList();
1808
                        listLayers = RasterDrawStrategy.getLayerList(getMapContext().getLayers(), listLayers);
1809
                        for (int i = 0; i < listLayers.size(); i++)
1810
                                if(listLayers.get(i) instanceof FLyrRasterSE)
1811
                                        ((FLyrRasterSE)listLayers.get(i)).updateDrawVersion();
1812
                }
1813

    
1814
                super.setVisible(visibility);
1815
        }
1816

    
1817
        /**
1818
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1819
         * @return valor de transparencia
1820
         */
1821
        public int getTransparency() {
1822
                try {
1823
                        return getRenderTransparency().getOpacity();
1824
                } catch (NullPointerException e) {
1825
                        return super.getTransparency();
1826
                }
1827
        }
1828

    
1829
        /**
1830
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1831
         * o no.
1832
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1833
         */
1834
        public boolean isTransparent() {
1835
                return getRenderTransparency().isTransparencyActive();
1836
        }
1837

    
1838
        /**
1839
         * Asigna la transparencia de la siguiente renderizaci?n
1840
         * @param valor de transparencia
1841
         */
1842
        public void setTransparency(int trans) {
1843
                super.setTransparency(trans);
1844
                try {
1845
                        getRenderTransparency().setOpacity(trans);
1846
                        getRenderTransparency().activeTransparency();
1847
                } catch (NullPointerException e) {
1848
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1849
                }
1850
        }
1851

    
1852
        /*
1853
         * (non-Javadoc)
1854
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getLastRenderBuffer()
1855
         */
1856
        public IBuffer getLastRenderBuffer() {
1857
                return getRender().getLastRenderBuffer();
1858
        }
1859

    
1860
        /**
1861
         *
1862
         * @return ROIs asociadas a la capa raster.
1863
         */
1864
        public ArrayList<ROI> getRois() {
1865
                return rois;
1866
        }
1867

    
1868
        /**
1869
         * Establece las ROI asociadas a la capa raster.
1870
         *
1871
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1872
         */
1873
        public void setRois(ArrayList<ROI> rois) {
1874
                this.rois = rois;
1875
        }
1876

    
1877
        /**
1878
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1879
         * devolver? null.
1880
         * @return TreeMap con la lista de capas a dibujar
1881
         */
1882
        public HashMap getRasterStrategy() {
1883
                if(strategy != null)
1884
                        return strategy.getStrategy();
1885
                return null;
1886
        }
1887

    
1888
        /**
1889
         * Devuelve el tipo de valor de NoData asociado a la capa.
1890
         * Sirve para diferenciar los estados seleccionados por el usuario. Siendo
1891
         * estos '0: Sin Valor NoData', '1: NoData de Capa'(Por defecto) y '2: Personalizado'
1892
         */
1893
        /**
1894
         * @return the noDataType
1895
         */
1896
        public int getNoDataType() {
1897
                return noDataType;
1898
        }
1899

    
1900
        /**
1901
         * @param noDataType the noDataType to set
1902
         */
1903
        public void setNoDataType(int noDataType) {
1904
                this.noDataType = noDataType;
1905
                if (dataset != null)
1906
                        dataset.setNoDataEnabled(noDataType != RasterLibrary.NODATATYPE_DISABLED);
1907
        }
1908

    
1909
        /**
1910
         * @return the configuration
1911
         */
1912
        static public IConfiguration getConfiguration() {
1913
                return configuration;
1914
        }
1915

    
1916
        /**
1917
         * @param configuration the configuration to set
1918
         */
1919
        static public void setConfiguration(IConfiguration configuration) {
1920
                FLyrRasterSE.configuration = configuration;
1921
        }
1922

    
1923
        /*
1924
         * (non-Javadoc)
1925
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#reload()
1926
         */
1927
        public void reload() throws ReloadLayerException {
1928
                try {
1929
                        super.reload();
1930
                        if (getMapContext() == null)
1931
                                return;
1932
                        if (isStopped())
1933
                                disableStopped();
1934
                        load();
1935
                        getMapContext().invalidate();
1936
                } catch (LoadLayerException e) {
1937
                        setAvailable(false);
1938
                        throw new ReloadLayerException(getName(), e);
1939
                }
1940
        }
1941

    
1942
        /**
1943
         * Devuelve si la capa tiene soporte para poder generar overviews
1944
         * @return
1945
         */
1946
        public boolean overviewsSupport() {
1947
                if ((getDataSource() != null) && (getDataSource().overviewsSupport()))
1948
                        return true;
1949

    
1950
                return false;
1951
        }
1952

    
1953
        /**
1954
         * Devuelve si la asignacion de las bandas a renderizar representa una capa
1955
         * en escala de grises
1956
         * @return
1957
         */
1958
        public boolean isRenderingAsGray() {
1959
                int[] renderBands = getRenderBands();
1960
                if ((renderBands != null) && (renderBands.length == 3) && (renderBands[0] >= 0) &&
1961
                                (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2]))
1962
                        return true;
1963
                return false;
1964
        }
1965

    
1966
        /*
1967
         * (non-Javadoc)
1968
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
1969
         */
1970
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1971
                updateDrawVersion();
1972
        }
1973

    
1974
        /*****************************************************/
1975
        //Utils
1976

    
1977
        /**
1978
         * Ajusta las coordenadas especificadas en el par?metro al ?rea m?xima
1979
         * del raster en p?xeles.
1980
         * @param req Punto a ajustar dentro del extener del raster
1981
         */
1982
        public Point2D adjustWorldRequest(Point2D req) {
1983
                Envelope ext = null;
1984

    
1985
                ext = getFullEnvelope();
1986
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
1987
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
1988
                return req;
1989
        }
1990

    
1991
        /*
1992
         * (non-Javadoc)
1993
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#cloneLayer()
1994
         */
1995
        public FLayer cloneLayer() throws Exception {
1996
                FLyrRasterSE newLayer = FLyrRasterSE.createLayer(this.getName(), params, this.getProjection());
1997
                for (int i = 0; i < dataset.getDatasetCount(); i++) {
1998
                        String name = dataset.getDataset(i)[0].getFName();
1999
                        if (!(dataset instanceof CompositeDataset) && !name.equals(this.getName()))
2000
                                newLayer.addFile(name);
2001
                }
2002
                ArrayList filters = getRender().getFilterList().getStatusCloned();
2003

    
2004
                //Hacemos una copia de las bandas a renderizar
2005
                if(getRenderBands() != null) {
2006
                        int[] rb = new int[getRenderBands().length];
2007
                        for (int i = 0; i < rb.length; i++)
2008
                                rb[i] = getRenderBands()[i];
2009
                        newLayer.setRenderBands(rb);
2010
                }
2011

    
2012
                //Asignamos el entorno
2013
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
2014
                newLayer.getRender().getFilterList().setStatus(filters);
2015

    
2016
                // Asignamos los valores noData del original
2017
                newLayer.setNoDataValue(getNoDataValue());
2018
                newLayer.setNoDataType(getNoDataType());
2019
                newLayer.applyNoData();
2020

    
2021
                return newLayer;
2022
        }
2023

    
2024
        /*****************************************************/
2025

    
2026
        public void disableStopped() {state.disableStopped();}
2027

    
2028
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
2029

    
2030
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
2031

    
2032
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
2033

    
2034
        public void enableStopped() {state.enableStopped();}
2035

    
2036
        public boolean isAwake() {return state.isAwake();}
2037

    
2038
        public boolean isClosed() {return state.isClosed();}
2039

    
2040
        public boolean isOpen() {return state.isOpen();}
2041

    
2042
        public boolean isStopped() {return state.isStopped();}
2043

    
2044

    
2045
        public Set getMetadataChildren() {
2046
                // TODO Auto-generated method stub
2047
                return null;
2048
        }
2049

    
2050
        public Object getMetadataID() {
2051
                // TODO Auto-generated method stub
2052
                return null;
2053
        }
2054

    
2055
        public String getMetadataName() {
2056
                // TODO Auto-generated method stub
2057
                return null;
2058
        }
2059

    
2060
        /*
2061
         * (non-Javadoc)
2062
         * @see org.gvsig.fmap.mapcontext.layers.operations.SingleLayer#getDataStore()
2063
         */
2064
        public DataStore getDataStore() {
2065
                return this.store;
2066
        }
2067

    
2068
        /*
2069
         * (non-Javadoc)
2070
         * @see org.gvsig.fmap.mapcontext.layers.operations.SingleLayer#setDataStore(org.gvsig.fmap.dal.DataStore)
2071
         */
2072
        public void setDataStore(DataStore dataStore) throws LoadLayerException {
2073
                this.store = (CoverageStore) dataStore;
2074
                // TODO temporal
2075
                RasterStoreParameters params = (RasterStoreParameters)store.getParameters();
2076
                this.setLoadParams(params.getFile());
2077
                if (params.getSRS() != null)
2078
                        this.setProjection(params.getSRS());
2079
                this.load();
2080
        }
2081

    
2082
}