Statistics
| Revision:

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

History | View | Annotate | Download (34.9 KB)

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

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

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

    
39
import org.cresques.cts.IProjection;
40
import org.gvsig.fmap.raster.legend.ColorTableLegend;
41
import org.gvsig.raster.RasterLibrary;
42
import org.gvsig.raster.buffer.BufferFactory;
43
import org.gvsig.raster.dataset.FileNotOpenException;
44
import org.gvsig.raster.dataset.IBuffer;
45
import org.gvsig.raster.dataset.InvalidSetViewException;
46
import org.gvsig.raster.dataset.MultiRasterDataset;
47
import org.gvsig.raster.dataset.NotSupportedExtensionException;
48
import org.gvsig.raster.dataset.RasterDataset;
49
import org.gvsig.raster.dataset.RasterDriverException;
50
import org.gvsig.raster.dataset.properties.DatasetMetadata;
51
import org.gvsig.raster.datastruct.ColorTable;
52
import org.gvsig.raster.datastruct.Extent;
53
import org.gvsig.raster.datastruct.ViewPortData;
54
import org.gvsig.raster.grid.Grid;
55
import org.gvsig.raster.grid.GridExtent;
56
import org.gvsig.raster.grid.GridPalette;
57
import org.gvsig.raster.grid.GridTransparency;
58
import org.gvsig.raster.grid.filter.RasterFilterList;
59
import org.gvsig.raster.grid.filter.RasterFilterListManager;
60
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
61
import org.gvsig.raster.grid.filter.enhancement.EnhancementListManager;
62
import org.gvsig.raster.grid.render.Rendering;
63
import org.gvsig.raster.hierarchy.IRasterDataset;
64
import org.gvsig.raster.hierarchy.IRasterProperties;
65
import org.gvsig.raster.hierarchy.IStatistics;
66
import org.gvsig.raster.util.MathUtils;
67

    
68
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
69
import com.iver.andami.PluginServices;
70
import com.iver.andami.messages.NotificationManager;
71
import com.iver.andami.ui.mdiManager.IWindow;
72
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
73
import com.iver.cit.gvsig.fmap.MapControl;
74
import com.iver.cit.gvsig.fmap.ViewPort;
75
import com.iver.cit.gvsig.fmap.core.FShape;
76
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
77
import com.iver.cit.gvsig.fmap.layers.FLyrDefault;
78
import com.iver.cit.gvsig.fmap.layers.LayerChangeSupport;
79
import com.iver.cit.gvsig.fmap.layers.LayerListener;
80
import com.iver.cit.gvsig.fmap.layers.LegendListener;
81
import com.iver.cit.gvsig.fmap.layers.Tiling;
82
import com.iver.cit.gvsig.fmap.layers.XMLException;
83
import com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable;
84
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
85
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
86
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
87
import com.iver.cit.gvsig.fmap.rendering.ILegend;
88
import com.iver.cit.gvsig.project.documents.view.gui.IView;
89
import com.iver.cit.gvsig.project.documents.view.gui.View;
90
import com.iver.utiles.XMLEntity;
91
import com.iver.utiles.swing.threads.Cancellable;
92
/**
93
 * Capa raster
94
 * @author Nacho Brodin (nachobrodin@gmail.com)
95
 */
