Statistics
| Revision:

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

History | View | Annotate | Download (31 KB)

1 10740 nacho
/* 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 11647 nacho
import org.gvsig.raster.RasterLibrary;
41 11084 nacho
import org.gvsig.raster.buffer.BufferFactory;
42 11594 nacho
import org.gvsig.raster.dataset.FileNotOpenException;
43 11827 nacho
import org.gvsig.raster.dataset.IBuffer;
44 11594 nacho
import org.gvsig.raster.dataset.InvalidSetViewException;
45 11579 nacho
import org.gvsig.raster.dataset.MultiRasterDataset;
46 11647 nacho
import org.gvsig.raster.dataset.NotSupportedExtensionException;
47
import org.gvsig.raster.dataset.RasterDataset;
48 10940 nacho
import org.gvsig.raster.dataset.RasterDriverException;
49
import org.gvsig.raster.dataset.properties.DatasetMetadata;
50 11579 nacho
import org.gvsig.raster.grid.Grid;
51 12066 nacho
import org.gvsig.raster.grid.GridPalette;
52 10740 nacho
import org.gvsig.raster.grid.GridTransparency;
53
import org.gvsig.raster.grid.filter.RasterFilterList;
54 11827 nacho
import org.gvsig.raster.grid.filter.RasterFilterListManager;
55 12066 nacho
import org.gvsig.raster.grid.filter.bands.ColorTableListManager;
56 11827 nacho
import org.gvsig.raster.grid.filter.enhancement.EnhancementListManager;
57 10740 nacho
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 12253 nacho
import org.gvsig.raster.shared.IStatistics;
62 11647 nacho
import org.gvsig.raster.shared.ViewPortData;
63 10740 nacho
64
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
65 11594 nacho
import com.iver.andami.PluginServices;
66 10740 nacho
import com.iver.andami.messages.NotificationManager;
67 12225 nacho
import com.iver.andami.ui.mdiManager.IWindow;
68 11647 nacho
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
69 10740 nacho
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 11647 nacho
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
77 10740 nacho
import com.iver.cit.gvsig.fmap.layers.layerOperations.StringXMLItem;
78
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
79 11594 nacho
import com.iver.cit.gvsig.project.documents.view.gui.IView;
80
import com.iver.cit.gvsig.project.documents.view.gui.View;
81 10740 nacho
import com.iver.utiles.XMLEntity;
82
import com.iver.utiles.swing.threads.Cancellable;
83
/**
84 11647 nacho
 * Capa raster
85 10740 nacho
 * @author Nacho Brodin (nachobrodin@gmail.com)
86
 */
