Statistics
| Revision:

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

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
import java.io.IOException;
26

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

    
30
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
31
import org.gvsig.gui.beans.table.exceptions.NotInitializeException;
32
import org.gvsig.raster.dataset.IRasterDataSource;
33
import org.gvsig.raster.dataset.NotSupportedExtensionException;
34
import org.gvsig.raster.dataset.RasterDataset;
35
import org.gvsig.raster.dataset.io.RasterDriverException;
36
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
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.raster.util.RasterUtilities;
46
import org.gvsig.rastertools.RasterModule;
47
import org.gvsig.rastertools.properties.panels.BandSelectorPanel;
48

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

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

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

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

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

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

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

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

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

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

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

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

    
204
                bandSetupPanel.onlyApply();
205
        }
206

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
266
                                                geoRasterDataset.close();
267

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

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

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

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

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

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

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

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

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