Statistics
| Revision:

gvsig-raster / org.gvsig.raster.tools / trunk / org.gvsig.raster.tools / org.gvsig.raster.tools.app / org.gvsig.raster.tools.app.basic / src / main / java / org / gvsig / raster / tools / app / basic / raster / process / FilterProcess.java @ 1864

History | View | Annotate | Download (13.2 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
* 
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
* 
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
* 
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
19
* MA  02110-1301, USA.
20
* 
21
*/
22
package org.gvsig.raster.tools.app.basic.raster.process;
23

    
24
import java.io.IOException;
25
import java.util.ArrayList;
26

    
27
import javax.swing.SwingUtilities;
28

    
29
import org.gvsig.andami.PluginServices;
30
import org.gvsig.fmap.dal.coverage.RasterLocator;
31
import org.gvsig.fmap.dal.coverage.RasterManager;
32
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
33
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
34
import org.gvsig.fmap.dal.coverage.exception.FilterManagerException;
35
import org.gvsig.fmap.dal.coverage.exception.FilterTypeException;
36
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
37
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
38
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
39
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
40
import org.gvsig.fmap.dal.coverage.grid.Grid;
41
import org.gvsig.fmap.dal.coverage.grid.RasterFilterList;
42
import org.gvsig.fmap.dal.coverage.grid.RasterFilterListManager;
43
import org.gvsig.fmap.dal.coverage.store.DataServerWriter;
44
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
45
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
46
import org.gvsig.fmap.dal.coverage.store.RasterWriter;
47
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
48
import org.gvsig.fmap.dal.exception.CloseException;
49
import org.gvsig.raster.fmap.layers.FLyrRaster;
50
import org.gvsig.raster.tools.app.basic.RasterToolsUtil;
51
import org.gvsig.raster.tools.app.basic.raster.bean.previewbase.ParamStruct;
52

    
53
/**
54
 * Clase donde se hara todo el proceso de aplicar una lista de filtros a una
55
 * capa. Muestra una ventana de dialogo de incremento informativa.
56
 *
57
 * @version 24/05/2007
58
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
59
 */
60
public class FilterProcess extends RasterProcess {
61
        private String                   filename         = "";
62
        private RasterDataStore          rasterDataSource = null;
63
        private ArrayList<ParamStruct>   listFilterUsed   = null;
64

    
65
        private RasterFilterList         rasterFilterList = null;
66
        private RasterWriter             geoRasterWriter  = null;
67
        private FLyrRaster               lyr              = null;
68
        private RasterManager            rManager         = RasterLocator.getManager();
69

    
70
        /*
71
         * (non-Javadoc)
72
         * @see org.gvsig.rastertools.RasterProcess#init()
73
         */
74
        @SuppressWarnings("unchecked")
75
        public void init() {
76
                filename = getStringParam("filename");
77
                listFilterUsed = (ArrayList) getParam("listfilterused");
78
                lyr = (FLyrRaster)getParam("layer");
79
                rasterDataSource = lyr.getDataStore();
80
        }
81

    
82
        /**
83
         * Devuelve una interpretacion de color. Es usado cuando no conseguimos un
84
         * rendering y no podemos saber que interpretacion l?gica ten?a antes.
85
         * @param geoRasterWriter
86
         */
87
        private ColorInterpretation getColorIntepretation(Buffer buffer, Grid grid) {
88
                ColorInterpretation colorInterpretation = null;
89

    
90
                do {
91
                        // Si tiene una tabla de color asignamos las tres bandas
92
                        if (grid.getFilterList().isActive("colortable")) {
93
                                colorInterpretation = rManager.getDataStructFactory().createColorInterpretation(
94
                                                new String[] { 
95
                                                                ColorInterpretation.RED_BAND, 
96
                                                                ColorInterpretation.GREEN_BAND, 
97
                                                                ColorInterpretation.BLUE_BAND 
98
                                                                });
99
                                break;
100
                        }
101

    
102
                        // Si el numero de bandas coincide asignamos la misma interpretacion que tenia antes
103
                        if (buffer.getBandCount() == rasterDataSource.getBandCount()) {
104
                                colorInterpretation = rasterDataSource.getColorInterpretation();
105
                                break;
106
                        }
107

    
108
                        String[] colorInterp = new String[rasterDataSource.getColorInterpretation().getValues().length];
109

    
110
                        for (int i = 0; i < rasterDataSource.getColorInterpretation().getValues().length; i++) {
111
                                if (rasterDataSource.getColorInterpretation().getValues()[i].equals(ColorInterpretation.UNDEF_BAND)) {
112
                                        colorInterp[i] = ColorInterpretation.GRAY_BAND;
113
                                        continue;
114
                                }
115
                                colorInterp[i] = rasterDataSource.getColorInterpretation().getValues()[i];
116
                        }
117
                        colorInterpretation = rManager.getDataStructFactory().createColorInterpretation(colorInterp);
118
                } while (false);
119

    
120
                return colorInterpretation;
121
        }
122
        
123
        /*
124
         * (non-Javadoc)
125
         * @see org.gvsig.rastertools.RasterProcess#process()
126
         */
127
        public void process() throws ProcessInterruptedException, ProcessException {
128
                DataServerWriter writerBufferServer = null;
129
                if(lyr != null)
130
                        lyr.setReadingData(Thread.currentThread().getId() + "");
131

    
132
                RasterDataStore dstoreCopy = null;
133
                RasterQuery query          = null;
134
                Buffer buffer              = null;
135
                Buffer buff                = null;
136
                Grid grid                  = null;
137
                Buffer alpha               = null;
138
                try {
139
                        insertLineLog(RasterToolsUtil.getText(this, "leyendo_raster"));
140
                        
141
                        //Creaci?n del BufferFactory
142
                        dstoreCopy = rasterDataSource.newDataStore();
143
                        query = rManager.createQuery();
144
                        //if (!RasterBuffer.loadInMemory(dsetCopy))
145
                        query.setReadOnly(true);
146

    
147
                        //Asignaci?n de bandas
148
                        int[] renderBands = lyr.getRender().getRenderBands();
149
                        if (renderBands != null) {
150
                                // Si es gris, se reduce a una sola banda
151
                                if ((renderBands.length == 3) && (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2])) 
152
                                        renderBands = new int[] { renderBands[0] };
153
                                query.setDrawableBands(renderBands);
154
                        } else
155
                                query.setAllDrawableBands();
156

    
157
                        query.setAreaOfInterest();
158
                        
159
                        buff = dstoreCopy.query(query);
160
                        if(buff.isReadOnlyBuffer()) 
161
                                buff.addDrawableBands(renderBands);
162
                        
163
                        grid = rManager.createGrid(buff, dstoreCopy, true);
164

    
165
                        //Obtenemos la lista de filtros
166
                        rasterFilterList = grid.getFilterList();
167
                        
168
                        //Aplicamos los filtros usados en el panel
169
                        addSelectedFilters(rasterFilterList, listFilterUsed);
170
                        
171
                        insertLineLog(RasterToolsUtil.getText(this, "aplicando_filtros"));
172

    
173
                        grid.setNoDataValue(rasterDataSource.getNoDataValue());
174
                        grid.applyFilters();
175
                        
176
                        insertLineLog(RasterToolsUtil.getText(this, "guardando_capa"));
177

    
178
                        buffer = grid.getRasterBuf();
179

    
180
                        writerBufferServer = rManager.createDataServerWriter();
181
                        writerBufferServer.setBuffer(buffer, -1);
182
                        // TODO: FUNCIONALIDAD: Poner los getWriter con la proyecci?n del fichero fuente
183

    
184
                        //Calculo de la interpretaci?n de color
185
                        ColorInterpretation colorInterpretation = null;
186
                        if(lyr.existColorTable() || buffer.getBandCount() > 1)
187
                                colorInterpretation = rManager.getDataStructFactory().createColorInterpretation(
188
                                                new String[] { ColorInterpretation.RED_BAND, ColorInterpretation.GREEN_BAND, ColorInterpretation.BLUE_BAND });
189
                        else if(buffer.getBandCount() == 2) {
190
                                renderBands = lyr.getRender().getRenderBands();
191
                                String[] ci = new String[renderBands.length];
192
                                for (int i = 0; i < renderBands.length; i++) {
193
                                        switch (renderBands[i]) {
194
                                        case 0:ci[i] = ColorInterpretation.RED_BAND; break;
195
                                        case 1:ci[i] = ColorInterpretation.GREEN_BAND; break;
196
                                        case 2:ci[i] = ColorInterpretation.BLUE_BAND; break;
197
                                        default: ci[i] = ColorInterpretation.UNDEF_BAND; 
198
                                        }
199
                                }
200
                                colorInterpretation = rManager.getDataStructFactory().createColorInterpretation(ci);
201
                        } else
202
                                colorInterpretation = rManager.getDataStructFactory().createColorInterpretation(
203
                                                new String[] { ColorInterpretation.GRAY_BAND });
204
                        
205
                        //Si la imagen original ten?a una banda de transparencia se asignar? esta. Si los filtros generados
206
                        //crean una banda se mezclar? con la original. 
207
                        int nbands = buffer.getBandCount();
208
                        if( rasterDataSource.getTransparency() != null &&
209
                                        rasterDataSource.getTransparency().getAlphaBandNumber() >= 0) {
210
                                query.setDrawableBands(new int[]{rasterDataSource.getTransparency().getAlphaBandNumber()});
211
                                query.setAreaOfInterest();
212
                                alpha = dstoreCopy.query(query);
213
                                if(grid.getFilterList().getAlphaBand() != null)
214
                                        alpha = rManager.getColorConversion().mergeTransparencyBuffers(alpha, grid.getFilterList().getAlphaBand());
215
                                writerBufferServer.setAlphaBuffer(alpha);
216
                                //Asignamos la interpretaci?n de color de la banda alpha                                
217
                                ColorInterpretation alphaI = rManager.getDataStructFactory().createColorInterpretation(
218
                                                new String[] { ColorInterpretation.ALPHA_BAND });
219
                                colorInterpretation.addColorInterpretation(alphaI);
220
                                nbands ++;
221
                        } else if(grid.getFilterList().getAlphaBand() != null) {
222
                                writerBufferServer.setAlphaBuffer(grid.getFilterList().getAlphaBand());
223
                                //Asignamos la interpretaci?n de color de la banda alpha
224
                                ColorInterpretation alphaI = rManager.getDataStructFactory().createColorInterpretation(
225
                                                new String[] { ColorInterpretation.ALPHA_BAND });
226
                                colorInterpretation.addColorInterpretation(alphaI);
227
                                nbands ++;
228
                        }
229
                        geoRasterWriter = rManager.createWriter(writerBufferServer, 
230
                                        filename,
231
                                        nbands, 
232
                                        rasterDataSource.getAffineTransform(), 
233
                                        buffer.getWidth(), 
234
                                        buffer.getHeight(), 
235
                                        buffer.getDataType(), 
236
                                        rManager.createWriter(filename).getParams(), 
237
                                        null);
238
                        
239
                        if (lyr.getRender() == null)
240
                                colorInterpretation = getColorIntepretation(buffer, grid);
241

    
242
                        geoRasterWriter.setColorBandsInterpretation(colorInterpretation.getValues());
243

    
244
                        geoRasterWriter.dataWrite();
245
                        geoRasterWriter.writeClose();
246
                        geoRasterWriter = null;
247
                        
248
                        // Guardamos en el RMF el valor NoData
249
                        //Si el del buffer tiene valor es porque alg?n filtro le ha salvado valor nodata por lo que se pone ese
250
                        //sino se pone el de la imagen original
251
                        NoData nodataOrigin = (NoData)rasterDataSource.getNoDataValue();
252
                        NoData nodataBuffer =  (NoData)buffer.getNoDataValue();
253
                        if(nodataBuffer != null && nodataBuffer.isDefined()) {
254
                                nodataBuffer.setFileName(filename);
255
                                nodataBuffer.save();
256
                        } else if(nodataOrigin != null && nodataOrigin.isDefined()) {
257
                                nodataOrigin.setFileName(filename);
258
                                nodataOrigin.save();
259
                        }
260
                        
261
                        SwingUtilities.invokeLater(new Runnable() {
262
                                public void run() {
263
                                        if (externalActions != null)
264
                                                externalActions.end(filename);
265
                                }
266
                        });
267
                } catch (NotSupportedExtensionException e) {
268
                        throw new ProcessException("error_writer_notsupportedextension", e);
269
                } catch (RasterDriverException e) {
270
                        throw new ProcessException("error_writer", e);
271
                } catch (IOException e) {
272
                        throw new ProcessException("error_writer", e);
273
                } catch (FilterTypeException e) {
274
                        throw new ProcessException("error_adding_filters", e);
275
                } catch (InvalidSetViewException e) {
276
                        throw new ProcessException("error_loading_data", e);
277
                } catch (FilterManagerException e) {
278
                        throw new ProcessException("error_adding_filters", e);
279
                } finally {
280
                        if(writerBufferServer != null)
281
                                writerBufferServer.dispose();
282
                        if(buff != null)
283
                                buff.dispose();
284
                        if(rasterFilterList != null)
285
                                rasterFilterList.dispose();
286
                        if (grid != null)
287
                                grid.dispose();
288
                        if(alpha != null)
289
                                alpha.dispose();
290
                        if(dstoreCopy != null)
291
                                try {
292
                                        dstoreCopy.close();
293
                                } catch (CloseException e) {
294
                                }
295
                        if(lyr != null)
296
                                lyr.setReadingData(null);
297
                        dispose();
298
                }
299
        }
300

    
301
        /**
302
         * Sustituye la lista de filtros de filterList por la que le pasamos en forma
303
         * de ArrayList
304
         * @param filterList
305
         * @param listFilterUsed
306
         * @throws FilterTypeException 
307
         * @throws FilterTypeException 
308
         */
309
        public void addSelectedFilters(RasterFilterList filterList, ArrayList<ParamStruct> listFilterUsed) throws FilterManagerException, FilterTypeException {
310
                filterList.clear();
311
                
312
                for (int i = 0; i < listFilterUsed.size(); i++) {
313
                        ParamStruct aux = (ParamStruct) listFilterUsed.get(i);
314
                        RasterFilterListManager filterManager = filterList.getManagerByFilterClass(aux.getFilterClass());
315
                        filterManager.addFilter(aux.getFilterClass(), aux.getFilterParam());
316
                }
317

    
318
                filterList.resetPercent();
319
        }
320

    
321
        /*
322
         * (non-Javadoc)
323
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
324
         */
325
        public int getPercent() {
326
                if (rasterFilterList == null)
327
                        return 0;
328

    
329
                if (rasterFilterList.getPercent() < 100)
330
                        return rasterFilterList.getPercent();
331

    
332
                if (geoRasterWriter == null)
333
                        return 0;
334

    
335
                return geoRasterWriter.getPercent();
336
        }
337

    
338
        /*
339
         * (non-Javadoc)
340
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
341
         */
342
        public String getTitle() {
343
                return PluginServices.getText(this, "aplicando_filtros");
344
        }
345
        
346
        /*
347
         * (non-Javadoc)
348
         * @see org.gvsig.raster.tools.app.basic.raster.process.RasterProcess#dispose()
349
         */
350
        public void dispose() {
351
                rasterDataSource = null;
352
                if(listFilterUsed != null) {
353
                        listFilterUsed.clear();
354
                        listFilterUsed = null;
355
                }
356
                rasterFilterList = null;
357
                geoRasterWriter  = null;
358
                lyr              = null;
359
        }
360
        
361
        /*
362
         * (non-Javadoc)
363
         * @see java.lang.Object#finalize()
364
         */
365
        @Override
366
        protected void finalize() throws Throwable {
367
                dispose();
368
                super.finalize();
369
        }
370
}