Statistics
| Revision:

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

History | View | Annotate | Download (64.8 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2007 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 */
19
package org.gvsig.fmap.raster.layers;
20

    
21
import java.awt.Dimension;
22
import java.awt.Graphics2D;
23
import java.awt.Point;
24
import java.awt.Rectangle;
25
import java.awt.geom.AffineTransform;
26
import java.awt.geom.NoninvertibleTransformException;
27
import java.awt.geom.Point2D;
28
import java.awt.geom.Rectangle2D;
29
import java.awt.image.BufferedImage;
30
import java.io.File;
31
import java.io.IOException;
32
import java.lang.reflect.Constructor;
33
import java.lang.reflect.InvocationTargetException;
34
import java.util.ArrayList;
35
import java.util.HashMap;
36
import java.util.Set;
37

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

    
120

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
418
                if(getDataSource() == null)
419
                        return;
420
                
421
                getDataSource().resetNoDataValue();
422
                applyNoData();
423
                GridTransparency gridTransparency = new GridTransparency(getDataSource().getTransparencyFilesStatus());
424

    
425
                filterList.setInitDataType(getDataType()[0]);
426
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
427

    
428
                // Quitamos la leyenda
429
                lastLegend = null;
430

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

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

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

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

    
473
                IStatistics stats = getDataSource().getStatistics();
474

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

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

    
492
                                                        colorTable.createColorTableInRange(stats.getMinimun(), stats.getMaximun(), true);
493

    
494
                                                        GridPalette p = new GridPalette(colorTable);
495
                                                        setLastLegend(p);
496

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

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

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

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

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

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

    
554
                try {
555
                        if (!isOpen())
556
                                return;
557

    
558
                        enableStopped();
559
                        // callLegendChanged(null);
560

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
949
                return xml;
950
        }
951

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

    
965
                try {
966
                        params = new File(xml.getStringProperty("file"));
967

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

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

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

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

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

    
1018
                }
1019
        }
1020

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

    
1027
                if (!isOpen() || !isVisible() || !isWithinScale(scale))
1028
                        return;
1029

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

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

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

    
1047

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

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

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

    
1069
                int numW, numH;
1070
                int stepX, stepY;
1071
                int xProv, yProv;
1072
                int A = 1500;
1073
                int H = 1500;
1074
                int altoAux, anchoAux;
1075

    
1076
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
1077

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

    
1083
                double[] srcPts = new double[8];
1084
                double[] dstPts = new double[8];
1085

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

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

    
1100
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
1101

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

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

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

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

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

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

    
1176
                        // System.gc();
1177
                        this.setRemoveRasterFlag(true);