87 11647 nacho
public class FLyrRasterSE extends FLyrDefault implements IRasterProperties, IRasterDataset, InfoByPoint {
88 12108 bsanchez
        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 10740 nacho
110 11647 nacho
        static {
111
                 RasterLibrary.wakeUp();
112
        }
113 12050 bsanchez
114 10740 nacho
        /**
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 12050 bsanchez
        public static FLyrRasterSE createLayer(String layerName, Object params,
124 11647 nacho
                        IProjection proj) throws LoadLayerException {
125 10740 nacho
                FLyrRasterSE capa = new FLyrRasterSE();
126 11647 nacho
                capa.setLoadParams(params);
127 10740 nacho
                capa.setName(layerName);
128
                capa.setProjection(proj);
129
                capa.load();
130
                return capa;
131
        }
132 12050 bsanchez
133 10740 nacho
        /**
134 11647 nacho
         * Asigna los par?metros para la carga de la capa
135
         * @param param Par?metros.
136 10740 nacho
         */
137 11647 nacho
        public void setLoadParams(Object param){
138
                this.params = param;
139 10740 nacho
        }
140
141
        /**
142 12182 nacho
         * 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 11647 nacho
         * Redefine wakeUp de FLyrDefault
151 10740 nacho
         */
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 11647 nacho
        /*
172
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#load()
173 10740 nacho
         */
174 11647 nacho
        public void load() throws LoadLayerException{
175
                if (getProjection() != null) {
176
                        String fName = null;
177
                        int test = -1;
178 12068 bsanchez
                        if (params != null && params instanceof File) {
179
                                fName = ((File) params).getAbsolutePath();
180 11647 nacho
                                test = fName.indexOf("ecwp:");
181
                        }
182 10740 nacho
183 11647 nacho
                        if (test != -1) {
184 12068 bsanchez
                                String urlECW = fName.substring(test + 6);
185
                                fName = "ecwp://" + urlECW;
186 11647 nacho
                                System.err.println(test + " " + fName);
187 12068 bsanchez
                        }
188 12050 bsanchez
189 11647 nacho
                        try {
190 12068 bsanchez
                                if (params == null || params instanceof File)
191 11647 nacho
                                        dataset = MultiRasterDataset.open(getProjection(), fName);
192 12050 bsanchez
                                else
193 11777 nacho
                                        dataset = MultiRasterDataset.open(getProjection(), params);
194 11647 nacho
                        } 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 12068 bsanchez
                        if (dataset == null)
200 11647 nacho
                                throw new LoadLayerException("Formato no valido", new IOException());
201
                        bufferFactory = new BufferFactory(dataset);
202 11675 nacho
                        getRender();
203 11827 nacho
                        initFilters();
204 11647 nacho
                } else
205
                        throw new LoadLayerException("Proyecci?n no asignada", new IOException());
206 10740 nacho
        }
207 12050 bsanchez
208 10740 nacho
        /**
209 11647 nacho
         * Crea el objeto renderizador de raster
210
         * @return Rendering
211 10740 nacho
         */
212 11675 nacho
        public Rendering getRender() {
213 12068 bsanchez
                if (render == null)
214 11647 nacho
                        render = new Rendering(bufferFactory);
215 12050 bsanchez
                return render;
216 10740 nacho
        }
217 12050 bsanchez
218 11827 nacho
        /**
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 12066 nacho
                RasterFilterListManager filterManager = new RasterFilterListManager(filterList);
227 12068 bsanchez
228 12225 nacho
                if (this.getGeoRasterMultiDataset().getColorTables()[0] != null) {
229
                        GridPalette p = new GridPalette(getGeoRasterMultiDataset().getColorTables()[0]);
230 12066 nacho
                        ColorTableListManager ctm = new ColorTableListManager(filterManager);
231 12166 bsanchez
                        ctm.addColorTableFilter(p);
232 12066 nacho
                } else {
233 12068 bsanchez
                        if (getDataType()[0] != IBuffer.TYPE_BYTE) {
234 12066 nacho
                                IStatistics stats = getGeoRasterMultiDataset().getStatistics();
235
                                EnhancementListManager elm = new EnhancementListManager(filterManager);
236 12166 bsanchez
                                elm.addEnhancedFilter(false, stats, 0.0, getRender().getRenderBands());
237 12066 nacho
                        }
238 11827 nacho
                }
239 12050 bsanchez
240 11827 nacho
                getRender().setFilterList(filterList);
241
        }
242 10740 nacho
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 12068 bsanchez
        public void draw(BufferedImage image, Graphics2D g, ViewPort vp, Cancellable cancel, double scale) {
249 11647 nacho
                if (isWithinScale(scale)) {
250 12050 bsanchez
251 12068 bsanchez
                        if (status != null && firstLoad) {
252
                                if (mustTileDraw) {
253 10740 nacho
                                        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 12068 bsanchez
                                        for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
258 10740 nacho
                                                // drawing part
259
                                                try {
260
                                                        ViewPort vport = tiles.getTileViewPort(vp, tileNr);
261 12068 bsanchez
                                                        // g.setClip(tiles.getClip(tileNr).x, tiles.getClip(tileNr).y, tiles.getClip(tileNr).width - 5, tiles.getClip(tileNr).height);
262 11647 nacho
                                                        draw(image, g, vport, cancel);
263 10740 nacho
                                                } catch (NoninvertibleTransformException e) {
264
                                                        e.printStackTrace();
265
                                                }
266
                                        }
267 12068 bsanchez
                                } else
268 11647 nacho
                                        draw(image, g, vp, cancel);
269 11670 nacho
                                status.applyStatus(this);
270 10740 nacho
                                firstLoad = false;
271
                        }
272
273 12068 bsanchez
                        if (mustTileDraw) {
274 10740 nacho
                                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 12068 bsanchez
                                for (int tileNr = 0; tileNr < tiles.getNumTiles(); tileNr++) {
279 10740 nacho
                                        // drawing part
280
                                        try {
281
                                                ViewPort vport = tiles.getTileViewPort(vp, tileNr);
282 11647 nacho
                                                draw(image, g, vport, cancel);
283 10740 nacho
                                        } catch (NoninvertibleTransformException e) {
284
                                                e.printStackTrace();
285
                                        }
286
                                }
287 12068 bsanchez
                        } else
288 11647 nacho
                                draw(image, g, vp, cancel);
289 10740 nacho
290 12068 bsanchez
                        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 10740 nacho
                        }
297
                }
298
        }
299 12050 bsanchez
300 11647 nacho
        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 11675 nacho
                getRender().draw(g, vp2);
306 11647 nacho
        }
307 10740 nacho
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 11647 nacho
                return dataset.getExtent().toRectangle2D();
322 10740 nacho
        }
323
324
        /**
325 11600 nacho
         * Obtiene el valor del pixel del Image en la posici?n real x,y
326 10740 nacho
         * @param x Posici?n x
327
         * @param y Posici?n y
328
         * @return valor de pixel
329
         */
330 11594 nacho
        public int[] getPixel(double wcx, double wcy) {
331 12068 bsanchez
                int[] argb = { -1, -1, -1, -1 };
332
                if (wcx <= getMaxX() && wcx >= getMinX() && wcy <= getMaxY() && wcy >= getMinY()) {
333 11594 nacho
                        View theView = (View) PluginServices.getMDIManager().getActiveWindow();
334 12068 bsanchez
                        if (theView instanceof IView) {
335
                                // BufferedImage buf = ((IView) theView).getMapControl().getImage();
336 11594 nacho
                                Point2D p = ((IView) theView).getMapControl().getViewPort().fromMapPoint(wcx, wcy);
337 12068 bsanchez
                                return getPixel((int) p.getX(), (int) p.getY());
338 11600 nacho
                        }
339
                }
340
                return argb;
341
        }
342 12050 bsanchez
343 11600 nacho
        /**
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 12068 bsanchez
                int[] argb = { -1, -1, -1, -1 };
351 11840 nacho
                View theView = (View) PluginServices.getMDIManager().getActiveWindow();
352
                BufferedImage buf = null;
353 12068 bsanchez
                if (theView instanceof IView)
354 11840 nacho
                        buf = ((IView) theView).getMapControl().getImage();
355 12068 bsanchez
                if (pxx >= 0 && pxx < buf.getWidth() && pxy >= 0 && pxy < buf.getHeight()) {
356
                        if (theView instanceof IView) {
357 11600 nacho
                                int value = buf.getRGB(pxx, pxy);
358 11594 nacho
                                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 10740 nacho
        }
366
367 11647 nacho
        /*
368
         * (non-Javadoc)
369
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxX()
370
         */
371 10740 nacho
        public double getMaxX(){
372 12068 bsanchez
                return this.getFullExtent().getMaxX();
373 10740 nacho
        }
374
375 11647 nacho
        /*
376
         * (non-Javadoc)
377
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMaxY()
378
         */
379 10740 nacho
        public double getMaxY(){
380
                return this.getFullExtent().getMaxY();
381
        }
382
383 11647 nacho
        /*
384
         * (non-Javadoc)
385
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinX()
386
         */
387 10740 nacho
        public double getMinX(){
388 12068 bsanchez
                return this.getFullExtent().getMinX();
389 10740 nacho
        }
390
391 11647 nacho
        /*
392
         * (non-Javadoc)
393
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getMinY()
394
         */
395 10740 nacho
        public double getMinY(){
396 12068 bsanchez
                return this.getFullExtent().getMinY();
397 10740 nacho
        }
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 11647 nacho
        public String queryByPoint(Point p) {
404 12068 bsanchez
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
405 10740 nacho
406 11647 nacho
                ArrayList attr = getAttributes();
407 10740 nacho
                data += "  <raster\n";
408 11647 nacho
                data += "    File=\"" + getFile() + "\"\n";
409
                for (int i = 0; i < attr.size(); i++) {
410 12068 bsanchez
                        Object[] a = (Object[]) attr.get(i);
411 10740 nacho
412 11647 nacho
                        data += "    " + a[0].toString() + "=";
413 10740 nacho
                        if (a[1].toString() instanceof String)
414 11647 nacho
                                data += "\"" + a[1].toString() + "\"\n";
415 10740 nacho
                        else
416 11647 nacho
                                data += a[1].toString() + "\n";
417 10740 nacho
                }
418 11647 nacho
                data += "    Point=\"" + posX + " , " + posY + "\"\n";
419
                data += "    Point_WC=\"" + posXWC + " , " + posYWC + "\"\n";
420
                data += "    RGB=\"" + r + ", " + g + ", " + b + "\"\n";
421 10740 nacho
                data += "  />\n";
422
423 11647 nacho
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
424 10740 nacho
                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 12068 bsanchez
                        pReal.getY() < this.getMaxY()) {
435 11647 nacho
                        ArrayList attr = getAttributes();
436 10740 nacho
                        int w = 0, h = 0;
437 11840 nacho
                        for (int i = 0; i < attr.size(); i++) {
438 12068 bsanchez
                                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 10740 nacho
                        }
444
                        px = new Point2D.Double();
445 11647 nacho
                        px.setLocation( ((pReal.getX() - this.getMinX()) * w) / getWCWidth(),
446
                                                        ((this.getMaxY() - pReal.getY()) * h) / getWCHeight());
447 10740 nacho
                }
448 12068 bsanchez
                int[] rgb = getPixel((int) p.getX(), (int) p.getY());
449 10740 nacho
450
                StringXMLItem[] item = new StringXMLItem[1];
451 11840 nacho
                String data = "<file:" + normalizeAsXMLTag(getName()) + ">\n";
452 10740 nacho
453
                data += "  <raster\n";
454 11840 nacho
                data += "    View_Point=\"" + p.getX() + " , " + p.getY() + "\"\n";
455 12068 bsanchez
                data += "    World_Point=\"" + pReal.getX() + " , " + pReal.getY() + "\"\n";
456
                if (px == null)
457 10740 nacho
                        data += "    Pixel_Point=\"Out\"\n";
458
                else
459 12068 bsanchez
                        data += "    Pixel_Point=\"" + (int) px.getX() + " , " + (int) px.getY() + "\"\n";
460 11840 nacho
                data += "    RGB=\"" + rgb[1] + "  " + rgb[2] + "  " + rgb[3] + "\"\n";
461 10740 nacho
                data += "    Band_Value=\"";
462 11594 nacho
                try {
463 12174 nacho
                        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 11594 nacho
                        }
477
                } catch (RasterDriverException ex) {
478 12050 bsanchez
479 11594 nacho
                } catch (InvalidSetViewException ex) {
480 12050 bsanchez
481 11594 nacho
                } catch (FileNotOpenException ex) {
482 12050 bsanchez
483 10740 nacho
                }
