Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRasterTools-SE / src / org / gvsig / fmap / layers / FLyrRasterSE.java @ 12225

History | View | Annotate | Download (31 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.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.raster.RasterLibrary;
41
import org.gvsig.raster.buffer.BufferFactory;
42
import org.gvsig.raster.dataset.FileNotOpenException;
43
import org.gvsig.raster.dataset.IBuffer;
44
import org.gvsig.raster.dataset.IStatistics;
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.grid.Grid;
52
import org.gvsig.raster.grid.GridPalette;
53
import org.gvsig.raster.grid.GridTransparency;
54
import org.gvsig.raster.grid.filter.RasterFilterList;
55
import org.gvsig.raster.grid.filter.RasterFilterListManager;
56
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
57
import org.gvsig.raster.grid.filter.enhancement.EnhancementListManager;
58
import org.gvsig.raster.grid.render.Rendering;
59
import org.gvsig.raster.shared.Extent;
60
import org.gvsig.raster.shared.IRasterDataset;
61
import org.gvsig.raster.shared.IRasterProperties;
62
import org.gvsig.raster.shared.ViewPortData;
63

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

    
110
        static {
111
                 RasterLibrary.wakeUp();
112
        }
113

    
114
        /**
115
         * Crea una capa Raster a partir del nombre driver, fichero y proyecci?n.
116
         * @param layerName Nombre de la capa.
117
         * @param d RasterDriver.
118
         * @param f Fichero.
119
         * @param proj Proyecci?n.
120
         * @return Nueva capa de tipo raster.
121
         * @throws DriverIOException
122
         */
123
        public static FLyrRasterSE createLayer(String layerName, Object params,
124
                        IProjection proj) throws LoadLayerException {
125
                FLyrRasterSE capa = new FLyrRasterSE();
126
                capa.setLoadParams(params);
127
                capa.setName(layerName);
128
                capa.setProjection(proj);
129
                capa.load();
130
                return capa;
131
        }
132

    
133
        /**
134
         * Asigna los par?metros para la carga de la capa
135
         * @param param Par?metros.
136
         */
137
        public void setLoadParams(Object param){
138
                this.params = param;
139
        }
140

    
141
        /**
142
         * Obtiene los par?metros para la carga de la capa
143
         * @return param Par?metros.
144
         */
145
        public Object getLoadParams() {
146
                return params;
147
        }
148
        
149
        /**
150
         * Redefine wakeUp de FLyrDefault
151
         */
152
        public void wakeUp(){
153
        }
154

    
155
        /**
156
         * Asignar el estado del raster
157
         * @param status
158
         */
159
        public void setStatus(StatusRasterInterface status){
160
                this.status = status;
161
        }
162

    
163
        /**
164
         * Obtiene el estado del raster
165
         * @return
166
         */
167
        public StatusRasterInterface getStatus(){
168
                return this.status;
169
        }
170

    
171
        /*
172
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
173
         */
174
        public void load() throws LoadLayerException{
175
                if (getProjection() != null) {
176
                        String fName = null;
177
                        int test = -1;
178
                        if (params != null && params instanceof File) {
179
                                fName = ((File) params).getAbsolutePath();
180
                                test = fName.indexOf("ecwp:");
181
                        }
182

    
183
                        if (test != -1) {
184
                                String urlECW = fName.substring(test + 6);
185
                                fName = "ecwp://" + urlECW;
186
                                System.err.println(test + " " + fName);
187
                        }
188

    
189
                        try {
190
                                if (params == null || params instanceof File)
191
                                        dataset = MultiRasterDataset.open(getProjection(), fName);
192
                                else
193
                                        dataset = MultiRasterDataset.open(getProjection(), params);
194
                        } catch (NotSupportedExtensionException e) {
195
                                throw new LoadLayerException("Formato no valido", e);
196
                        } catch (RasterDriverException e) {
197
                                throw new LoadLayerException("Formato no valido", e);
198
                        }
199
                        if (dataset == null)
200
                                throw new LoadLayerException("Formato no valido", new IOException());
201
                        bufferFactory = new BufferFactory(dataset);
202
                        getRender();
203
                        initFilters();
204
                } else
205
                        throw new LoadLayerException("Proyecci?n no asignada", new IOException());
206
        }
207

    
208
        /**
209
         * Crea el objeto renderizador de raster
210
         * @return Rendering 
211
         */
212
        public Rendering getRender() {
213
                if (render == null)
214
                        render = new Rendering(bufferFactory);
215
                return render;
216
        }
217

    
218
        /**
219
         * Filtros a?adidos por defecto en la pila para visualizaci?n.
220
         */
221
        private void initFilters() {
222
                RasterFilterList filterList = new RasterFilterList();
223
                filterList.addParam("IStatistics", getGeoRasterMultiDataset().getStatistics());
224
                filterList.addParam("MultiRasterDataset", getGeoRasterMultiDataset());
225
                filterList.setInitDataType(getDataType()[0]);
226
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
227

    
228
                if (this.getGeoRasterMultiDataset().getColorTables()[0] != null) {
229
                        GridPalette p = new GridPalette(getGeoRasterMultiDataset().getColorTables()[0]);
230
                        ColorTableListManager ctm = new ColorTableListManager(filterManager);
231
                        ctm.addColorTableFilter(p);
232
                } else {
233
                        if (getDataType()[0] != IBuffer.TYPE_BYTE) {
234
                                IStatistics stats = getGeoRasterMultiDataset().getStatistics();
235
                                EnhancementListManager elm = new EnhancementListManager(filterManager);
236
                                elm.addEnhancedFilter(false, stats, 0.0, getRender().getRenderBands());
237
                        }
238
                }
239

    
240
                getRender().setFilterList(filterList);
241
        }
242

    
243
        /**
244
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
245
         *                 java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort,
246
         *                 com.iver.utiles.swing.threads.Cancellable)
247
         */
248
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) {
249
                if (isWithinScale(scale)) {
250

    
251
                        if (status != null && firstLoad) {
252
                                if (mustTileDraw) {
253
                                        Point2D p = vp.getOffset();
254
                                        Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
255
                                        Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
256
                                        tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
257
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
258
                                                // drawing part
259
                                                try {
260
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
261
                                                        // g.setClip(tiles.getClip(tileNr).x, tiles.getClip(tileNr).y, tiles.getClip(tileNr).width - 5, tiles.getClip(tileNr).height);
262
                                                        draw(image, g, vport, cancel);
263
                                                } catch (NoninvertibleTransformException e) {
264
                                                        e.printStackTrace();
265
                                                }
266
                                        }
267
                                } else
268
                                        draw(image, g, vp, cancel);
269
                                status.applyStatus(this);
270
                                firstLoad = false;
271
                        }
272

    
273
                        if (mustTileDraw) {
274
                                Point2D p = vp.getOffset();
275
                                Rectangle r = new Rectangle((int) p.getX(), (int) p.getY(), vp.getImageWidth(), vp.getImageHeight());
276
                                Tiling tiles = new Tiling(maxTileDrawWidth, maxTileDrawHeight, r);
277
                                tiles.setAffineTransform((AffineTransform) vp.getAffineTransform().clone());
278
                                for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
279
                                        // drawing part
280
                                        try {
281
                                                ViewPort vport = tiles.getTileViewPort(vp, tileNr);
282
                                                draw(image, g, vport, cancel);
283
                                        } catch (NoninvertibleTransformException e) {
284
                                                e.printStackTrace();
285
                                        }
286
                                }
287
                        } else
