Statistics
| Revision:

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

History | View | Annotate | Download (31.2 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2007 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 */
19
package org.gvsig.fmap.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.InvalidSetViewException;
45
import org.gvsig.raster.dataset.MultiRasterDataset;
46
import org.gvsig.raster.dataset.NotSupportedExtensionException;
47
import org.gvsig.raster.dataset.RasterDataset;
48
import org.gvsig.raster.dataset.RasterDriverException;
49
import org.gvsig.raster.dataset.properties.DatasetMetadata;
50
import org.gvsig.raster.grid.Grid;
51
import org.gvsig.raster.grid.GridPalette;
52
import org.gvsig.raster.grid.GridTransparency;
53
import org.gvsig.raster.grid.filter.RasterFilterList;
54
import org.gvsig.raster.grid.filter.RasterFilterListManager;
55
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
56
import org.gvsig.raster.grid.filter.enhancement.EnhancementListManager;
57
import org.gvsig.raster.grid.render.Rendering;
58
import org.gvsig.raster.shared.Extent;
59
import org.gvsig.raster.shared.IRasterDataset;
60
import org.gvsig.raster.shared.IRasterProperties;
61
import org.gvsig.raster.shared.IStatistics;
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

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

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

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

    
142
        /**
143
         * Obtiene los par?metros para la carga de la capa
144
         * @return param Par?metros.
145
         */
146
        public Object getLoadParams() {
147
                return params;
148
        }
149

    
150
        /**
151
         * Redefine wakeUp de FLyrDefault
152
         */
153
        public void wakeUp(){
154
        }
155

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
480
                } catch (InvalidSetViewException ex) {
481

    
482
                } catch (FileNotOpenException ex) {
483

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

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

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

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

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

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

    
536
                return xml;
537
        }
538

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

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

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

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

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

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

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

    
586
        }
587

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

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

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

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

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

    
614

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

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

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

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

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

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

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

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

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

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

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

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

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

    
703
        /**
704
         * Borra de la lista de listeners el que se pasa como par?metro.
705
         *
706
         * @param o LayerListener a borrar.
707
         *
708
         * @return True si ha sido correcto el borrado del Listener.
709
         */
710
        public boolean removeLayerListener(LayerListener o) {
711
                //Salva a RMF
712
                try {
713
                        this.getGeoRasterMultiDataset().saveRmfModification();
714
                } catch (IOException e) {
715
                        //No se ha salvado nada
716
                }
717

    
718
                //Cierra todas las ventanas asociadas a la capa
719
                IWindow[] wList = PluginServices.getMDIManager().getAllWindows();
720
                for (int i = 0; i < wList.length; i++) {
721
                        String name = wList[i].getWindowInfo().getAdditionalInfo();
722
                        if( name != null && name.compareTo(getName()) == 0)
723
                                PluginServices.getMDIManager().closeWindow(wList[i]);
724
                }
725

    
726
                if (this.isRemoveRasterFlag()) {
727
                        dataset.close();
728
                        this.setRemoveRasterFlag(true);
729
                }
730
                return super.layerListeners.remove(o);
731
        }
732

    
733
        /**
734
         * @return Returns the removeRasterFlag.
735
         */
736
        public boolean isRemoveRasterFlag() {
737
                return removeRasterFlag;
738
        }
739

    
740
        /**
741
         * Asigna el valor del flag que dice si destruimos la memoria del raster
742
         * al eliminarlo del TOC o  no.
743
         * @param removeRasterFlag The removeRasterFlag to set.
744
         */
745
        public void setRemoveRasterFlag(boolean removeRasterFlag) {
746
                this.removeRasterFlag = removeRasterFlag;
747
        }
748

    
749
        public ImageIcon getTocImageIcon() {
750
                return new ImageIcon(MapControl.class.getResource("images/icolayerRaster.PNG"));
751
        }
752

    
753
        /*
754
         *  (non-Javadoc)
755
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#getTileSize()
756
         */
757
        public int[] getTileSize() {
758
                int[] size = {maxTileDrawWidth, maxTileDrawHeight};
759
                return size;
760
        }
761

    
762
        /*
763
         *  (non-Javadoc)
764
         * @see com.iver.cit.gvsig.fmap.layers.RasterOperations#isTiled()
765
         */
766
        public boolean isTiled() {
767
                return mustTileDraw;
768
        }
769

    
770
        /**
771
         * Obtiene el flag que dice si la imagen est? o no georreferenciada
772
         * @return true si est? georreferenciada y false si no lo est?.
773
         */
774
        public boolean isGeoreferenced() {
775
                return dataset.isGeoreferenced();
776
        }
777

    
778
        /**
779
         * Get datasource object
780
         * @return
781
         */
782
        public BufferFactory getDatasource(){
783
                return bufferFactory;
784
        }
785

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

    
794
        /*
795
         * (non-Javadoc)
796
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
797
         */
798
        public double getPxWidth() {
799
                return (dataset.getWidth() != null && dataset.getWidth().length >= 1) ? dataset.getWidth()[0] : 0;
800
        }
801

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

    
810
        /*
811
         * (non-Javadoc)
812
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
813
         */
814
        public double getWCWidth() {
815
                return getFullExtent().getWidth();
816
        }
817

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

    
830
        /*
831
         * (non-Javadoc)
832
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
833
         */
834
        public String[] getFileName(){
835
                int nFiles = dataset.getDatasetCount();
836
                String[] s = new String[nFiles];
837
                for (int i = 0; i < nFiles; i++)
838
                        s[i] = dataset.getDataset(i).getFName();
839
                return s;
840
        }