96
public class FLyrRasterSE extends FLyrDefault
97
        implements IRasterProperties, IRasterDataset, InfoByPoint, Classifiable {
98
        public static double          noDataDefault      = -99999;
99
        boolean                       isPrinting         = false;
100
        boolean                       mustTileDraw       = false;
101
        boolean                       mustTilePrint      = true;
102
        private int                   maxTileDrawWidth   = 200;
103
        private int                   maxTileDrawHeight  = 200;
104
        int                           maxTilePrintWidth  = 1500;
105
        int                           maxTilePrintHeight = 1500;
106
        private StatusRasterInterface status             = null;
107
        private boolean               firstLoad          = false;
108
        private boolean               removeRasterFlag   = true;
109
        private Object                params             = null;
110
        private MultiRasterDataset    dataset            = null;
111
        private Rendering             render             = null;
112
        private BufferFactory         bufferFactory      = null;
113
        private int                   posX               = 0;
114
        private int                   posY               = 0;
115
        private double                posXWC             = 0;
116
        private int                   posYWC             = 0;
117
        private int                   r                  = 0;
118
        private int                   g                  = 0;
119
        private int                   b                  = 0;
120
        //private IClassifiedLegend     legend             = null;
121
        private LayerChangeSupport    layerChangeSupport = new LayerChangeSupport();
122
        public double                 noDataValue        = -99999;
123

    
124
        static {
125
                 RasterLibrary.wakeUp();
126
        }
127

    
128
        /**
129
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
130
         * @param layerName Nombre de la capa.
131
         * @param d RasterDriver.
132
         * @param f Fichero.
133
         * @param proj Proyecci?n.
134
         * @return Nueva capa de tipo raster.
135
         * @throws DriverIOException
136
         */
137
        public static FLyrRasterSE createLayer(String layerName, Object params,
138
                        IProjection proj) throws LoadLayerException {
139
                FLyrRasterSE capa = new FLyrRasterSE();
140
                capa.setLoadParams(params);
141
                capa.setName(layerName);
142
                capa.setProjection(proj);
143
                capa.load();
144
                return capa;
145
        }
146

    
147
        /**
148
         * Asigna los par?metros para la carga de la capa
149
         * @param param Par?metros.
150
         */
151
        public void setLoadParams(Object param){
152
                this.params = param;
153
        }
154

    
155
        /**
156
         * Obtiene los par?metros para la carga de la capa
157
         * @return param Par?metros.
158
         */
159
        public Object getLoadParams() {
160
                return params;
161
        }
162

    
163
        /**
164
         * Redefine wakeUp de FLyrDefault
165
         */
166
        public void wakeUp(){
167
        }
168

    
169
        /**
170
         * Asignar el estado del raster
171
         * @param status
172
         */
173
        public void setStatus(StatusRasterInterface status){
174
                this.status = status;
175
        }
176

    
177
        /**
178
         * Obtiene el estado del raster
179
         * @return
180
         */
181
        public StatusRasterInterface getStatus(){
182
                return this.status;
183
        }
184

    
185
        /*
186
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
187
         */
188
        public void load() throws LoadLayerException{
189
                if (getProjection() != null) {
190
                        String fName = null;
191
                        int test = -1;
192
                        if (params != null && params instanceof File) {
193
                                fName = ((File) params).getAbsolutePath();
194
                                test = fName.indexOf("ecwp:");
195
                        }
196

    
197
                        if (test != -1) {
198
                                String urlECW = fName.substring(test + 6);
199
                                fName = "ecwp://" + urlECW;
200
                                System.err.println(test + " " + fName);
201
                        }
202

    
203
                        try {
204
                                if (params == null || params instanceof File)
205
                                        dataset = MultiRasterDataset.open(getProjection(), fName);
206
                                else
207
                                        dataset = MultiRasterDataset.open(getProjection(), params);
208
                        } catch (NotSupportedExtensionException e) {
209
                                throw new LoadLayerException("Formato no valido", e);
210
                        } catch (RasterDriverException e) {
211
                                throw new LoadLayerException("Formato no valido", e);
212
                        }
213
                        if (dataset == null)
214
                                throw new LoadLayerException("Formato no valido", new IOException());
215
                        bufferFactory = new BufferFactory(dataset);
216
                        getRender();
217
                        initFilters();
218
                } else
219
                        throw new LoadLayerException("Proyecci?n no asignada", new IOException());
220
        }
221

    
222
        /**
223
         * Crea el objeto renderizador de raster
224
         * @return Rendering
225
         */
226
        public Rendering getRender() {
227
                if (render == null)
228
                        render = new Rendering(bufferFactory);
229
                return render;
230
        }
231

    
232
        /**
233
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
234
         */
235
        private void initFilters() {
236
                RasterFilterList filterList = new RasterFilterList();
237
                filterList.addParam("IStatistics", getMultiRasterDataset().getStatistics());
238
                filterList.addParam("MultiRasterDataset", getMultiRasterDataset());
239
                filterList.setInitDataType(getDataType()[0]);
240
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
241

    
242
                if (this.getMultiRasterDataset().getColorTables()[0] != null) {
243
                        GridPalette p = new GridPalette(getMultiRasterDataset().getColorTables()[0]);
244
                        ColorTableListManager ctm = new ColorTableListManager(filterManager);
245
                        ctm.addColorTableFilter(p);
246
                } else {
247
                        if (getDataType()[0] != IBuffer.TYPE_BYTE) {
248
                                IStatistics stats = getMultiRasterDataset().getStatistics();
249
                                EnhancementListManager elm = new EnhancementListManager(filterManager);
250
                                elm.addEnhancedFilter(false, stats, 0.0, getRender().getRenderBands());
251
                        }
252
                }
253

    
254
                getRender().setFilterList(filterList);
255
        }
256

    
257
        /**
258
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
259
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
260
         *                 com.iver.utiles.swing.threads.Cancellable)
261
         */
262
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) {
263
                if (isWithinScale(scale)) {
264

    
265
                        if (status != null && firstLoad) {
266
                                if (mustTileDraw) {
267
                                        Point2D p = vp.getOffset();
268
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
269
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
270
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
271
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
272
                                                // drawing part
273
                                                try {
274
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
275
                                                        // g.setClip(tiles.getClip(tileNr).x, tiles.getClip(tileNr).y, tiles.getClip(tileNr).width - 5, tiles.getClip(tileNr).height);
276
                                                        draw(image, g, vport, cancel);
277
                                                } catch (NoninvertibleTransformException e) {
278
                                                        NotificationManager.addError("Error en la transformaci?n", e);
279
                                                }
280
                                        }
281
                                } else
282
                                        draw(image, g, vp, cancel);
283
                                status.applyStatus(this);
284
                                firstLoad = false;
285
                        }
286

    
287
                        if (mustTileDraw) {
288
                                Point2D p = vp.getOffset();
289
                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
290
                                Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
291
                                tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
292
                                for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
293
                                        // drawing part
294
                                        try {
295
                                                ViewPort vport = tiles.getTileViewPort(vp, tileNr);
296
                                                draw(image, g, vport, cancel);
297
                                        } catch (NoninvertibleTransformException e) {
298
                                                NotificationManager.addError("Error en la transformaci?n", e);
299
                                        }
300
                                }
301
                        } else