288
                                draw(image, g, vp, cancel);
289

    
290
                        if (getVirtualLayers() != null) {
291
                                try {
292
                                        getVirtualLayers().draw(image, g, vp, cancel, scale);
293
                                } catch (ReadDriverException e) {
294
                                        NotificationManager.addError("Error dibujando", e);
295
                                }
296
                        }
297
                }
298
        }
299

    
300
        private void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel) {
301
                Extent e = new Extent(vp.getAdjustedExtent());
302
                Dimension imgSz = vp.getImageSize();
303
                ViewPortData vp2 = new ViewPortData(vp.getProjection(), e, imgSz );
304
                vp2.setMat(vp.getAffineTransform());
305
                getRender().draw(g, vp2);
306
        }
307

    
308
        /**
309
         * Inserta la proyecci?n.
310
         *
311
         * @param proj Proyecci?n.
312
         */
313
        public void setProjection(IProjection proj) {
314
                super.setProjection(proj);
315
        }
316

    
317
        /*
318
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
319
         */
320
        public Rectangle2D getFullExtent(){
321
                return dataset.getExtent().toRectangle2D();
322
        }
323

    
324
        /**
325
         * Obtiene el valor del pixel del Image en la posici?n real x,y
326
         * @param x Posici?n x
327
         * @param y Posici?n y
328
         * @return valor de pixel
329
         */