484
                data += "\"\n";
485
                data += "  />\n";
486 11647 nacho
                data += "</file:" + normalizeAsXMLTag(getName()) + ">\n";
487 10740 nacho
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 11670 nacho
                return s.replaceAll("[^a-zA-Z0-9]", "");
500 10740 nacho
        }
501
502
        /**
503
         * Obtiene atributos a partir de un georasterfile
504
         * @return
505
         */
506
        public ArrayList getAttributes() {
507 11647 nacho
                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 10740 nacho
        }
519
520
        /**
521 12225 nacho
         * Escribe en el proyecto la capa actual
522 10740 nacho
         * @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 11647 nacho
                xml.putProperty("file", getFile());
528
                xml.putProperty("driverName", "gvSIG Raster Driver");
529 10740 nacho
530 12068 bsanchez
                // Si no hay ning?n Status aplicamos el StatusLayerRaster que se usa por defecto
531
                if (status == null)
532 10740 nacho
                        status = new StatusLayerRaster();
533 11670 nacho
                status.getXMLEntity(xml, true, this);
534 12050 bsanchez
535 10740 nacho
                return xml;
536
        }
537
538 12068 bsanchez
        public void setXMLEntity03(XMLEntity xml) throws XMLException {
539 10740 nacho
        }
540
541 12225 nacho
        /**
542
         * Recupera de disco los datos de la capa.
543
         */