1178

    
1179
                        for (int i = 0; i < files.length; i++) {
1180
                                File file = new File(files[i]);
1181
                                File dirTemp = RasterLibrary.getTemporalFile();
1182
                                if (dirTemp.compareTo(file.getParentFile()) == 0) {
1183
                                        file.delete();
1184

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

    
1202
        /**
1203
         * @return Returns the removeRasterFlag.
1204
         */
1205
        public boolean isRemoveRasterFlag() {
1206
                return removeRasterFlag;
1207
        }
1208

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

    
1218
        /*
1219
         * (non-Javadoc)
1220
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
1221
         */
1222
        public String getTocImageIcon() {
1223
                return "map-ico-ok";
1224
        }
1225

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

    
1235
        /*
1236
         *  (non-Javadoc)
1237
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
1238
         */
1239
        public boolean isTiled() {
1240
                return mustTileDraw;
1241
        }
1242

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

    
1251
        /**
1252
         * Get datasource object
1253
         * @return
1254
         */
1255
        public BufferFactory getBufferFactory(){
1256
                return bufferFactory;
1257
        }
1258

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

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

    
1280
        /*
1281
         * (non-Javadoc)
1282
         * @see org.gvsig.fmap.raster.IRasterOperations#getPXHeight()
1283
         */
1284
        public double getPxHeight() {
1285
                return dataset.getHeight();
1286
        }
1287

    
1288
        /*
1289
         * (non-Javadoc)
1290
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
1291
         */
1292
        public double getPxWidth() {
1293
                return dataset.getWidth();
1294
        }
1295

    
1296
        /*
1297
         * (non-Javadoc)
1298
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCHeight()
1299
         */
1300
        public double getWCHeight() {
1301
                return getFullEnvelope().getMaximum(1);
1302
        }
1303

    
1304
        /*
1305
         * (non-Javadoc)
1306
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
1307
         */
1308
        public double getWCWidth() {
1309
                return getFullEnvelope().getMaximum(0);
1310
        }
1311

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

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

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

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

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

    
1367
        /*
1368
         * (non-Javadoc)
1369
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
1370
         */
1371
        public int[] getDataType() {
1372
                return dataset.getDataType();
1373
        }
1374

    
1375
        /*
1376
         * (non-Javadoc)
1377
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
1378
         */
1379
        public GridTransparency getRenderTransparency() {
1380
                return getRender().getLastTransparency();
1381
        }
1382

    
1383
        /*
1384
         * (non-Javadoc)
1385
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
1386
         */
1387
        public RasterFilterList getRenderFilterList() {
1388
                return getRender().getFilterList();
1389
        }
1390

    
1391
        /*
1392
         * (non-Javadoc)
1393
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getRenderBands()
1394
         */
1395
        public int[] getRenderBands() {
1396
                return getRender().getRenderBands();
1397
        }
1398

    
1399
        /*
1400
         * (non-Javadoc)
1401
         * @see org.gvsig.raster.hierarchy.IRasterRendering#setRenderBands(int[])
1402
         */
1403
        public void setRenderBands(int[] renderBands) {
1404
                getRender().setRenderBands(renderBands);
1405
        }
1406

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

    
1415
        /*
1416
         * (non-Javadoc)
1417
         * @see org.gvsig.raster.hierarchy.IRasterDataset#getDataSource()
1418
         */
1419
        public IRasterDataSource getDataSource() {
1420
                return dataset;
1421
        }
1422

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

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

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

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

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

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

    
1485
        /*
1486
         * (non-Javadoc)
1487
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
1488
         */
1489
        public String getWktProjection() throws RasterDriverException {
1490
                return dataset.getWktProjection();
1491
        }
1492

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

    
1503
// Quitado pq no necesariamente tiene pq tener 3 bandas para ser RGB
1504
//                if (dataset.getBandCount() < 3)
1505
//                        return false;
1506

    
1507
                if (dataset.getDataType()[0] != IBuffer.TYPE_BYTE)
1508
                        return false;
1509

    
1510
                boolean R = false;
1511
                boolean G = false;
1512
                boolean B = false;
1513

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

    
1529
                if (R && G && B)
1530
                        return true;
1531

    
1532
                return false;
1533
        }
1534

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

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

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

    
1582
        /*
1583
         * (non-Javadoc)
1584
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1585
         */
1586
        public Extent getFullRasterExtent() {
1587
                return this.getDataSource().getExtent();
1588
        }
1589

    
1590

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

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

    
1608
        /*
1609
         * (non-Javadoc)
1610
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1611
         */
1612
        public boolean existColorTable() {
1613
                return getRender().existColorTable();
1614
        }
1615

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

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

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

    
1646
        /**
1647
         * Devuelve la Leyenda de la capa.
1648
         * @return Leyenda.
1649
         */
1650
        public ILegend getLegend() {
1651
                if (lastLegend != null)
1652
                        return lastLegend;
1653

    
1654
                return null;
1655
        }
1656

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

    
1665
        /*
1666
         *  (non-Javadoc)
1667
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1668
         */
1669
        public int getShapeType() {
1670
                return TYPES.SURFACE;
1671
        }
1672

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

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

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

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

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

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

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

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

    
1746
                // Guardamos la GeoReferenciacion de cada dataset
1747
                for (int i = 0; i < getDataSource().getDatasetCount(); i++)
1748
                        getDataSource().saveObjectToRmf(i, RasterDataset.class, getDataSource().getDataset(i)[0]);
1749

    
1750
                affineTransformList.clear();
1751
                affineTransformList.add(this.getAffineTransform());
1752
        }
1753

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

    
1788
        /*
1789
         * (non-Javadoc)
1790
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setVisible(boolean)
1791
         */
1792
        public void setVisible(boolean visibility) {
1793
                if(visibility)
1794
                        state.disableStopped();
1795
                else
1796
                        enableStopped();
1797

    
1798
                if(isAwake() || isClosed())
1799
                        try {
1800
                                this.load();
1801
                        } catch (LoadLayerException e) {
1802
                                e.printStackTrace();
1803
                        }
1804

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

    
1820
                super.setVisible(visibility);
1821
        }