841

    
842
        /*
843
         * (non-Javadoc)
844
         * @see org.gvsig.fmap.raster.IRasterFile#getFileCount()
845
         */
846
        public int getFileCount(){
847
                return dataset.getDatasetCount();
848
        }
849

    
850
        /*
851
         * (non-Javadoc)
852
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
853
         */
854
        public String getFileFormat(){
855
                String fName = dataset.getDataset(0).getFName();
856
                int index = fName.lastIndexOf(".") + 1;
857
                String ext = null;
858
                if (index > 0)
859
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
860
                return ext;
861
        }
862

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

    
871
        /*
872
         * (non-Javadoc)
873
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
874
         */
875
        public int[] getDataType(){
876
                return dataset.getDataType();
877
        }
878

    
879
        /*
880
         * (non-Javadoc)
881
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
882
         */
883
        public GridTransparency getRenderTransparency(){
884
                return render.getLastTransparency();
885
        }
886

    
887
        /*
888
         * (non-Javadoc)
889
         * @see org.gvsig.fmap.raster.IRasterDataset#getGeoRasterMultiDataset()
890
         */
891
        public MultiRasterDataset getGeoRasterMultiDataset() {
892
                return dataset;
893
        }
894

    
895
        /*
896
         * (non-Javadoc)
897
         * @see org.gvsig.fmap.raster.IRasterDataset#addFile(java.lang.String)
898
         */
899
        public void addFile(String fileName) {
900
                try {
901
                        if (getRender() != null)
902
                                bufferFactory.addFile(RasterDataset.open(getProjection(), fileName));
903
                } catch (NotSupportedExtensionException e) {
904
                        NotificationManager.addError("Formato no valido", e);
905
                } catch (RasterDriverException e) {
906
                        NotificationManager.addError("Formato no valido", e);
907
                }
908
        }
909

    
910
        /*
911
         * (non-Javadoc)
912
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
913
         */
914
        public void delFile(String fileName) {
915
                if (getRender() != null)
916
                        bufferFactory.removeFile(fileName);
917
        }
918

    
919
        /*
920
         * (non-Javadoc)
921
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
922
         */
923
        public Object getInfo(String key) {
924
                if (key.equals("DriverName"))
925
                        return "gvSIG Raster Driver";
926
                return null;
927
        }
928

    
929
        /*
930
         * (non-Javadoc)
931
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
932
         */
933
        public RasterFilterList getRenderFilterList(){
934
                return getRender().getFilterList();
935
        }
936

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

    
945
        /*
946
         * (non-Javadoc)
947
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getPixelSizeY()
948
         */
949
        public double[] getPxHeightByDataset() {
950
                return dataset.getHeight();
951
        }
952

    
953
        /*
954
         * (non-Javadoc)
955
         * @see org.gvsig.raster.shared.IRasterOperations#getMetadata()
956
         */
957
        public DatasetMetadata[] getMetadata() {
958
                int count = dataset.getDatasetCount();
959
                DatasetMetadata[] metadata = new DatasetMetadata[count];
960
                for (int i = 0; i < count; i++) {
961
                        metadata[i] = dataset.getDataset(i).getMetadata();
962
                }
963
                return metadata;
964
        }
965

    
966
        /*
967
         * (non-Javadoc)
968
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
969
         */
970
        public int[] getBandCountFromDataset() {
971
                int count = dataset.getDatasetCount();
972
                int[] bands = new int[count];
973
                for (int i = 0; i < count; i++) {
974
                        bands[i] = dataset.getDataset(i).getBandCount();
975
                }
976
                return bands;
977
        }
978

    
979
        /*
980
         * (non-Javadoc)
981
         * @see org.gvsig.raster.shared.IRasterOperations#getColourInterpretation(int, int)
982
         */
983
        public String getColourInterpretation(int band, int dataset) {
984
                if (this.dataset.getColorInterpretation(dataset) == null)
985
                        return "Undefined";
986
                return this.dataset.getColorInterpretation(dataset).get(band);
987
        }
988

    
989
        /*
990
         * (non-Javadoc)
991
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
992
         */
993
        public String getStringProjection() {
994
                try {
995
                        return dataset.getStringProjection();
996
                } catch (RasterDriverException e) {
997
                        NotificationManager.addError("No puedo obtener la proyecci?n asociada al dataset.", e);
998
                }
999
                return null;
1000
        }
1001

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

    
1017
        /*
1018
         * (non-Javadoc)
1019
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1020
         */
1021
        public Extent getFullRasterExtent() {
1022
                return new Extent(getFullExtent());
1023
        }
1024

    
1025

    
1026
        /**
1027
         * Devuelve el fichero asociado a la capa o null si no tiene.
1028
         * @return Fichero.
1029
         */
1030
        public File getFile() {
1031
                return (params instanceof File) ? ((File)params) : null;
1032
        }
1033

    
1034
        /**
1035
         * Consulta si un fichero es aceptado o no para este tipo de capa.
1036
         * @param file Fichero a consultar
1037
         * @return true si es aceptado y false si no lo es.
1038
         */
1039
        public static boolean isFileAccepted(File file) {
1040
                return RasterDataset.fileIsSupported(file.getName());
1041
        }
1042

    
1043
        /*
1044
         * (non-Javadoc)
1045
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1046
         */
1047
        public boolean existColorTable() {
1048
                return this.getRender().existColorTable();
1049
        }
1050
}