544 11670 nacho
        public void setXMLEntity(XMLEntity xml)throws XMLException {
545 10740 nacho
                super.setXMLEntity(xml);
546 12050 bsanchez
547 11670 nacho
                params = new File(xml.getStringProperty("file"));
548 10740 nacho
549 11647 nacho
                // Para notificar al adapter-driver cual es la proyecci?n.
550
                setProjection(super.getProjection());
551 10740 nacho
552 11647 nacho
                //Inicializamos la clase a la que se usa por defecto para
553
                //compatibilidad con proyectos antiguos
554
                String claseStr = StatusLayerRaster.defaultClass;
555 12050 bsanchez
                if (xml.contains("raster.class"))
556 11647 nacho
                        claseStr = xml.getStringProperty("raster.class");
557 12050 bsanchez
558 12068 bsanchez
                if (status != null)
559 11670 nacho
                        status.setXMLEntity(xml, this);
560 12068 bsanchez
                else {
561
                        // Cuando cargamos un proyecto
562 10740 nacho
563 12068 bsanchez
                        if (claseStr != null && !claseStr.equals("")) {
564
                                try {
565 11647 nacho
                                        Class clase = Class.forName(claseStr);
566
                                        Constructor constr = clase.getConstructor(null);
567 12068 bsanchez
                                        status = (StatusRasterInterface) constr.newInstance(null);
568
                                        if (status != null)
569 11670 nacho
                                                status.setXMLEntity(xml, this);
570 12068 bsanchez
                                } catch (ClassNotFoundException exc) {
571 11647 nacho
                                        exc.printStackTrace();
572 12068 bsanchez
                                } catch (InstantiationException exc) {
573 11647 nacho
                                        exc.printStackTrace();
574 12068 bsanchez
                                } catch (IllegalAccessException exc) {
575 11647 nacho
                                        exc.printStackTrace();
576 12068 bsanchez
                                } catch (NoSuchMethodException exc) {
577 11647 nacho
                                        exc.printStackTrace();
578 12068 bsanchez
                                } catch (InvocationTargetException exc) {
579 11647 nacho
                                        exc.printStackTrace();
580
                                }
581
                        }
582 10740 nacho
                }
583 11647 nacho
                firstLoad = true;
584
585 10740 nacho
        }
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 12068 bsanchez
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet propeties) {
591 10740 nacho
592 12068 bsanchez
                if (!isVisible() || !isWithinScale(scale))
593
                        return;
594
595 10740 nacho
                isPrinting = true;
596
                if (!mustTilePrint) {
597 12068 bsanchez
                        draw(null, g, viewPort, cancel,scale);
598 10740 nacho
                } else {
599 12068 bsanchez
                        // 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 10740 nacho
                        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 12068 bsanchez
                        //stats.history.add(stats.new History(getName(), stats.minBandValue, stats.maxBandValue, stats.secondMinBandValue, stats.secondMaxBandValue));
612 10740 nacho
613
614 12068 bsanchez
                        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 10740 nacho
                                } catch (NoninvertibleTransformException e) {
620
                                        e.printStackTrace();
621
                                }
622 12068 bsanchez
                        }
