Statistics
| Revision:

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

History | View | Annotate | Download (64.2 KB)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
948
                return xml;
949
        }
950

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

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

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

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

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

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

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

    
1017
                }
1018
        }
1019

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

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

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

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

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

    
1045

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1529
                return false;
1530
        }
1531

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

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

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

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

    
1587

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

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

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

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

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

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

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

    
1651
                return null;
1652
        }
1653

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1815
                super.setVisible(visibility);
1816
        }
1817

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1951
                return false;
1952
        }
1953

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

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

    
1975
        /*****************************************************/
1976
        //Utils
1977

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

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

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

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

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

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

    
2022
                return newLayer;
2023
        }
2024

    
2025
        /*****************************************************/
2026

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

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

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

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

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

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

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

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

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

    
2045

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

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

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

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

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

    
2083
}