Statistics
| Revision:

root / trunk / extensions / extRasterTools-SE / src / org / gvsig / rastertools / properties / control / BandSelectorListener.java @ 22475

History | View | Annotate | Download (12.8 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.rastertools.properties.control;
20

    
21
import java.awt.event.ActionEvent;
22
import java.awt.event.ActionListener;
23
import java.awt.geom.Rectangle2D;
24
import java.io.File;
25

    
26
import javax.swing.JFileChooser;
27
import javax.swing.JOptionPane;
28

    
29
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
30
import org.gvsig.gui.beans.table.exceptions.NotInitializeException;
31
import org.gvsig.raster.dataset.IRasterDataSource;
32
import org.gvsig.raster.dataset.NotSupportedExtensionException;
33
import org.gvsig.raster.dataset.RasterDataset;
34
import org.gvsig.raster.dataset.io.RasterDriverException;
35
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
36
import org.gvsig.raster.dataset.serializer.RmfSerializerException;
37
import org.gvsig.raster.datastruct.Extent;
38
import org.gvsig.raster.datastruct.Transparency;
39
import org.gvsig.raster.grid.GridTransparency;
40
import org.gvsig.raster.gui.wizards.DriverFileFilter;
41
import org.gvsig.raster.hierarchy.IRasterDataset;
42
import org.gvsig.raster.hierarchy.IRasterProperties;
43
import org.gvsig.raster.hierarchy.IRasterRendering;
44
import org.gvsig.raster.util.RasterToolsUtil;
45
import org.gvsig.rastertools.RasterModule;
46
import org.gvsig.rastertools.properties.panels.BandSelectorPanel;
47

    
48
import com.iver.andami.PluginServices;
49
import com.iver.andami.messages.NotificationManager;
50
import com.iver.cit.gvsig.addlayer.fileopen.FileOpenWizard;
51
import com.iver.cit.gvsig.fmap.layers.FLayer;
52
/**
53
 * Clase que maneja los eventos del panel BandSetupPanel. Gestiona el a?adir o
54
 * eliminar ficheros de la lista y contiene las acciones a realizar cuando en
55
 * panel registrable se pulsa aceptar, aplicar o cancelar.
56
 *
57
 * @author Nacho Brodin (brodin_ign@gva.es)
58
 */
59
public class BandSelectorListener implements ActionListener {
60
        private BandSelectorPanel     bandSetupPanel = null;
61
        private JFileChooser          fileChooser    = null;
62
        private FLayer                fLayer         = null;
63
        private IRasterDataset        dataset        = null;
64
        private IRasterProperties     prop           = null;
65
        private IRasterRendering      render         = null;
66
        private boolean               enabled        = true;
67

    
68
        /**
69
         * N?mero de bandas.
70
         */
71
        protected int                 nbands         = 0;
72

    
73
        /**
74
         * Lista de geoRasterDataset correspondiente a los ficheros de bandas
75
         */
76
        protected RasterDataset[]     grd            = null;
77

    
78
        /**
79
         * Constructor
80
         * @param bs Panel del selector de bandas
81
         * @param lyr Capa raster
82
         */
83
        public BandSelectorListener(BandSelectorPanel bs) {
84
                this.bandSetupPanel = bs;
85
                bs.getFileList().getJButtonAdd().addActionListener(this);
86
                bs.getFileList().getJButtonRemove().addActionListener(this);
87
                bs.getNumBandSelectorCombo().addActionListener(this);
88
        }
89

    
90
        /**
91
         * Comprobar si la asignacion de color es correcta para las 4 bandas. No puede
92
         * existir una banda con distintas interpretaciones de color. Se comprueban dos
93
         * casos, asignaciones en escala de grises o en RGB.
94
         * @param r
95
         * @param g
96
         * @param b
97
         * @param a
98
         * @return
99
         */
100
        private boolean isCorrectAssignedBand(int r, int g, int b, int a) {
101
                // Si es gris es correcta la asignacion 
102
                if ((r == g) && (r == b) && (r >= 0)) {
103
                        // Si el alpha esta asignado a la misma banda es incorrecto
104
                        if (r == a)
105
                                return false;
106
                        // En caso contrario es correcto
107
                        return true;
108
                }
109

    
110
                // Si dos bandas coinciden, se dice que no es correcta la asignacion
111
                int list[] = { r, g, b, a };
112
                for (int i = 0; i <= 3; i++)
113
                        for (int j = 0; j <= 3; j++)
114
                                if ((i != j) && (list[i] == list[j]) && (list[i] > -1))
115
                                        return false;
116

    
117
                return true;
118
        }
119
        
120
        /**
121
         * Constructor
122
         * @param bs Panel del selector de bandas
123
         * @param lyr Capa raster
124
         */
125
        public void init(IRasterDataset dset, IRasterProperties prop, FLayer lyr) {
126
                //TODO: FUNCIONALIDAD: Cancelaci?n para la selecci?n de bandas
127
                this.dataset = dset;
128
                this.prop = prop;
129
                fLayer = lyr;
130
                if(fLayer instanceof IRasterRendering)
131
                        render = (IRasterRendering)fLayer;
132
        }
133

    
134
        /**
135
         * Listener para la gesti?n de los botones de a?adir, eliminar fichero y
136
         * el combo de selecci?n de bandas.
137
         */
138
        public void actionPerformed(ActionEvent e) {
139

    
140
                if (e.getSource().equals(bandSetupPanel.getFileList().getJButtonAdd()))
141
                        addFileBand();
142

    
143
                if (e.getSource().equals(bandSetupPanel.getFileList().getJButtonRemove()))
144
                        delFileBand();
145
                
146
                if (e.getSource().equals(bandSetupPanel.getNumBandSelectorCombo())) {
147
                        String vBands = (String) bandSetupPanel.getNumBandSelectorCombo().getSelectedItem();
148
                        if (vBands != null) {
149
                                if (vBands.compareTo("3") == 0)
150
                                        bandSetupPanel.resetMode(3);
151

    
152
                                if (vBands.compareTo("2") == 0)
153
                                        bandSetupPanel.resetMode(2);
154

    
155
                                if (vBands.compareTo("1") == 0)
156
                                        bandSetupPanel.resetMode(1);
157
                        }
158
                }
159
                                
160
                if (e.getSource().equals(bandSetupPanel.getSaveButton())) {
161
                        int rBand = bandSetupPanel.getAssignedBand(RasterDataset.RED_BAND);
162
                        int gBand = bandSetupPanel.getAssignedBand(RasterDataset.GREEN_BAND);
163
                        int bBand = bandSetupPanel.getAssignedBand(RasterDataset.BLUE_BAND);
164
                        int aBand = bandSetupPanel.getAssignedBand(RasterDataset.ALPHA_BAND);
165
                        
166
                        if (!isCorrectAssignedBand(rBand, gBand, bBand, aBand)) {
167
                                RasterToolsUtil.messageBoxError("combinacion_no_asignable", bandSetupPanel);
168
                                return;
169
                        }
170
                        
171
                        RasterToolsUtil.messageBoxYesOrNot("color_interpretation_continue", this);
172
                        IRasterDataSource dataSource = ((FLyrRasterSE)fLayer).getDataSource();
173
                        if(dataSource == null) {
174
                                RasterToolsUtil.messageBoxError("error_carga_capa", bandSetupPanel);
175
                                return;
176
                        }
177
                        
178
                        DatasetColorInterpretation ci = dataSource.getColorInterpretation();
179
                        try {
180
                                // Combinaci?n GRAY
181
                                if ((rBand == gBand) && (rBand == bBand) && (rBand >= 0)) {
182
                                        for (int iBand = 0; iBand < bandSetupPanel.getARGBTable().getRowCount(); iBand++) {
183
                                                ci.setColorInterpValue(iBand, DatasetColorInterpretation.UNDEF_BAND);
184
                                        }
185
                                        ci.setColorInterpValue(rBand, DatasetColorInterpretation.GRAY_BAND);
186
                                        ci.setColorInterpValue(aBand, DatasetColorInterpretation.ALPHA_BAND);
187
                                } else {
188
                                        // Combinaci?n RGB
189
                                        for (int iBand = 0; iBand < bandSetupPanel.getARGBTable().getRowCount(); iBand++)
190
                                                ci.setColorInterpValue(iBand, bandSetupPanel.getColorInterpretationByBand(iBand));
191
                                }
192
                                ((FLyrRasterSE) fLayer).getDataSource().getDataset(0)[0].saveObjectToRmf(DatasetColorInterpretation.class, ci);
193
                        } catch (RmfSerializerException exc) {
194
                                RasterToolsUtil.messageBoxError("error_salvando_rmf", bandSetupPanel, exc);
195
                        } catch (NotInitializeException exc) {
196
                                RasterToolsUtil.messageBoxError("table_not_initialize", bandSetupPanel, exc);
197
                        }
198
                }
199
                
200
                if (!RasterModule.autoRefreshView)
201
                        return;
202

    
203
                bandSetupPanel.onlyApply();
204
        }
205

    
206
        /**
207
         * A?ade una banda al raster
208
         * @param e
209
         */
210
        private void addFileBand() {
211
                // String[] driverNames = null;
212

    
213
                // Creaci?n del dialogo para selecci?n de ficheros
214

    
215
                fileChooser = new JFileChooser(FileOpenWizard.getLastPath());
216
                fileChooser.setMultiSelectionEnabled(true);
217
                fileChooser.setAcceptAllFileFilterUsed(false);
218

    
219
                fileChooser.addChoosableFileFilter(new DriverFileFilter());
220

    
221
                int result = fileChooser.showOpenDialog(bandSetupPanel);
222

    
223
                if (result == JFileChooser.APPROVE_OPTION) {
224
                        IRasterDataSource ds = dataset.getDataSource();
225
                        File[] files = fileChooser.getSelectedFiles();
226

    
227
                        FileOpenWizard.setLastPath(files[0].getPath());
228

    
229
                        // Lo a?adimos a la capa si no esta
230

    
231
                        for (int i = 0; i < files.length; i++) {
232

    
233
                                // Comprobamos que el fichero no est?
234
                                boolean exist = false;
235
                                for (int j = 0; j < ds.getDatasetCount(); j++) {
236
                                        if (dataset.getDataSource().getDataset(j)[0].getFName().endsWith(files[i].getName()))
237
                                                exist = true;
238
                                }
239
                                if (!exist) {
240
                                        try {
241
                                                Rectangle2D extentOrigin = prop.getFullRasterExtent().toRectangle2D();
242

    
243
                                                RasterDataset geoRasterDataset = RasterDataset.open(prop.getProjection(), files[i].getAbsolutePath());
244
                                                Extent extentNewFile = geoRasterDataset.getExtent();
245
                                                nbands += geoRasterDataset.getBandCount();
246

    
247
                                                // Comprobamos que el extent y tama?o del fichero a?adido sea igual al
248
                                                // fichero original. Si no es as? no abrimos la capa y mostramos un aviso
249

    
250
                                                double widthNewFile = (extentNewFile.getMax().getX() - extentNewFile.getMin().getX());
251
                                                double heightNewFile = (extentNewFile.getMax().getY() - extentNewFile.getMin().getY());
252

    
253
                                                if ((widthNewFile - extentOrigin.getWidth()) > 1.0 || (widthNewFile - extentOrigin.getWidth()) < -1.0 || (heightNewFile - extentOrigin.getHeight()) > 1.0
254
                                                                || (heightNewFile - extentOrigin.getHeight()) < -1.0) {
255
                                                        JOptionPane.showMessageDialog(null, PluginServices.getText(this, "extents_no_coincidentes"), "", JOptionPane.ERROR_MESSAGE);
256
                                                        continue;
257
                                                }
258

    
259
                                                if ((extentNewFile.getMax().getX() - extentNewFile.getMin().getX()) != extentOrigin.getWidth()
260
                                                                || (extentNewFile.getMax().getY() - extentNewFile.getMin().getY()) != extentOrigin.getHeight()) {
261
                                                        JOptionPane.showMessageDialog(null, PluginServices.getText(this, "extents_no_coincidentes"), "", JOptionPane.ERROR_MESSAGE);
262
                                                        continue;
263
                                                }
264

    
265
                                                geoRasterDataset.close();
266

    
267
                                        } catch (Exception exc) {
268
                                                RasterToolsUtil.messageBoxError("addband_error", bandSetupPanel, exc);
269
                                        }
270

    
271
                                        // Lo a?adimos a la capa
272
                                        try {
273
                                                dataset.addFile(files[i].getAbsolutePath());
274
                                        } catch (NotSupportedExtensionException e) {
275
                                                RasterToolsUtil.messageBoxError("addband_error", bandSetupPanel, e);
276
                                        } catch (RasterDriverException e) {
277
                                                RasterToolsUtil.messageBoxError("addband_error", bandSetupPanel, e);
278
                                        }
279
                                } else {
280
                                        RasterToolsUtil.messageBoxError("fichero_existe" + " " + files[i].getAbsolutePath(), bandSetupPanel);
281
                                        return;
282
                                }
283
                        }
284

    
285
                        // A?adimos los georasterfile a la tabla del Panel
286
                        try {
287
                                bandSetupPanel.addFiles(ds);
288
                        } catch (NotInitializeException e) {
289
                                RasterToolsUtil.messageBoxError("table_not_initialize", this, e);
290
                        }
291
                }
292
        }
293

    
294
        /**
295
         * Elimina una banda del raster. Si queda solo un fichero o no se ha
296
         * seleccionado ninguna banda no hace nada.
297
         *
298
         * @param e
299
         */
300
        private void delFileBand() {
301
                Object[] objects = bandSetupPanel.getFileList().getJList().getSelectedValues();
302

    
303
                for (int i = objects.length - 1; i >=0; i--) {
304
                        if (bandSetupPanel.getFileList().getNFiles() > 1) {
305
                                String pathName = objects[i].toString();
306
                                RasterDataset geoRasterFile = null;
307
                                try {
308
                                        geoRasterFile = RasterDataset.open(prop.getProjection(), pathName);
309
                                } catch (NotSupportedExtensionException e) {
310
                                        NotificationManager.addError(e.getMessage(), e);
311
                                } catch (RasterDriverException e1) {
312
                                        NotificationManager.addError(e1.getMessage(), e1);
313
                                }
314
                                nbands -= geoRasterFile.getBandCount();
315
                                dataset.delFile(pathName);
316
                                String file = pathName.substring(pathName.lastIndexOf("/") + 1);
317
                                file = file.substring(file.lastIndexOf("\\") + 1);
318
                                bandSetupPanel.removeFile(file);
319
                        }
320
                }
321
        }
322

    
323
        /**
324
         * Acciones a ejecutar cuando se aplica
325
         */
326
        public void apply() {
327
                if (enabled)
328
                        setNewBandsPositionInRendering();
329
        }
330

    
331
        /**
332
         * Asigna la posici?n de las bandas en el rederizado basandose en la selecci?n
333
         * hecho en la tabla de bandas.
334
         */
335
        public void setNewBandsPositionInRendering() {
336
                if (prop != null && prop.getRender() != null) {
337
                        if(render != null) {
338
                                render.getRenderBands()[0] = bandSetupPanel.getAssignedBand(RasterDataset.RED_BAND);
339
                                render.getRenderBands()[1] = bandSetupPanel.getAssignedBand(RasterDataset.GREEN_BAND);
340
                                render.getRenderBands()[2] = bandSetupPanel.getAssignedBand(RasterDataset.BLUE_BAND);
341
                                int alphaBand = bandSetupPanel.getAssignedBand(RasterDataset.ALPHA_BAND);
342
                                // Ultima transparencia aplicada en el renderizador
343
                                GridTransparency gt = render.getRenderTransparency();
344
                                if(gt != null) 
345
                                        gt.setTransparencyBand(alphaBand);
346

    
347
                                // Transparencia del dataset
348
                                Transparency t = ((FLyrRasterSE) fLayer).getDataSource().getTransparencyFilesStatus();
349
                                if(t != null)
350
                                        t.setTransparencyBand(alphaBand);
351
                        }
352
                        fLayer.getMapContext().invalidate();
353
                }
354
        }
355

    
356
        /**
357
         * Activa o desactiva la acci?n del panel
358
         * @param enabled true para activa y false para desactivar.
359
         */
360
        public void setEnabledPanelAction(boolean enabled) {
361
                this.enabled = enabled;
362
        }
363
}