302
                                draw(image, g, vp, cancel);
303

    
304
                        if (getVirtualLayers() != null) {
305
                                try {
306
                                        getVirtualLayers().draw(image, g, vp, cancel, scale);
307
                                } catch (ReadDriverException e) {
308
                                        NotificationManager.addError("Error dibujando", e);
309
                                }
310
                        }
311
                }
312
        }
313

    
314
        private void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) {
315
                Extent e = new Extent(vp.getAdjustedExtent());
316
                Dimension imgSz = vp.getImageSize();
317
                ViewPortData vp2 = new ViewPortData(vp.getProjection(), e, imgSz );
318
                vp2.setMat(vp.getAffineTransform());
319
                getRender().draw(g, vp2);
320
        }
321

    
322
        /**
323
         * Inserta la proyecci?n.
324
         *
325
         * @param proj Proyecci?n.
326
         */
327
        public void setProjection(IProjection proj) {
328
                super.setProjection(proj);
329
        }
330

    
331
        /*
332
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
333
         */
334
        public Rectangle2D getFullExtent(){
335
                if(dataset.isRotated())
336
                        return dataset.getLimits().toRectangle2D();
337
                return dataset.getExtent().toRectangle2D();
338
                
339
        }
340

    
341
        /**
342
         * Obtiene el extent de la capa raster completa
343
         * @return GridExtent
344
         */
345
        public GridExtent getGridExtent() {
346
                Extent extent = getMultiRasterDataset().getExtent();
347
                double dCellsize = (extent.getMax().getX() - extent.getMin().getX()) / (double)getMultiRasterDataset().getWidth()[0];
348
                return new GridExtent(extent, dCellsize);
349
        }
350

    
351
        /**
352
         * Obtiene el valor del pixel del Image en la posici?n real x,y
353
         * @param x Posici?n x
354
         * @param y Posici?n y
355
         * @return valor de pixel
356
         */
357
        public int[] getPixel(double wcx, double wcy) {
358
                int[] argb = { -1, -1, -1, -1 };
359
                if (wcx <= getMaxX() && wcx >= getMinX() && wcy <= getMaxY() && wcy >= getMinY()) {
360
                        View theView = (View) PluginServices.getMDIManager().getActiveWindow();
361
                        if (theView instanceof IView) {
362
                                // BufferedImage buf = ((IView) theView).getMapControl().getImage();
363
                                Point2D p = ((IView) theView).getMapControl().getViewPort().fromMapPoint(wcx, wcy);
364
                                return getPixel((int) p.getX(), (int) p.getY());
365
                        }
366
                }
367
                return argb;
368
        }
369

    
370
        /**
371
         * Obtiene el valor del pixel del Image en la posici?n x,y
372
         * @param x Posici?n x
373
         * @param y Posici?n y
374
         * @return valor de pixel
375
         */
376
        public int[] getPixel(int pxx, int pxy) {
377
                int[] argb = { -1, -1, -1, -1 };
378
                View theView = (View) PluginServices.getMDIManager().getActiveWindow();
379
                BufferedImage buf = null;
380
                if (theView instanceof IView)
381
                        buf = ((IView) theView).getMapControl().getImage();
382
                if (pxx >= 0 && pxx < buf.getWidth() && pxy >= 0 && pxy < buf.getHeight()) {
383
                        if (theView instanceof IView) {
384
                                int value = buf.getRGB(pxx, pxy);
385
                                argb[0] = ((value & 0xff000000) >> 24);
386
                                argb[1] = ((value & 0x00ff0000) >> 16);
387
                                argb[2] = ((value & 0x0000ff00) >> 8);
388
                                argb[3] = (value & 0x000000ff);
389
                        }
390
                }
391
                return argb;
392
        }
393

    
394
        /*
395
         * (non-Javadoc)
396
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
397
         */
398
        public double getMaxX(){
399
                return this.getFullExtent().getMaxX();
400
        }
401

    
402
        /*
403
         * (non-Javadoc)
404
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
405
         */
406
        public double getMaxY(){
407
                return this.getFullExtent().getMaxY();
408
        }
409

    
410
        /*
411
         * (non-Javadoc)
412
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinX()
413
         */
414
        public double getMinX(){
415
                return this.getFullExtent().getMinX();
416
        }
417

    
418
        /*
419
         * (non-Javadoc)
420
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinY()
421
         */
422
        public double getMinY(){
423
                return this.getFullExtent().getMinY();
424
        }