1822

    
1823
        /**
1824
         * Consulta la transparencia asignada en la ?ltima renderizaci?n de la capa
1825
         * @return valor de transparencia
1826
         */
1827
        public int getTransparency() {
1828
                try {
1829
                        return getRenderTransparency().getOpacity();
1830
                } catch (NullPointerException e) {
1831
                        return super.getTransparency();
1832
                }
1833
        }
1834

    
1835
        /**
1836
         * Consulta si tiene aplicada alguna transparencia en la ?ltima renderizaci?n
1837
         * o no.
1838
         * @return true si se aplic? alguna transparencia en la ?ltima renderizaci?n.
1839
         */
1840
        public boolean isTransparent() {
1841
                return getRenderTransparency().isTransparencyActive();
1842
        }
1843

    
1844
        /**
1845
         * Asigna la transparencia de la siguiente renderizaci?n
1846
         * @param valor de transparencia
1847
         */
1848
        public void setTransparency(int trans) {
1849
                super.setTransparency(trans);
1850
                try {
1851
                        getRenderTransparency().setOpacity(trans);
1852
                        getRenderTransparency().activeTransparency();
1853
                } catch (NullPointerException e) {
1854
                        //Solo asigna la transparencia a la clase padre y no a la renderizaci?n
1855
                }
1856
        }
1857

    
1858
        /*
1859
         * (non-Javadoc)
1860
         * @see org.gvsig.raster.hierarchy.IRasterRendering#getLastRenderBuffer()
1861
         */
1862
        public IBuffer getLastRenderBuffer() {
1863
                return getRender().getLastRenderBuffer();
1864
        }
1865

    
1866
        /**
1867
         *
1868
         * @return ROIs asociadas a la capa raster.
1869
         */
1870
        public ArrayList<ROI> getRois() {
1871
                return rois;
1872
        }
1873

    
1874
        /**
1875
         * Establece las ROI asociadas a la capa raster.
1876
         *
1877
         * @param rois ArrayList de ROIs a asociar a la capa raster.
1878
         */
1879
        public void setRois(ArrayList<ROI> rois) {
1880
                this.rois = rois;
1881
        }
1882

    
1883
        /**
1884
         * Si ya tiene una estrategia de dibujado de raster calculada la devuelve, sino
1885
         * devolver? null.
1886
         * @return TreeMap con la lista de capas a dibujar
1887
         */
1888
        public HashMap getRasterStrategy() {
1889
                if(strategy != null)
1890
                        return strategy.getStrategy();
1891
                return null;
1892
        }
1893

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

    
1906
        /**
1907
         * @param noDataType the noDataType to set
1908
         */
1909
        public void setNoDataType(int noDataType) {
1910
                this.noDataType = noDataType;
1911
                if (dataset != null)
1912
                        dataset.setNoDataEnabled(noDataType != RasterLibrary.NODATATYPE_DISABLED);
1913
        }
1914

    
1915
        /**
1916
         * @return the configuration
1917
         */
1918
        static public IConfiguration getConfiguration() {
1919
                return configuration;
1920
        }
1921

    
1922
        /**
1923
         * @param configuration the configuration to set
1924
         */
1925
        static public void setConfiguration(IConfiguration configuration) {
1926
                FLyrRasterSE.configuration = configuration;
1927
        }
1928

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

    
1948
        /**
1949
         * Devuelve si la capa tiene soporte para poder generar overviews
1950
         * @return
1951
         */
1952
        public boolean overviewsSupport() {
1953
                if ((getDataSource() != null) && (getDataSource().overviewsSupport()))
1954
                        return true;
1955

    
1956
                return false;
1957
        }
1958

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

    
1972
        /*
1973
         * (non-Javadoc)
1974
         * @see org.gvsig.raster.grid.render.VisualPropertyListener#actionValueChanged(org.gvsig.raster.grid.render.VisualPropertyEvent)
1975
         */
1976
        public void visualPropertyValueChanged(VisualPropertyEvent e) {
1977
                updateDrawVersion();
1978
        }
1979

    
1980
        /*****************************************************/
1981
        //Utils
1982

    
1983
        /**
1984
         * Ajusta las coordenadas especificadas en el par?metro al ?rea m?xima
1985
         * del raster en p?xeles.
1986
         * @param req Punto a ajustar dentro del extener del raster
1987
         */