623 10740 nacho
                        /*if(stats != null){
624
                                getSource().getFilterStack().getStats().history.clear();
625
                                stats = getSource().getFilterStack().getStats();
626
                        }*/
627
                }
628 12068 bsanchez
                isPrinting = false;
629 10740 nacho
        }
630
631 12068 bsanchez
        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 10740 nacho
637 12068 bsanchez
                int numW, numH;
638
                int stepX, stepY;
639
                int xProv, yProv;
640
                int A = 1500;
641
                int H = 1500;
642
                int altoAux, anchoAux;
643 10740 nacho
644 12068 bsanchez
                AffineTransform mat = (AffineTransform) viewPort.getAffineTransform().clone();
645 10740 nacho
646 12068 bsanchez
                // 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 10740 nacho
651 12068 bsanchez
                double[] srcPts = new double[8];
652
                double[] dstPts = new double[8];
653 10740 nacho
654 12068 bsanchez
                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 10740 nacho
661 12068 bsanchez
                        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 10740 nacho
668 12068 bsanchez
                                //Rectangle newRect = new Rectangle(xProv, yProv, anchoAux, altoAux);
669 10740 nacho
670 12068 bsanchez
                                // 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 10740 nacho
680 12068 bsanchez
                                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 10740 nacho
685 12068 bsanchez
                                        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 10740 nacho