425

    
426
        /* (non-Javadoc)
427
         * @deprecated. See String getInfo(Point p) throws DriverException
428
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
429
         */
430
        public String queryByPoint(Point p) {
431
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
432

    
433
                ArrayList attr = getAttributes();
434
                data += "  <raster\n";
435
                data += "    File=\"" + getFile() + "\"\n";
436
                for (int i = 0; i < attr.size(); i++) {
437
                        Object[] a = (Object[]) attr.get(i);
438

    
439
                        data += "    " + a[0].toString() + "=";
440
                        if (a[1].toString() instanceof String)
441
                                data += "\"" + a[1].toString() + "\"\n";
442
                        else
443
                                data += a[1].toString() + "\n";
444
                }
445
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
446
                data += "    Point_WC=\"" + MathUtils.format(posXWC, 3) + " , " + MathUtils.format(posYWC, 3) + "\"\n";
447
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
448
                data += "  />\n";
449

    
450
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
451
                return data;
452
        }
453

    
454
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) {
455

    
456
                Point2D pReal = getMapContext().getViewPort().toMapPoint(p);
457
                Point2D px = null;
458
                if(        pReal.getX() > this.getMinX() &&
459
                        pReal.getX() < this.getMaxX() &&
460
                        pReal.getY() > this.getMinY() &&
461
                        pReal.getY() < this.getMaxY()) {
462
                        ArrayList attr = getAttributes();
463
                        int w = 0, h = 0;
464
                        for (int i = 0; i < attr.size(); i++) {
465
                                Object[] a = (Object[]) attr.get(i);
466
                                if (a[0].toString().equals("Width"))
467
                                        w = ((Integer) a[1]).intValue();
468
                                if (a[0].toString().equals("Height"))
469
                                        h = ((Integer) a[1]).intValue();
470
                        }
471
                        px = new Point2D.Double();
472
                        px.setLocation( ((pReal.getX() - this.getMinX()) * w) / getWCWidth(),
473
                                                        ((this.getMaxY() - pReal.getY()) * h) / getWCHeight());
474
                }
475
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
476

    
477
                StringXMLItem[] item = new StringXMLItem[1];
478
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
479

    
480
                data += "  <raster\n";
481
                data += "    View_Point=\"" + p.getX() + " , " + p.getY() + "\"\n";
482
                data += "    World_Point=\"" + MathUtils.format(pReal.getX(), 3) + " , " + MathUtils.format(pReal.getY(), 3) + "\"\n";
483
                if (px == null)
484
                        data += "    Pixel_Point=\"Out\"\n";
485
                else
486
                        data += "    Pixel_Point=\"" + (int) px.getX() + " , " + (int) px.getY() + "\"\n";
487
                data += "    RGB=\"" + rgb[1] + "  " + rgb[2] + "  " + rgb[3] + "\"\n";
488
                data += "    Band_Value=\"";
489
                try {
490
                        if (px != null) {
491
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3){
492
                                        for(int i = 0; i < getBandCount(); i++)
493
                                                data += ((Integer)getMultiRasterDataset().getData((int)px.getX(), (int)px.getY(), i)).intValue() + "  ";
494
                                }
495
                                if(getDataType()[0] == 4){
496
                                        for(int i = 0; i < getBandCount(); i++)
497
                                                data += ((Float)getMultiRasterDataset().getData((int)px.getX(), (int)px.getY(), i)).floatValue() + "  ";
498
                                }
499
                                if(getDataType()[0] == 5){
500
                                        for(int i = 0; i < getBandCount(); i++)
501
                                                data += ((Double)getMultiRasterDataset().getData((int)px.getX(), (int)px.getY(), i)).doubleValue() + "  ";
502
                                }
503
                        }
504
                } catch (RasterDriverException ex) {
505

    
506
                } catch (InvalidSetViewException ex) {
507

    
508
                } catch (FileNotOpenException ex) {
509

    
510
                }
511
                data += "\"\n";
512
                data += "  />\n";
513
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
514

    
515
                item[0] = new StringXMLItem(data, this);
516
                return item;
517
        }
518

    
519
        /**
520
         * Filters a string for being suitable as XML Tag, erasing
521
         * all not alphabetic or numeric characters.
522
         * @param s
523
         * @return string normalized
524
         */
525
        public String normalizeAsXMLTag(String s) {
526
                return s.replaceAll("[^a-zA-Z0-9]", "");
527
        }
528

    
529
        /**
530
         * Obtiene atributos a partir de un georasterfile
531
         * @return
532
         */
533
        public ArrayList getAttributes() {
534
                ArrayList attr = new ArrayList();
535
                Object [][] a = {
536
                        {"Filename", dataset.getDataset(0).getFName()},
537
                        {"Filesize", new Long(dataset.getFileSize())},
538
                        {"Width", new Integer((int)dataset.getWidth()[0])},
539
                        {"Height", new Integer((int)dataset.getHeight()[0])},
540
                        {"Bands", new Integer(dataset.getBandCount())}
541
                };
542
                for (int i = 0; i < a.length; i++)
543
                        attr.add(a[i]);
544
                return attr;
545
        }