1988
        public Point2D adjustWorldRequest(Point2D req) {
1989
                Envelope ext = null;
1990

    
1991
                ext = getFullEnvelope();
1992
                req.setLocation(Math.max(ext.getMinimum(0), req.getX()), Math.max(ext.getMinimum(1), req.getY()));
1993
                req.setLocation(Math.min(ext.getMaximum(0), req.getX()), Math.min(ext.getMaximum(1), req.getY()));
1994
                return req;
1995
        }
1996

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

    
2010
                //Hacemos una copia de las bandas a renderizar
2011
                if(getRenderBands() != null) {
2012
                        int[] rb = new int[getRenderBands().length];
2013
                        for (int i = 0; i < rb.length; i++)
2014
                                rb[i] = getRenderBands()[i];
2015
                        newLayer.setRenderBands(rb);
2016
                }
2017

    
2018
                //Asignamos el entorno
2019
                newLayer.getRender().getFilterList().setEnv(getRender().getFilterList().getEnv());
2020
                newLayer.getRender().getFilterList().setStatus(filters);
2021

    
2022
                // Asignamos los valores noData del original
2023
                newLayer.setNoDataValue(getNoDataValue());
2024
                newLayer.setNoDataType(getNoDataType());
2025
                newLayer.applyNoData();
2026

    
2027
                return newLayer;
2028
        }
2029
        
2030
        /**
2031
         * Gets a layer which the source is a file
2032
         * @return
2033
         */
2034
        public FLayer getFileLayer() {
2035
                try {
2036
                        return cloneLayer();
2037
                } catch (Exception e) {
2038
                }
2039
                return null;
2040
        }
2041

    
2042
        /*****************************************************/
2043

    
2044
        public void disableStopped() {state.disableStopped();}
2045

    
2046
        public void enableAwake() throws NotAvailableStateException {state.enableAwake();}
2047

    
2048
        public void enableClosed() throws NotAvailableStateException {state.enableClosed();}
2049

    
2050
        public void enableOpen() throws NotAvailableStateException {state.enableOpen();}
2051

    
2052
        public void enableStopped() {state.enableStopped();}
2053

    
2054
        public boolean isAwake() {return state.isAwake();}
2055

    
2056
        public boolean isClosed() {return state.isClosed();}
2057

    
2058
        public boolean isOpen() {return state.isOpen();}
2059

    
2060
        public boolean isStopped() {return state.isStopped();}
2061

    
2062

    
2063
        public Set getMetadataChildren() {
2064
                // TODO Auto-generated method stub
2065
                return null;
2066
        }
2067

    
2068
        public Object getMetadataID() {
2069
                // TODO Auto-generated method stub
2070
                return null;
2071
        }
2072

    
2073
        public String getMetadataName() {
2074
                // TODO Auto-generated method stub
2075
                return null;
2076
        }
2077

    
2078
        /*
2079
         * (non-Javadoc)
2080
         * @see org.gvsig.fmap.mapcontext.layers.operations.SingleLayer#getDataStore()
2081
         */
2082
        public DataStore getDataStore() {
2083
                return this.store;
2084
        }
2085

    
2086
        /*
2087
         * (non-Javadoc)
2088
         * @see org.gvsig.fmap.mapcontext.layers.operations.SingleLayer#setDataStore(org.gvsig.fmap.dal.DataStore)
2089
         */
2090
        public void setDataStore(DataStore dataStore) throws LoadLayerException {
2091
                this.store = (CoverageStore) dataStore;
2092
                // TODO temporal
2093
                RasterStoreParameters params = (RasterStoreParameters)store.getParameters();
2094
                this.setLoadParams(params.getFile());
2095
                if (params.getSRS() != null)
2096
                        this.setProjection(params.getSRS());
2097
                this.load();
2098
        }
2099
        
2100
        /**
2101
         * Returns true if exists a process reading data from this layer
2102
         * @return
2103
         */
2104
        public boolean isReadingData() {
2105
                return readingData != null;
2106
        }
2107

    
2108
        /**
2109
         * When a process is using information of this layer this variable will contain
2110
         * the thread ID.
2111
         * @param readingData
2112
         */
2113
        public synchronized void setReadingData(String readingData) {
2114
                this.readingData = readingData;
2115
        }
2116

    
2117
}