692 12068 bsanchez
                                } catch (NoninvertibleTransformException e) {
693
                                        e.printStackTrace();
694
                                }
695
                                // Fin parte que dibuja
696
                                xProv = xProv + A;
697
                        }
698
                        yProv = yProv + H;
699
                }
700 10740 nacho
        }
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 12225 nacho
                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 12068 bsanchez
                if (this.isRemoveRasterFlag()) {
718 11647 nacho
                        dataset.close();
719 10740 nacho
                        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 11647 nacho
                return dataset.isGeoreferenced();
767 10740 nacho
        }
768 12050 bsanchez
769 10740 nacho
        /**
770
         * Get datasource object
771
         * @return
772
         */
773 11084 nacho
        public BufferFactory getDatasource(){
774 11647 nacho
                return bufferFactory;
775 12050 bsanchez
        }
776
777 10740 nacho
        /*
778
         * (non-Javadoc)
779
         * @see org.gvsig.fmap.raster.IRasterOperations#getPXHeight()
780
         */
781
        public double getPxHeight() {
782 11647 nacho
                return (dataset.getHeight() != null && dataset.getHeight().length >= 1) ? dataset.getHeight()[0] : 0;
783 10740 nacho
        }
784
785
        /*
786
         * (non-Javadoc)
787
         * @see org.gvsig.fmap.raster.IRasterOperations#getPxWidth()
788
         */
789
        public double getPxWidth() {
790 11647 nacho
                return (dataset.getWidth() != null && dataset.getWidth().length >= 1) ? dataset.getWidth()[0] : 0;
791 10740 nacho
        }
792
793
        /*
794
         * (non-Javadoc)
795
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCHeight()
796
         */
797
        public double getWCHeight() {
798 11647 nacho
                return getFullExtent().getHeight();
799 10740 nacho
        }
800
801
        /*
802
         * (non-Javadoc)
803
         * @see org.gvsig.fmap.raster.IGeoDimension#getWCWidth()
804
         */
805
        public double getWCWidth() {
806 11647 nacho
                return getFullExtent().getWidth();
807 10740 nacho
        }
808 12050 bsanchez
809 10740 nacho
        /*
810
         * (non-Javadoc)
811
         * @see org.gvsig.fmap.raster.IRasterFile#getFileSize()
812
         */