546

    
547
        /**
548
         * Escribe en el proyecto la capa actual
549
         * @throws XMLException
550
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
551
         */
552
        public XMLEntity getXMLEntity() throws XMLException {
553
                XMLEntity xml = super.getXMLEntity();
554
                xml.putProperty("file", getFile());
555
                xml.putProperty("driverName", "gvSIG Raster Driver");
556

    
557
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
558
                if (status == null)
559
                        status = new StatusLayerRaster();
560
                status.getXMLEntity(xml, true, this);
561

    
562
                return xml;
563
        }
564

    
565
        public void setXMLEntity03(XMLEntity xml) throws XMLException {
566
        }
567

    
568
        /**
569
         * Recupera de disco los datos de la capa.
570
         */
571
        public void setXMLEntity(XMLEntity xml)throws XMLException {
572
                super.setXMLEntity(xml);
573

    
574
                params = new File(xml.getStringProperty("file"));
575

    
576
                // Para notificar al adapter-driver cual es la proyecci?n.
577
                setProjection(super.getProjection());
578

    
579
                //Inicializamos la clase a la que se usa por defecto para
580
                //compatibilidad con proyectos antiguos
581
                String claseStr = StatusLayerRaster.defaultClass;
582
                if (xml.contains("raster.class"))
583
                        claseStr = xml.getStringProperty("raster.class");
584

    
585
                if (status != null)
586
                        status.setXMLEntity(xml, this);
587
                else {
588
                        // Cuando cargamos un proyecto
589

    
590
                        if (claseStr != null && !claseStr.equals("")) {
591
                                try {
592
                                        Class clase = Class.forName(claseStr);
593
                                        Constructor constr = clase.getConstructor(null);
594
                                        status = (StatusRasterInterface) constr.newInstance(null);
595
                                        if (status != null)
596
                                                status.setXMLEntity(xml, this);
597
                                } catch (ClassNotFoundException exc) {
598
                                        NotificationManager.addError("Error localizando la clase a instanciar. " + claseStr, exc);
599
                                } catch (InstantiationException exc) {
600
                                        NotificationManager.addError("Error instanciando " + claseStr, exc);
601
                                } catch (IllegalAccessException exc) {
602
                                        NotificationManager.addError("Error instanciando " + claseStr, exc);
603
                                } catch (NoSuchMethodException exc) {
604
                                        NotificationManager.addError("Error obteniendo el constructor para la clase " + claseStr, exc);
605
                                } catch (InvocationTargetException exc) {
606
                                        NotificationManager.addError("Error instanciando " + claseStr, exc);
607
                                }
608
                        }
609
                }
610
                firstLoad = true;
611

    
612
        }
613

    
614
        /* (non-Javadoc)
615
         * @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)
616
         */
617
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet propeties) {
618

    
619
                if (!isVisible() || !isWithinScale(scale))
620
                        return;
621

    
622
                isPrinting = true;
623
                if (!mustTilePrint) {
624
                        draw(null, g, viewPort, cancel,scale);
625
                } else {
626
                        // Para no pedir imagenes demasiado grandes, vamos
627
                        // a hacer lo mismo que hace EcwFile: chunkear.
628
                        // Llamamos a drawView con cuadraditos m?s peque?os
629
                        // del BufferedImage ni caso, cuando se imprime viene con null
630
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
631
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
632

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

    
636
                        //RasterStats stats = getSource().getFilterStack().getStats();
637
                        //if(stats != null)
638
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
639

    
640

    
641
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
642
                                // Parte que dibuja
643
                                try {
644
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
645
                                        draw(null, g, vp, cancel, scale);
646
                                } catch (NoninvertibleTransformException e) {
647
                                        NotificationManager.addError("Error en la transformaci?n.", e);
648
                                }
649
                        }
650
                        /*if(stats != null){
651
                                getSource().getFilterStack().getStats().history.clear();
652
                                stats = getSource().getFilterStack().getStats();
653
                        }*/
654
                }
655
                isPrinting = false;
656
        }