330
        public int[] getPixel(double wcx, double wcy) {
331
                int[] argb = { -1, -1, -1, -1 };
332
                if (wcx <= getMaxX() && wcx >= getMinX() && wcy <= getMaxY() && wcy >= getMinY()) {
333
                        View theView = (View) PluginServices.getMDIManager().getActiveWindow();
334
                        if (theView instanceof IView) {
335
                                // BufferedImage buf = ((IView) theView).getMapControl().getImage();
336
                                Point2D p = ((IView) theView).getMapControl().getViewPort().fromMapPoint(wcx, wcy);
337
                                return getPixel((int) p.getX(), (int) p.getY());
338
                        }
339
                }
340
                return argb;
341
        }
342

    
343
        /**
344
         * Obtiene el valor del pixel del Image en la posici?n x,y
345
         * @param x Posici?n x
346
         * @param y Posici?n y
347
         * @return valor de pixel
348
         */
349
        public int[] getPixel(int pxx, int pxy) {
350
                int[] argb = { -1, -1, -1, -1 };
351
                View theView = (View) PluginServices.getMDIManager().getActiveWindow();
352
                BufferedImage buf = null;
353
                if (theView instanceof IView)
354
                        buf = ((IView) theView).getMapControl().getImage();
355
                if (pxx >= 0 && pxx < buf.getWidth() && pxy >= 0 && pxy < buf.getHeight()) {
356
                        if (theView instanceof IView) {
357
                                int value = buf.getRGB(pxx, pxy);
358
                                argb[0] = ((value & 0xff000000) >> 24);
359
                                argb[1] = ((value & 0x00ff0000) >> 16);
360
                                argb[2] = ((value & 0x0000ff00) >> 8);
361
                                argb[3] = (value & 0x000000ff);
362
                        }
363
                }
364
                return argb;
365
        }
366

    
367
        /*
368
         * (non-Javadoc)
369
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
370
         */
371
        public double getMaxX(){
372
                return this.getFullExtent().getMaxX();
373
        }
374

    
375
        /*
376
         * (non-Javadoc)
377
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
378
         */
379
        public double getMaxY(){
380
                return this.getFullExtent().getMaxY();
381
        }
382

    
383
        /*
384
         * (non-Javadoc)
385
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinX()
386
         */
387
        public double getMinX(){
388
                return this.getFullExtent().getMinX();
389
        }
390

    
391
        /*
392
         * (non-Javadoc)
393
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinY()
394
         */
395
        public double getMinY(){
396
                return this.getFullExtent().getMinY();
397
        }
398

    
399
        /* (non-Javadoc)
400
         * @deprecated. See String getInfo(Point p) throws DriverException
401
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#queryByPoint(java.awt.Point)
402
         */
403
        public String queryByPoint(Point p) {
404
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
405

    
406
                ArrayList attr = getAttributes();
407
                data += "  <raster\n";
408
                data += "    File=\"" + getFile() + "\"\n";
409
                for (int i = 0; i < attr.size(); i++) {
410
                        Object[] a = (Object[]) attr.get(i);
411

    
412
                        data += "    " + a[0].toString() + "=";
413
                        if (a[1].toString() instanceof String)
414
                                data += "\"" + a[1].toString() + "\"\n";
415
                        else
416
                                data += a[1].toString() + "\n";
417
                }
418
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
419
                data += "    Point_WC=\"" + posXWC + " , " + posYWC + "\"\n";
420
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
421
                data += "  />\n";
422

    
423
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
424
                return data;
425
        }