813
        public long[] getFileSize(){
814 11647 nacho
                int nFiles = dataset.getDatasetCount();
815 10740 nacho
                long[] s = new long[nFiles];
816 12068 bsanchez
                for (int i = 0; i < nFiles; i++)
817 11647 nacho
                        s[i] = dataset.getDataset(i).getFileSize();
818 10740 nacho
                return s;
819
        }
820 12050 bsanchez
821 10740 nacho
        /*
822
         * (non-Javadoc)
823
         * @see org.gvsig.fmap.raster.IRasterFile#getFileName()
824
         */
825
        public String[] getFileName(){
826 11647 nacho
                int nFiles = dataset.getDatasetCount();
827 10740 nacho
                String[] s = new String[nFiles];
828 12068 bsanchez
                for (int i = 0; i < nFiles; i++)
829 11647 nacho
                        s[i] = dataset.getDataset(i).getFName();
830 10740 nacho
                return s;
831
        }
832 12050 bsanchez
833 10740 nacho
        /*
834
         * (non-Javadoc)
835
         * @see org.gvsig.fmap.raster.IRasterFile#getFileCount()
836
         */
837
        public int getFileCount(){
838 11647 nacho
                return dataset.getDatasetCount();
839 10740 nacho
        }
840 12050 bsanchez
841 10740 nacho
        /*
842
         * (non-Javadoc)
843
         * @see org.gvsig.fmap.raster.IRasterFile#getFileFormat()
844
         */
845
        public String getFileFormat(){
846 11647 nacho
                String fName = dataset.getDataset(0).getFName();
847 10740 nacho
                int index = fName.lastIndexOf(".") + 1;
848
                String ext = null;
849 12068 bsanchez
                if (index > 0)
850 10740 nacho
                        ext = fName.substring(fName.lastIndexOf(".") + 1, fName.length());
851
                return ext;
852
        }
853 12050 bsanchez
854 10740 nacho
        /*
855
         * (non-Javadoc)
856
         * @see org.gvsig.fmap.raster.IRasterOperations#getBandCount()
857
         */
858
        public int getBandCount(){
859 11647 nacho
                return dataset.getBandCount();
860 10740 nacho
        }
861 12050 bsanchez
862 10740 nacho
        /*
863
         * (non-Javadoc)
864
         * @see org.gvsig.fmap.raster.IRasterOperations#getDatatype()
865
         */
866
        public int[] getDataType(){
867 11647 nacho
                return dataset.getDataType();
868 10740 nacho
        }
869 12050 bsanchez
870 10740 nacho
        /*
871
         * (non-Javadoc)
872
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderTransparency()
873
         */
874
        public GridTransparency getRenderTransparency(){
875 11647 nacho
                return render.getLastTransparency();
876 10740 nacho
        }
877
878
        /*
879
         * (non-Javadoc)
880
         * @see org.gvsig.fmap.raster.IRasterDataset#getGeoRasterMultiDataset()
881
         */
882 11482 nacho
        public MultiRasterDataset getGeoRasterMultiDataset() {
883 11647 nacho
                return dataset;
884 10740 nacho
        }
885 12050 bsanchez
886 10740 nacho
        /*
887
         * (non-Javadoc)
888
         * @see org.gvsig.fmap.raster.IRasterDataset#addFile(java.lang.String)
889
         */
890 11670 nacho
        public void addFile(String fileName) {
891 12068 bsanchez
                try {
892
                        if (getRender() != null)
893 11647 nacho
                                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 10740 nacho
                }
899
        }
900
901
        /*
902
         * (non-Javadoc)
903
         * @see org.gvsig.fmap.raster.IRasterDataset#delFile(java.lang.String)
904
         */
905 11670 nacho
        public void delFile(String fileName) {
906 12068 bsanchez
                if (getRender() != null)
907 11647 nacho
                        bufferFactory.removeFile(fileName);
908 10740 nacho
        }