657

    
658
        public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,double scale) {
659
                // Para no pedir imagenes demasiado grandes, vamos
660
                // a hacer lo mismo que hace EcwFile: chunkear.
661
                // Llamamos a drawView con cuadraditos m?s peque?os
662
                // del BufferedImage ni caso, cuando se imprime viene con null
663

    
664
                int numW, numH;
665
                int stepX, stepY;
666
                int xProv, yProv;
667
                int A = 1500;
668
                int H = 1500;
669
                int altoAux, anchoAux;
670

    
671
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
672

    
673
                // Vamos a hacerlo en trozos de AxH
674
                Rectangle r = g.getClipBounds();
675
                numW = (int) (r.width) / A;
676
                numH = (int) (r.height) / H;
677

    
678
                double[] srcPts = new double[8];
679
                double[] dstPts = new double[8];
680

    
681
                yProv = (int) r.y;
682
                for (stepY = 0; stepY < numH + 1; stepY++) {
683
                        if ((yProv + H) > r.getMaxY())
684
                                altoAux = (int) r.getMaxY() - yProv;
685
                        else
686
                                altoAux = H;
687

    
688
                        xProv = (int) r.x;
689
                        for (stepX = 0; stepX < numW + 1; stepX++) {
690
                                if ((xProv + A) > r.getMaxX())
691
                                        anchoAux = (int) r.getMaxX() - xProv;
692
                                else
693
                                        anchoAux = A;
694

    
695
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
696

    
697
                                // Parte que dibuja
698
                                srcPts[0] = xProv;
699
                                srcPts[1] = yProv;
700
                                srcPts[2] = xProv + anchoAux + 1;
701
                                srcPts[3] = yProv;
702
                                srcPts[4] = xProv + anchoAux + 1;
703
                                srcPts[5] = yProv + altoAux + 1;
704
                                srcPts[6] = xProv;
705
                                srcPts[7] = yProv + altoAux + 1;
706

    
707
                                try {
708
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
709
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
710
                                        // Extent extent = new Extent(rectCuadricula);
711

    
712
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
713
                                        ViewPort vp = viewPort.cloneViewPort();
714
                                        vp.setImageSize(tam);
715
                                        vp.setExtent(rectCuadricula);
716
                                        vp.setAffineTransform(mat);
717
                                        draw(null, g, vp, cancel, scale);
718

    
719
                                } catch (NoninvertibleTransformException e) {
720
                                        NotificationManager.addError("Error en la transformaci?n.", e);
721
                                }
722
                                // Fin parte que dibuja
723
                                xProv = xProv + A;
724
                        }
725
                        yProv = yProv + H;
726
                }
727
        }
728

    
729
        /**
730
         * Borra de la lista de listeners el que se pasa como par?metro.
731
         *
732
         * @param o LayerListener a borrar.
733
         *
734
         * @return True si ha sido correcto el borrado del Listener.
735
         */
736
        public boolean removeLayerListener(LayerListener o) {
737
                //Salva a RMF
738
                try {
739
                        this.getMultiRasterDataset().saveRmfModification();
740
                } catch (IOException e) {
741
                        //No se ha salvado nada
742
                }
743

    
744
                //Cierra todas las ventanas asociadas a la capa
745
                IWindow[] wList = PluginServices.getMDIManager().getAllWindows();
746
                for (int i = 0; i < wList.length; i++) {
747
                        String name = wList[i].getWindowInfo().getAdditionalInfo();
748
                        if( name != null && name.compareTo(getName()) == 0)
749
                                PluginServices.getMDIManager().closeWindow(wList[i]);
750
                }
751

    
752
                if (this.isRemoveRasterFlag()) {
753
                        dataset.close();
754
                        this.setRemoveRasterFlag(true);
755
                }
756
                return super.layerListeners.remove(o);
757
        }
758

    
759
        /**
760
         * @return Returns the removeRasterFlag.
761
         */
762
        public boolean isRemoveRasterFlag() {
763
                return removeRasterFlag;
764
        }
765

    
766
        /**
767
         * Asigna el valor del flag que dice si destruimos la memoria del raster
768
         * al eliminarlo del TOC o  no.
769
         * @param removeRasterFlag The removeRasterFlag to set.
770
         */
771
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
772
                this.removeRasterFlag = removeRasterFlag;
773
        }
774

    
775
        public ImageIcon getTocImageIcon() {
776
                return new ImageIcon(MapControl.class.getResource("images/icolayerRaster.PNG"));
777
        }
778

    
779
        /*
780
         *  (non-Javadoc)
781
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
782
         */
783
        public int[] getTileSize() {
784
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
785
                return size;
786
        }
787

    
788
        /*
789
         *  (non-Javadoc)
790
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
791
         */
792
        public boolean isTiled() {
793
                return mustTileDraw;
794
        }
795

    
796
        /**
797
         * Obtiene el flag que dice si la imagen est? o no georreferenciada
798
         * @return true si est? georreferenciada y false si no lo est?.
799
         */
800
        public boolean isGeoreferenced() {
801
                return dataset.isGeoreferenced();
802
        }
803

    
804
        /**
805
         * Get datasource object
806
         * @return
807
         */
808
        public BufferFactory getDatasource(){
809
                return bufferFactory;
810
        }
811

    
812
        /**
813
         * Asigna el valor noData asociado a la capa
814
         * @return double que representa el valor noData asociado a la capa
815
         */
816
        public double getNoDataValue() {
817
                return noDataValue;
818
        }
819

    
820
        /**
821
         * Asigna el valor no data asociado a la capa
822
         * @param nd
823
         */
824
        public void setNoDataValue(double nd){
825
                if (bufferFactory != null)
826
                        bufferFactory.setNoDataValue(nd);
827
                noDataValue = nd;
828
        }
829

    
830
        /*
831
         * (non-Javadoc)
832
         * @see org.gvsig.fmap.raster.IRasterOperations#getPXHeight()
833
         */