426

    
427
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) {
428

    
429
                Point2D pReal = getMapContext().getViewPort().toMapPoint(p);
430
                Point2D px = null;
431
                if(        pReal.getX() > this.getMinX() &&
432
                        pReal.getX() < this.getMaxX() &&
433
                        pReal.getY() > this.getMinY() &&
434
                        pReal.getY() < this.getMaxY()) {
435
                        ArrayList attr = getAttributes();
436
                        int w = 0, h = 0;
437
                        for (int i = 0; i < attr.size(); i++) {
438
                                Object[] a = (Object[]) attr.get(i);
439
                                if (a[0].toString().equals("Width"))
440
                                        w = ((Integer) a[1]).intValue();
441
                                if (a[0].toString().equals("Height"))
442
                                        h = ((Integer) a[1]).intValue();
443
                        }
444
                        px = new Point2D.Double();
445
                        px.setLocation( ((pReal.getX() - this.getMinX()) * w) / getWCWidth(),
446
                                                        ((this.getMaxY() - pReal.getY()) * h) / getWCHeight());
447
                }
448
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
449

    
450
                StringXMLItem[] item = new StringXMLItem[1];
451
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
452

    
453
                data += "  <raster\n";
454
                data += "    View_Point=\"" + p.getX() + " , " + p.getY() + "\"\n";
455
                data += "    World_Point=\"" + pReal.getX() + " , " + pReal.getY() + "\"\n";
456
                if (px == null)
457
                        data += "    Pixel_Point=\"Out\"\n";
458
                else
459
                        data += "    Pixel_Point=\"" + (int) px.getX() + " , " + (int) px.getY() + "\"\n";
460
                data += "    RGB=\"" + rgb[1] + "  " + rgb[2] + "  " + rgb[3] + "\"\n";
461
                data += "    Band_Value=\"";
462
                try {
463
                        if (px != null) {
464
                                if(getDataType()[0] >= 0 && getDataType()[0] <= 3){
465
                                        for(int i = 0; i < getBandCount(); i++)
466
                                                data += ((Integer)getGeoRasterMultiDataset().getData((int)px.getX(), (int)px.getY(), i)).intValue() + "  ";
467
                                }
468
                                if(getDataType()[0] == 4){
469
                                        for(int i = 0; i < getBandCount(); i++)
470
                                                data += ((Float)getGeoRasterMultiDataset().getData((int)px.getX(), (int)px.getY(), i)).floatValue() + "  ";
471
                                }
472
                                if(getDataType()[0] == 5){
473
                                        for(int i = 0; i < getBandCount(); i++)
474
                                                data += ((Double)getGeoRasterMultiDataset().getData((int)px.getX(), (int)px.getY(), i)).doubleValue() + "  ";
475
                                }
476
                        }
477
                } catch (RasterDriverException ex) {
478

    
479
                } catch (InvalidSetViewException ex) {
480

    
481
                } catch (FileNotOpenException ex) {
482

    
483
                }
484
                data += "\"\n";
485
                data += "  />\n";
486
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
487

    
488
                item[0] = new StringXMLItem(data, this);
489
                return item;
490
        }
491

    
492
        /**
493
         * Filters a string for being suitable as XML Tag, erasing
494
         * all not alphabetic or numeric characters.
495
         * @param s
496
         * @return string normalized
497
         */
498
        public String normalizeAsXMLTag(String s) {
499
                return s.replaceAll("[^a-zA-Z0-9]", "");
500
        }
501

    
502
        /**
503
         * Obtiene atributos a partir de un georasterfile
504
         * @return
505
         */
506
        public ArrayList getAttributes() {
507
                ArrayList attr = new ArrayList();
508
                Object [][] a = {
509
                        {"Filename", dataset.getDataset(0).getFName()},
510
                        {"Filesize", new Long(dataset.getFileSize())},
511
                        {"Width", new Integer((int)dataset.getWidth()[0])},
512
                        {"Height", new Integer((int)dataset.getHeight()[0])},
513
                        {"Bands", new Integer(dataset.getBandCount())}
514
                };
515
                for (int i = 0; i < a.length; i++)
516
                        attr.add(a[i]);
517
                return attr;
518
        }
519

    
520
        /**
521
         * Escribe en el proyecto la capa actual
522
         * @throws XMLException
523
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
524
         */