909
910
        /*
911
         * (non-Javadoc)
912
         * @see org.gvsig.fmap.raster.IRasterDataset#getInfo(java.lang.String)
913
         */
914
        public Object getInfo(String key) {
915 12068 bsanchez
                if (key.equals("DriverName"))
916 11647 nacho
                        return "gvSIG Raster Driver";
917 10740 nacho
                return null;
918
        }
919 12050 bsanchez
920 10740 nacho
        /*
921
         * (non-Javadoc)
922
         * @see org.gvsig.fmap.raster.IRasterRendering#getRenderFilterList()
923
         */
924
        public RasterFilterList getRenderFilterList(){
925 11675 nacho
                return getRender().getFilterList();
926 10740 nacho
        }
927
928
        /*
929
         * (non-Javadoc)
930
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getPixelSizeX()
931
         */
932
        public double[] getPxWidthByDataset() {
933 11647 nacho
                return dataset.getWidth();
934 10740 nacho
        }
935
936
        /*
937
         * (non-Javadoc)
938
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getPixelSizeY()
939
         */
940
        public double[] getPxHeightByDataset() {
941 11647 nacho
                return dataset.getHeight();
942 10740 nacho
        }
943
944
        /*
945
         * (non-Javadoc)
946
         * @see org.gvsig.raster.shared.IRasterOperations#getMetadata()
947
         */
948
        public DatasetMetadata[] getMetadata() {
949 11647 nacho
                int count = dataset.getDatasetCount();
950 10740 nacho
                DatasetMetadata[] metadata = new DatasetMetadata[count];
951 11647 nacho
                for (int i = 0; i < count; i++) {
952
                        metadata[i] = dataset.getDataset(i).getMetadata();
953 10740 nacho
                }
954
                return metadata;
955
        }
956
957
        /*
958
         * (non-Javadoc)
959
         * @see org.gvsig.raster.shared.IRasterOperations#getBandCountFromDataset()
960
         */
961
        public int[] getBandCountFromDataset() {
962 11647 nacho
                int count = dataset.getDatasetCount();
963 10740 nacho
                int[] bands = new int[count];
964 11647 nacho
                for (int i = 0; i < count; i++) {
965
                        bands[i] = dataset.getDataset(i).getBandCount();
966 10740 nacho
                }
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 12050 bsanchez
                if (this.dataset.getColorInterpretation(dataset) == null)
976 11647 nacho
                        return "Undefined";
977
                return this.dataset.getColorInterpretation(dataset).get(band);
978 10740 nacho
        }
979 12050 bsanchez
980 11647 nacho
        /*
981
         * (non-Javadoc)
982
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getStringProjection()
983
         */
984 10740 nacho
        public String getStringProjection() {
985
                try {
986 11647 nacho
                        return dataset.getStringProjection();
987 10740 nacho
                } catch (RasterDriverException e) {
988 11647 nacho
                        NotificationManager.addError("No puedo obtener la proyecci?n asociada al dataset.", e);
989 10740 nacho
                }
990
                return null;
991
        }
992 12050 bsanchez
993 11173 nacho
        /**
994 11579 nacho
         * 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 11647 nacho
1008 11670 nacho
        /*
1009
         * (non-Javadoc)
1010
         * @see org.gvsig.raster.shared.IRasterGeoOperations#getFullRasterExtent()
1011
         */
1012 11647 nacho
        public Extent getFullRasterExtent() {
1013
                return new Extent(getFullExtent());
1014
        }
1015
1016 12050 bsanchez
1017 11647 nacho
        /**
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 12050 bsanchez
1025 11647 nacho
        /**
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 11713 nacho
1034 12035 nacho
        /*
1035
         * (non-Javadoc)
1036
         * @see org.gvsig.raster.shared.IRasterRendering#existColorTable()
1037
         */
1038
        public boolean existColorTable() {
1039
                return this.getRender().existColorTable();
1040
        }
1041 10740 nacho
}