834
        public double getPxHeight() {
835
                return (dataset.getHeight() != null && dataset.getHeight().length >= 1) ? dataset.getHeight()[0] : 0;
836
        }
837

    
838
        /*
839
         * (non-Javadoc)
840
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
841
         */
842
        public double getPxWidth() {
843
                return (dataset.getWidth() != null && dataset.getWidth().length >= 1) ? dataset.getWidth()[0] : 0;
844
        }
845

    
846
        /*
847
         * (non-Javadoc)
848
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCHeight()
849
         */
850
        public double getWCHeight() {
851
                return getFullExtent().getHeight();
852
        }
853

    
854
        /*
855
         * (non-Javadoc)
856
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
857
         */
858
        public double getWCWidth() {
859
                return getFullExtent().getWidth();
860
        }
861

    
862
        /*
863
         * (non-Javadoc)
864
         * @see org.gvsig.fmap.raster.IRasterFile#getFileSize()
865
         */
866
        public long[] getFileSize(){
867
                int nFiles = dataset.getDatasetCount();
868
                long[] s = new long[nFiles];
869
                for (int i = 0; i < nFiles; i++)
870
                        s[i] = dataset.getDataset(i).getFileSize();
871
                return s;
872
        }
873

    
874
        /*
875
         * (non-Javadoc)
876
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
877
         */
878
        public String[] getFileName(){
879
                int nFiles = dataset.getDatasetCount();
880
                String[] s = new String[nFiles];
881
                for (int i = 0; i < nFiles; i++)
882
                        s[i] = dataset.getDataset(i).getFName();
883
                return s;
884
        }
885

    
886
        /*
887
         * (non-Javadoc)
888
         * @see org.gvsig.fmap.raster.IRasterFile#getFileCount()
889
         */
890
        public int getFileCount(){
891
                return dataset.getDatasetCount();
892
        }
893

    
894
        /*
895
         * (non-Javadoc)
896
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
897
         */
898
        public String getFileFormat(){
899
                String fName = dataset.getDataset(0).getFName();
900
                int index = fName.lastIndexOf(".") + 1;
901
                String ext = null;
902
                if (index > 0)
903
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
904
                return ext;
905
        }
906

    
907
        /*
908
         * (non-Javadoc)
909
         * @see org.gvsig.fmap.raster.IRasterOperations#getBandCount()
910
         */
911
        public int getBandCount(){
912
                return dataset.getBandCount();
913
        }
914

    
915
        /*
916
         * (non-Javadoc)
917
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
918
         */
919
        public int[] getDataType(){
920
                return dataset.getDataType();
921
        }
922

    
923
        /*
924
         * (non-Javadoc)
925
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
926
         */
927
        public GridTransparency getRenderTransparency(){
928
                return render.getLastTransparency();
929
        }
930

    
931
        /*
932
         * (non-Javadoc)
933
         * @see org.gvsig.fmap.raster.IRasterDataset#getGeoRasterMultiDataset()
934
         */
935
        public MultiRasterDataset getMultiRasterDataset() {
936
                return dataset;
937
        }
938

    
939
        /*
940
         * (non-Javadoc)
941
         * @see org.gvsig.fmap.raster.IRasterDataset#addFile(java.lang.String)
942
         */
943
        public void addFile(String fileName) {
944
                try {
945
                        if (getRender() != null)
946
                                bufferFactory.addFile(RasterDataset.open(getProjection(), fileName));
947
                } catch (NotSupportedExtensionException e) {
948
                        NotificationManager.addError("Formato no valido", e);
949
                } catch (RasterDriverException e) {
950
                        NotificationManager.addError("Formato no valido", e);
951
                }
952
        }
953

    
954
        /*
955
         * (non-Javadoc)
956
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
957
         */
958
        public void delFile(String fileName) {
959
                if (getRender() != null)
960
                        bufferFactory.removeFile(fileName);
961
        }
962

    
963
        /*
964
         * (non-Javadoc)
965
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
966
         */
967
        public Object getInfo(String key) {
968
                if (key.equals("DriverName"))
969
                        return "gvSIG Raster Driver";
970
                return null;
971
        }
972

    
973
        /*
974
         * (non-Javadoc)
975
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
976
         */
977
        public RasterFilterList getRenderFilterList(){
978
                return getRender().getFilterList();
979
        }
980

    
981
        /*
982
         * (non-Javadoc)
983
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getPixelSizeX()
984
         */
985
        public double[] getPxWidthByDataset() {
986
                return dataset.getWidth();
987
        }
988

    
989
        /*
990
         * (non-Javadoc)
991
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getPixelSizeY()
992
         */
993
        public double[] getPxHeightByDataset() {
994
                return dataset.getHeight();
995
        }
996

    
997
        /*
998
         * (non-Javadoc)
999
         * @see org.gvsig.raster.shared.IRasterOperations#getMetadata()
1000
         */
1001
        public DatasetMetadata[] getMetadata() {
1002
                int count = dataset.getDatasetCount();
1003
                DatasetMetadata[] metadata = new DatasetMetadata[count];
1004
                for (int i = 0; i < count; i++) {
1005
                        metadata[i] = dataset.getDataset(i).getMetadata();
1006
                }
1007
                return metadata;
1008
        }