525
        public XMLEntity getXMLEntity() throws XMLException {
526
                XMLEntity xml = super.getXMLEntity();
527
                xml.putProperty("file", getFile());
528
                xml.putProperty("driverName", "gvSIG Raster Driver");
529

    
530
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
531
                if (status == null)
532
                        status = new StatusLayerRaster();
533
                status.getXMLEntity(xml, true, this);
534

    
535
                return xml;
536
        }
537

    
538
        public void setXMLEntity03(XMLEntity xml) throws XMLException {
539
        }
540

    
541
        /**
542
         * Recupera de disco los datos de la capa.
543
         */
544
        public void setXMLEntity(XMLEntity xml)throws XMLException {
545
                super.setXMLEntity(xml);
546

    
547
                params = new File(xml.getStringProperty("file"));
548

    
549
                // Para notificar al adapter-driver cual es la proyecci?n.
550
                setProjection(super.getProjection());
551

    
552
                //Inicializamos la clase a la que se usa por defecto para
553
                //compatibilidad con proyectos antiguos
554
                String claseStr = StatusLayerRaster.defaultClass;
555
                if (xml.contains("raster.class"))
556
                        claseStr = xml.getStringProperty("raster.class");
557

    
558
                if (status != null)
559
                        status.setXMLEntity(xml, this);
560
                else {
561
                        // Cuando cargamos un proyecto
562

    
563
                        if (claseStr != null && !claseStr.equals("")) {
564
                                try {
565
                                        Class clase = Class.forName(claseStr);
566
                                        Constructor constr = clase.getConstructor(null);
567
                                        status = (StatusRasterInterface) constr.newInstance(null);
568
                                        if (status != null)
569
                                                status.setXMLEntity(xml, this);
570
                                } catch (ClassNotFoundException exc) {
571
                                        exc.printStackTrace();
572
                                } catch (InstantiationException exc) {
573
                                        exc.printStackTrace();
574
                                } catch (IllegalAccessException exc) {
575
                                        exc.printStackTrace();
576
                                } catch (NoSuchMethodException exc) {
577
                                        exc.printStackTrace();
578
                                } catch (InvocationTargetException exc) {
579
                                        exc.printStackTrace();
580
                                }
581
                        }
582
                }
583
                firstLoad = true;
584

    
585
        }
586

    
587
        /* (non-Javadoc)
588
         * @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)
589
         */
590
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet propeties) {
591

    
592
                if (!isVisible() || !isWithinScale(scale))
593
                        return;
594

    
595
                isPrinting = true;
596
                if (!mustTilePrint) {
597
                        draw(null, g, viewPort, cancel,scale);
598
                } else {
599
                        // Para no pedir imagenes demasiado grandes, vamos
600
                        // a hacer lo mismo que hace EcwFile: chunkear.
601
                        // Llamamos a drawView con cuadraditos m?s peque?os
602
                        // del BufferedImage ni caso, cuando se imprime viene con null
603
                        Tiling tiles = new Tiling(maxTilePrintWidth, maxTilePrintHeight, g.getClipBounds());
604
                        tiles.setAffineTransform((AffineTransform) viewPort.getAffineTransform().clone());
605

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

    
609
                        //RasterStats stats = getSource().getFilterStack().getStats();
610
                        //if(stats != null)
611
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
612

    
613

    
614
                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
615
                                // Parte que dibuja
616
                                try {
617
                                        ViewPort vp = tiles.getTileViewPort(viewPort, tileNr);
618
                                        draw(null, g, vp, cancel, scale);
619
                                } catch (NoninvertibleTransformException e) {
620
                                        e.printStackTrace();
621
                                }
622
                        }
623
                        /*if(stats != null){
624
                                getSource().getFilterStack().getStats().history.clear();
625
                                stats = getSource().getFilterStack().getStats();
626
                        }*/
627
                }
628
                isPrinting = false;
629
        }
630

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

    
637
                int numW, numH;
638
                int stepX, stepY;
639
                int xProv, yProv;
640
                int A = 1500;
641
                int H = 1500;
642
                int altoAux, anchoAux;
643

    
644
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
645

    
646
                // Vamos a hacerlo en trozos de AxH
647
                Rectangle r = g.getClipBounds();
648
                numW = (int) (r.width) / A;
649
                numH = (int) (r.height) / H;
650

    
651
                double[] srcPts = new double[8];
652
                double[] dstPts = new double[8];
653

    
654
                yProv = (int) r.y;
655
                for (stepY = 0; stepY < numH + 1; stepY++) {
656
                        if ((yProv + H) > r.getMaxY())
657
                                altoAux = (int) r.getMaxY() - yProv;
658
                        else
659
                                altoAux = H;
660

    
661
                        xProv = (int) r.x;
662
                        for (stepX = 0; stepX < numW + 1; stepX++) {
663
                                if ((xProv + A) > r.getMaxX())
664
                                        anchoAux = (int) r.getMaxX() - xProv;
665
                                else
666
                                        anchoAux = A;
667

    
668
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
669

    
670
                                // Parte que dibuja
671
                                srcPts[0] = xProv;
672
                                srcPts[1] = yProv;
673
                                srcPts[2] = xProv + anchoAux + 1;
674
                                srcPts[3] = yProv;
675
                                srcPts[4] = xProv + anchoAux + 1;
676
                                srcPts[5] = yProv + altoAux + 1;
677
                                srcPts[6] = xProv;
678
                                srcPts[7] = yProv + altoAux + 1;
679

    
680
                                try {
681
                                        mat.inverseTransform(srcPts, 0, dstPts, 0, 4);
682
                                        Rectangle2D.Double rectCuadricula = new Rectangle2D.Double(dstPts[0], dstPts[1], dstPts[2] - dstPts[0], dstPts[5] - dstPts[3]);
683
                                        // Extent extent = new Extent(rectCuadricula);
684

    
685
                                        Dimension tam = new Dimension(anchoAux + 1, altoAux + 1);
686
                                        ViewPort vp = viewPort.cloneViewPort();
687
                                        vp.setImageSize(tam);
688
                                        vp.setExtent(rectCuadricula);
689
                                        vp.setAffineTransform(mat);
690
                                        draw(null, g, vp, cancel, scale);
691

    
692
                                } catch (NoninvertibleTransformException e) {
693
                                        e.printStackTrace();
694
                                }
695
                                // Fin parte que dibuja
696
                                xProv = xProv + A;
697
                        }
698
                        yProv = yProv + H;
699
                }
700
        }
701

    
702
        /**
703
         * Borra de la lista de listeners el que se pasa como par?metro.
704
         *
705
         * @param o LayerListener a borrar.
706
         *
707
         * @return True si ha sido correcto el borrado del Listener.
708
         */
709
        public boolean removeLayerListener(LayerListener o) {
710
                IWindow[] wList = PluginServices.getMDIManager().getAllWindows();
711
                for (int i = 0; i < wList.length; i++) {
712
                        String name = wList[i].getWindowInfo().getAdditionalInfo();
713
                        if( name != null && name.compareTo(getName()) == 0)
714
                                PluginServices.getMDIManager().closeWindow(wList[i]);
715
                }
716
                
717
                if (this.isRemoveRasterFlag()) {
718
                        dataset.close();
719
                        this.setRemoveRasterFlag(true);
720
                }
721
                return super.layerListeners.remove(o);
722
        }
723

    
724
        /**
725
         * @return Returns the removeRasterFlag.
726
         */
727
        public boolean isRemoveRasterFlag() {
728
                return removeRasterFlag;
729
        }
730

    
731
        /**
732
         * Asigna el valor del flag que dice si destruimos la memoria del raster
733
         * al eliminarlo del TOC o  no.
734
         * @param removeRasterFlag The removeRasterFlag to set.
735
         */
736
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
737
                this.removeRasterFlag = removeRasterFlag;
738
        }
739

    
740
        public ImageIcon getTocImageIcon() {
741
                return new ImageIcon(MapControl.class.getResource("images/icolayerRaster.PNG"));
742
        }
743

    
744
        /*
745
         *  (non-Javadoc)
746
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
747
         */
748
        public int[] getTileSize() {
749
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
750
                return size;
751
        }
752

    
753
        /*
754
         *  (non-Javadoc)
755
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
756
         */
757
        public boolean isTiled() {
758
                return mustTileDraw;
759
        }
760

    
761
        /**
762
         * Obtiene el flag que dice si la imagen est? o no georreferenciada
763
         * @return true si est? georreferenciada y false si no lo est?.
764
         */