1009

    
1010
        /*
1011
         * (non-Javadoc)
1012
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
1013
         */
1014
        public int[] getBandCountFromDataset() {
1015
                int count = dataset.getDatasetCount();
1016
                int[] bands = new int[count];
1017
                for (int i = 0; i < count; i++) {
1018
                        bands[i] = dataset.getDataset(i).getBandCount();
1019
                }
1020
                return bands;
1021
        }
1022

    
1023
        /*
1024
         * (non-Javadoc)
1025
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
1026
         */
1027
        public String getColourInterpretation(int band, int dataset) {
1028
                if (this.dataset.getColorInterpretation(dataset) == null)
1029
                        return "Undefined";
1030
                return this.dataset.getColorInterpretation(dataset).get(band);
1031
        }
1032

    
1033
        /*
1034
         * (non-Javadoc)
1035
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
1036
         */
1037
        public String getWktProjection() {
1038
                try {
1039
                        return dataset.getWktProjection();
1040
                } catch (RasterDriverException e) {
1041
                        NotificationManager.addError("No puedo obtener la proyecci?n asociada al dataset.", e);
1042
                }
1043
                return null;
1044
        }
1045

    
1046
        /**
1047
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
1048
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser
1049
         * cacheado o no dependiendo del tama?o de esta.
1050
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
1051
         * @return Grid.
1052
         */
1053
        public Grid getFullGrid(boolean interpolated) {
1054
                BufferFactory bf = getDatasource();
1055
                bf.clearDrawableBand();
1056
                bf.setAllDrawableBands();
1057
                bf.setAreaOfInterest();
1058
                return new Grid(bf, interpolated);
1059
        }
1060

    
1061
        /*
1062
         * (non-Javadoc)
1063
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1064
         */
1065
        public Extent getFullRasterExtent() {
1066
                return new Extent(getFullExtent());
1067
        }
1068

    
1069

    
1070
        /**
1071
         * Devuelve el fichero asociado a la capa o null si no tiene.
1072
         * @return Fichero.
1073
         */
1074
        public File getFile() {
1075
                return (params instanceof File) ? ((File)params) : null;
1076
        }
1077

    
1078
        /**
1079
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1080
         * @param file Fichero a consultar
1081
         * @return true si es aceptado y false si no lo es.
1082
         */
1083
        public static boolean isFileAccepted(File file) {
1084
                return RasterDataset.fileIsSupported(file.getName());
1085
        }
1086

    
1087
        /*
1088
         * (non-Javadoc)
1089
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1090
         */
1091
        public boolean existColorTable() {
1092
                return this.getRender().existColorTable();
1093
        }
1094

    
1095
        /**
1096
         * Devuelve la Leyenda de la capa.
1097
         * @return Leyenda.
1098
         */
1099
        public ILegend getLegend() {
1100
                ColorTable ct = this.getMultiRasterDataset().getColorTable(0);
1101
                if (ct != null)
1102
                        return ColorTableLegend.createLegend(ct);
1103
                return null;
1104
        }
1105

    
1106
        /*
1107
         * (non-Javadoc)
1108
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#addLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1109
         */
1110
        public void addLegendListener(LegendListener listener) {
1111
                layerChangeSupport.addLayerListener(listener);
1112
        }
1113

    
1114
        /*
1115
         *  (non-Javadoc)
1116
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#getShapeType()
1117
         */
1118
        public int getShapeType() throws ReadDriverException {
1119
                return FShape.POLYGON;
1120
        }
1121

    
1122
        /*
1123
         * (non-Javadoc)
1124
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.Classifiable#removeLegendListener(com.iver.cit.gvsig.fmap.layers.LegendListener)
1125
         */
1126
        public void removeLegendListener(LegendListener listener) {
1127
                layerChangeSupport.removeLayerListener(listener);
1128
        }
1129

    
1130
        /**
1131
         * Metodo que obtiene si un punto cae dentro de los l?mites de la capa
1132
         * o fuera de ellos.
1133
         * @param p Punto a calcular
1134
         * @return true si est? dentro de los l?mites y false si est? fuera
1135
         */
1136
        public boolean isInside(Point2D p) {
1137
                 return getMultiRasterDataset().isInside(p);
1138
        }
1139

    
1140
        /**
1141
         * Recupera del raster la matriz de transformaci?n que lo situa en cualquier parte de la vista
1142
         * @return AffineTransform
1143
         */
1144
        public AffineTransform getAffineTransform(){
1145
                return getMultiRasterDataset().getAffineTransform();
1146
        }
1147

    
1148
        /**
1149
         * Asigna al raster la matriz de transformaci?n para situarlo en cualquier parte de la vista
1150
         * @param transf
1151
         */
1152
        public void setAffineTransform(AffineTransform transf){
1153
                getMultiRasterDataset().setAffineTransform(transf);
1154
        }
1155
}