765
        public boolean isGeoreferenced() {
766
                return dataset.isGeoreferenced();
767
        }
768

    
769
        /**
770
         * Get datasource object
771
         * @return
772
         */
773
        public BufferFactory getDatasource(){
774
                return bufferFactory;
775
        }
776

    
777
        /*
778
         * (non-Javadoc)
779
         * @see org.gvsig.fmap.raster.IRasterOperations#getPXHeight()
780
         */
781
        public double getPxHeight() {
782
                return (dataset.getHeight() != null && dataset.getHeight().length >= 1) ? dataset.getHeight()[0] : 0;
783
        }
784

    
785
        /*
786
         * (non-Javadoc)
787
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
788
         */
789
        public double getPxWidth() {
790
                return (dataset.getWidth() != null && dataset.getWidth().length >= 1) ? dataset.getWidth()[0] : 0;
791
        }
792

    
793
        /*
794
         * (non-Javadoc)
795
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCHeight()
796
         */
797
        public double getWCHeight() {
798
                return getFullExtent().getHeight();
799
        }
800

    
801
        /*
802
         * (non-Javadoc)
803
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
804
         */
805
        public double getWCWidth() {
806
                return getFullExtent().getWidth();
807
        }
808

    
809
        /*
810
         * (non-Javadoc)
811
         * @see org.gvsig.fmap.raster.IRasterFile#getFileSize()
812
         */
813
        public long[] getFileSize(){
814
                int nFiles = dataset.getDatasetCount();
815
                long[] s = new long[nFiles];
816
                for (int i = 0; i < nFiles; i++)
817
                        s[i] = dataset.getDataset(i).getFileSize();
818
                return s;
819
        }
820

    
821
        /*
822
         * (non-Javadoc)
823
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
824
         */
825
        public String[] getFileName(){
826
                int nFiles = dataset.getDatasetCount();
827
                String[] s = new String[nFiles];
828
                for (int i = 0; i < nFiles; i++)
829
                        s[i] = dataset.getDataset(i).getFName();
830
                return s;
831
        }
832

    
833
        /*
834
         * (non-Javadoc)
835
         * @see org.gvsig.fmap.raster.IRasterFile#getFileCount()
836
         */
837
        public int getFileCount(){
838
                return dataset.getDatasetCount();
839
        }
840

    
841
        /*
842
         * (non-Javadoc)
843
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
844
         */
845
        public String getFileFormat(){
846
                String fName = dataset.getDataset(0).getFName();
847
                int index = fName.lastIndexOf(".") + 1;
848
                String ext = null;
849
                if (index > 0)
850
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
851
                return ext;
852
        }
853

    
854
        /*
855
         * (non-Javadoc)
856
         * @see org.gvsig.fmap.raster.IRasterOperations#getBandCount()
857
         */
858
        public int getBandCount(){
859
                return dataset.getBandCount();
860
        }
861

    
862
        /*
863
         * (non-Javadoc)
864
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
865
         */
866
        public int[] getDataType(){
867
                return dataset.getDataType();
868
        }
869

    
870
        /*
871
         * (non-Javadoc)
872
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
873
         */
874
        public GridTransparency getRenderTransparency(){
875
                return render.getLastTransparency();
876
        }
877

    
878
        /*
879
         * (non-Javadoc)
880
         * @see org.gvsig.fmap.raster.IRasterDataset#getGeoRasterMultiDataset()
881
         */
882
        public MultiRasterDataset getGeoRasterMultiDataset() {
883
                return dataset;
884
        }
885

    
886
        /*
887
         * (non-Javadoc)
888
         * @see org.gvsig.fmap.raster.IRasterDataset#addFile(java.lang.String)
889
         */
890
        public void addFile(String fileName) {
891
                try {
892
                        if (getRender() != null)
893
                                bufferFactory.addFile(RasterDataset.open(getProjection(), fileName));
894
                } catch (NotSupportedExtensionException e) {
895
                        NotificationManager.addError("Formato no valido", e);
896
                } catch (RasterDriverException e) {
897
                        NotificationManager.addError("Formato no valido", e);
898
                }
899
        }
900

    
901
        /*
902
         * (non-Javadoc)
903
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
904
         */
905
        public void delFile(String fileName) {
906
                if (getRender() != null)
907
                        bufferFactory.removeFile(fileName);
908
        }
909

    
910
        /*
911
         * (non-Javadoc)
912
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
913
         */
914
        public Object getInfo(String key) {
915
                if (key.equals("DriverName"))
916
                        return "gvSIG Raster Driver";
917
                return null;
918
        }
919

    
920
        /*
921
         * (non-Javadoc)
922
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
923
         */
924
        public RasterFilterList getRenderFilterList(){
925
                return getRender().getFilterList();
926
        }
927

    
928
        /*
929
         * (non-Javadoc)
930
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getPixelSizeX()
931
         */
932
        public double[] getPxWidthByDataset() {
933
                return dataset.getWidth();
934
        }
935

    
936
        /*
937
         * (non-Javadoc)
938
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getPixelSizeY()
939
         */
940
        public double[] getPxHeightByDataset() {
941
                return dataset.getHeight();
942
        }
943

    
944
        /*
945
         * (non-Javadoc)
946
         * @see org.gvsig.raster.shared.IRasterOperations#getMetadata()
947
         */
948
        public DatasetMetadata[] getMetadata() {
949
                int count = dataset.getDatasetCount();
950
                DatasetMetadata[] metadata = new DatasetMetadata[count];
951
                for (int i = 0; i < count; i++) {
952
                        metadata[i] = dataset.getDataset(i).getMetadata();
953
                }
954
                return metadata;
955
        }
956

    
957
        /*
958
         * (non-Javadoc)
959
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
960
         */
961
        public int[] getBandCountFromDataset() {
962
                int count = dataset.getDatasetCount();
963
                int[] bands = new int[count];
964
                for (int i = 0; i < count; i++) {
965
                        bands[i] = dataset.getDataset(i).getBandCount();
966
                }
967
                return bands;
968
        }
969

    
970
        /*
971
         * (non-Javadoc)
972
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
973
         */
974
        public String getColourInterpretation(int band, int dataset) {
975
                if (this.dataset.getColorInterpretation(dataset) == null)
976
                        return "Undefined";
977
                return this.dataset.getColorInterpretation(dataset).get(band);
978
        }
979

    
980
        /*
981
         * (non-Javadoc)
982
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
983
         */
984
        public String getStringProjection() {
985
                try {
986
                        return dataset.getStringProjection();
987
                } catch (RasterDriverException e) {
988
                        NotificationManager.addError("No puedo obtener la proyecci?n asociada al dataset.", e);
989
                }
990
                return null;
991
        }
992

    
993
        /**
994
         * Obtiene el grid de la capa completa. Hay que tener cuidado porque cuando se hace esta
995
         * petici?n se carga un buffer con todos los datos de la capa. Este buffer puede ser 
996
         * cacheado o no dependiendo del tama?o de esta.
997
         * @param interpolated true si se solicita un grid interpolado y false si se solicita sin interpolar.
998
         * @return Grid.
999
         */
1000
        public Grid getFullGrid(boolean interpolated) {
1001
                BufferFactory bf = getDatasource();
1002
                bf.clearDrawableBand();
1003
                bf.setAllDrawableBands();
1004
                bf.setAreaOfInterest();
1005
                return new Grid(bf, interpolated);
1006
        }
1007

    
1008
        /*
1009
         * (non-Javadoc)
1010
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1011
         */
1012
        public Extent getFullRasterExtent() {
1013
                return new Extent(getFullExtent());
1014
        }
1015

    
1016

    
1017
        /**
1018
         * Devuelve el fichero asociado a la capa o null si no tiene.
1019
         * @return Fichero.
1020
         */
1021
        public File getFile() {
1022
                return (params instanceof File) ? ((File)params) : null;
1023
        }
1024

    
1025
        /**
1026
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1027
         * @param file Fichero a consultar
1028
         * @return true si es aceptado y false si no lo es.
1029
         */
1030
        public static boolean isFileAccepted(File file) {
1031
                return RasterDataset.fileIsSupported(file.getName());
1032
        }
1033

    
1034
        /*
1035
         * (non-Javadoc)
1036
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1037
         */
1038
        public boolean existColorTable() {
1039
                return this.getRender().existColorTable();
1040
        }
1041
}