Statistics
| Revision:

gvsig-raster / org.gvsig.raster.tools / trunk / org.gvsig.raster.tools / org.gvsig.raster.tools.app / org.gvsig.raster.tools.app.multifile / src / main / java / org / gvsig / raster / tools / app / multifile / panel / BandSelectorListener.java @ 859

History | View | Annotate | Download (17 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.multifile.panel;
23

    
24
import java.awt.event.ActionEvent;
25
import java.awt.event.ActionListener;
26
import java.awt.geom.Point2D;
27
import java.awt.geom.Rectangle2D;
28
import java.io.File;
29
import java.io.IOException;
30
import java.util.ArrayList;
31

    
32
import javax.swing.JOptionPane;
33

    
34
import org.gvsig.andami.PluginServices;
35
import org.gvsig.andami.ui.mdiManager.WindowInfo;
36
import org.gvsig.fmap.dal.DALLocator;
37
import org.gvsig.fmap.dal.DataServerExplorer;
38
import org.gvsig.fmap.dal.DataServerExplorerParameters;
39
import org.gvsig.fmap.dal.coverage.RasterLocator;
40
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
41
import org.gvsig.fmap.dal.coverage.exception.InvalidSourceException;
42
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
43
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
44
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
45
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
46
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
47
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
48
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
49
import org.gvsig.fmap.dal.coverage.util.ProviderServices;
50
import org.gvsig.fmap.dal.exception.CloseException;
51
import org.gvsig.fmap.dal.raster.spi.CoverageStoreProvider;
52
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
53
import org.gvsig.fmap.dal.spi.DataStoreProvider;
54
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
55
import org.gvsig.gui.beans.buttonspanel.ButtonsPanelEvent;
56
import org.gvsig.gui.beans.buttonspanel.ButtonsPanelListener;
57
import org.gvsig.gui.beans.swing.JFileChooser;
58
import org.gvsig.gui.beans.table.exceptions.NotInitializeException;
59
import org.gvsig.raster.fmap.layers.DefaultFLyrRaster;
60
import org.gvsig.raster.fmap.layers.FLyrRaster;
61
import org.gvsig.raster.tools.app.basic.RasterExtension;
62
import org.gvsig.raster.tools.app.basic.RasterToolsUtil;
63
import org.gvsig.raster.tools.app.basic.raster.gui.wizard.DriverFileFilter;
64
import org.gvsig.raster.tools.multifile.io.MultiFileDataParameters;
65
import org.gvsig.raster.tools.multifile.io.MultiFileFormat;
66
import org.gvsig.raster.tools.multifile.io.MultiFileProvider;
67
import org.gvsig.tools.locator.LocatorException;
68

    
69
/**
70
 * Clase que maneja los eventos del panel BandSetupPanel. Gestiona el a?adir o
71
 * eliminar ficheros de la lista y contiene las acciones a realizar cuando en
72
 * panel registrable se pulsa aceptar, aplicar o cancelar.
73
 *
74
 * @author Nacho Brodin (brodin_ign@gva.es)
75
 */
76
public class BandSelectorListener implements ActionListener, ButtonsPanelListener {
77
        private BandSelectorPanel     bandSetupPanel = null;
78
        private JFileChooser          fileChooser    = null;
79
        private FLyrRaster            fLayer         = null;
80
        private boolean               enabled        = true;
81
        private ArrayList<File>       fileList       = null;
82

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

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

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

    
122
                return true;
123
        }
124

    
125
        /**
126
         * Constructor
127
         * @param bs Panel del selector de bandas
128
         * @param lyr Capa raster
129
         */
130
        public void init(FLyrRaster lyr) {
131
                fLayer = lyr;
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(RasterDataStore.RED_BAND);
162
                        int gBand = bandSetupPanel.getAssignedBand(RasterDataStore.GREEN_BAND);
163
                        int bBand = bandSetupPanel.getAssignedBand(RasterDataStore.BLUE_BAND);
164
                        int aBand = bandSetupPanel.getAssignedBand(RasterDataStore.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
                        RasterDataStore dataSource = fLayer.getDataStore();
173
                        if(dataSource == null) {
174
                                RasterToolsUtil.messageBoxError("error_carga_capa", bandSetupPanel);
175
                                return;
176
                        }
177

    
178
                        ColorInterpretation 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, ColorInterpretation.UNDEF_BAND);
184
                                        }
185
                                        ci.setColorInterpValue(rBand, ColorInterpretation.GRAY_BAND);
186
                                        ci.setColorInterpValue(aBand, ColorInterpretation.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
                                String fileName = fLayer.getDataStore().getName();
193
                                RasterLocator.getManager().getProviderServices().saveObjectToRmfFile(fileName, ci);
194
                        } catch (RmfSerializerException exc) {
195
                                RasterToolsUtil.messageBoxError("error_salvando_rmf", bandSetupPanel, exc);
196
                        } catch (NotInitializeException exc) {
197
                                RasterToolsUtil.messageBoxError("table_not_initialize", bandSetupPanel, exc);
198
                        }
199
                }
200

    
201
                if (!RasterExtension.autoRefreshView)
202
                        return;
203

    
204
                bandSetupPanel.onlyApply();
205
        }
206

    
207
        /**
208
         * Checks if the new file is compatible with the old one
209
         * @param file
210
         * @return
211
         * @throws LocatorException
212
         * @throws NotSupportedExtensionException
213
         * @throws RasterDriverException
214
         * @throws CloseException
215
         */
216
        private boolean checkNewFile(String file) throws LocatorException, NotSupportedExtensionException, RasterDriverException, CloseException {
217
                Rectangle2D extentOrigin = fLayer.getFullRasterExtent().toRectangle2D();
218
                
219
                ProviderServices provServ = RasterLocator.getManager().getProviderServices();
220
                RasterDataParameters storeParameters = provServ.createParameters(file);
221
                storeParameters.setSRS(fLayer.getDataStore().getProjection());
222
                RasterDataStore dataStore = RasterLocator.getManager().open(storeParameters);
223
                
224
                Extent extentNewFile = dataStore.getExtent();
225

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

    
229
                double widthNewFile = (extentNewFile.getMax().getX() - extentNewFile.getMin().getX());
230
                double heightNewFile = (extentNewFile.getMax().getY() - extentNewFile.getMin().getY());
231

    
232
                if ((widthNewFile - extentOrigin.getWidth()) > 1.0 || (widthNewFile - extentOrigin.getWidth()) < -1.0 || (heightNewFile - extentOrigin.getHeight()) > 1.0
233
                                || (heightNewFile - extentOrigin.getHeight()) < -1.0) {
234
                        return false;
235
                }
236

    
237
                if ((extentNewFile.getMax().getX() - extentNewFile.getMin().getX()) != extentOrigin.getWidth()
238
                                || (extentNewFile.getMax().getY() - extentNewFile.getMin().getY()) != extentOrigin.getHeight()) {
239
                        return false;
240
                }
241

    
242
                dataStore.close();
243
                return true;
244
        }
245
        
246
        /**
247
         * A?ade una banda al raster
248
         * @param e
249
         */
250
        private void addFileBand() {
251
                // String[] driverNames = null;
252

    
253
                // Creaci?n del dialogo para selecci?n de ficheros
254

    
255
                fileChooser = new JFileChooser("BAND_SELECTOR_LISTENER",JFileChooser.getLastPath("BAND_SELECTOR_LISTENER",null));//,FileOpenWizard.getLastPath());
256
                fileChooser.setMultiSelectionEnabled(true);
257
                fileChooser.setAcceptAllFileFilterUsed(false);
258

    
259
                fileChooser.addChoosableFileFilter(new DriverFileFilter());
260

    
261
                int result = fileChooser.showOpenDialog(bandSetupPanel);
262

    
263
                if (result == JFileChooser.APPROVE_OPTION) {
264
                        RasterDataStore dataStore = fLayer.getDataStore();
265
                        File[] files = fileChooser.getSelectedFiles();
266

    
267
                        JFileChooser.setLastPath("BAND_SELECTOR_LISTENER",files[0]);
268
                        
269
                        fileList = new ArrayList<File>();
270
                        
271
                        for (int i = 0; i < files.length; i++) {
272
                                //Checks that the file does not exist
273
                                String[] uris = dataStore.getURIByProvider();
274
                                boolean exists = false;
275
                                for (int j = 0; j < uris.length; j++) {
276
                                        if (uris[j].endsWith(files[i].getName())) {
277
                                                RasterToolsUtil.messageBoxError( PluginServices.getText( this, "fichero_existe") + ": " + files[i].getAbsolutePath(), bandSetupPanel);
278
                                                exists = true;
279
                                                break;
280
                                        }
281
                                }
282
                                if(!exists)
283
                                        fileList.add(files[i]);
284
                        }
285
                        
286
                        for (int i = fileList.size() - 1; i >= 0; i--) {
287
                                //Checks extents
288
                                try {
289
                                        if(!checkNewFile(fileList.get(i).getAbsolutePath())) {
290
                                                JOptionPane.showMessageDialog(null, PluginServices.getText(this, "extents_no_coincidentes") +  " " + files[i].getAbsolutePath(), "", JOptionPane.ERROR_MESSAGE);
291
                                                fileList.remove(i);
292
                                        }
293
                                } catch (Exception e) {
294
                                        e.printStackTrace();
295
                                }
296
                        }
297

    
298
                        if(dataStore.isMultiFile()) {
299
                                for (int i = 0; i < fileList.size(); i++) {
300
                                        try {
301
                                                dataStore.addFile(fileList.get(i).getAbsolutePath());
302
                                        } catch (InvalidSourceException e) {
303
                                                RasterToolsUtil.messageBoxError("addband_error", bandSetupPanel, e);
304
                                        }
305
                                }
306
                                
307
                                dataStore.setProvider(dataStore.getProvider());
308
                                
309
                                //It shows the files and bands in the panel
310
                                try {
311
                                        bandSetupPanel.addFiles(dataStore);
312
                                } catch (NotInitializeException e) {
313
                                        RasterToolsUtil.messageBoxError("table_not_initialize", this, e);
314
                                }
315
                        } else {
316
                                //New layer name
317
                                WindowInfo wi = PluginServices.getMDIManager().getActiveWindow().getWindowInfo();
318
                                LayerNameDialog dialog = new LayerNameDialog(new Point2D.Double(wi.getX(), wi.getY()), 300, 80, this);
319
                                RasterToolsUtil.addWindow(dialog);
320
                        }
321
                }
322
        }
323
        
324
        /**
325
         * Catchs the events from LayerNameDialog to get the name of the new layer
326
         */
327
        public void actionButtonPressed(ButtonsPanelEvent e) {
328
                String layerName = (String)e.getSource();
329
        
330
                RasterDataStore dataStore = fLayer.getDataStore();
331
                RasterDataParameters paramFirstFile = (RasterDataParameters)dataStore.getParameters();//(RasterDataParameters)((RasterProvider)dataStore.getProvider()).getDataParameters();
332
                
333
                ProviderServices provServ = RasterLocator.getManager().getProviderServices();
334
                DataManagerProviderServices dataManager = (DataManagerProviderServices)DALLocator.getDataManager();
335

    
336
                try {
337
                        //It creates the new Multifile provider
338
                        DataServerExplorerParameters explParams = dataManager.createServerExplorerParameters(MultiFileProvider.NAME);
339
                        DataServerExplorer explorer = dataManager.openServerExplorer(MultiFileProvider.NAME, explParams);
340
                        MultiFileDataParameters newParamsMultifile = (MultiFileDataParameters)dataManager.createStoreParameters(explorer.getProviderName());
341
                        String path = paramFirstFile.getURI().substring(0, paramFirstFile.getURI().lastIndexOf(File.separator) + 1);
342
                        path = path + layerName + ".mff";
343
                        newParamsMultifile.setURI(path);
344
                        newParamsMultifile.addProvider(dataStore);
345
                        DataStoreProvider provMultifile = dataManager.createProvider((DataStoreProviderServices)dataStore, newParamsMultifile);
346

    
347
                        //And now it creates and adds the new ones
348
                        for (int i = 0; i < fileList.size(); i++) {
349
                                ArrayList<RasterDataParameters> storeParametersList = provServ.createParametersList(fileList.get(i).getAbsolutePath());
350
                                for (int j = 0; j < storeParametersList.size(); j++) {
351
                                        DataStoreProvider newFileProv = dataManager.createProvider((DataStoreProviderServices)dataStore, storeParametersList.get(j));
352
                                        newParamsMultifile.addProviderNotTiled(newFileProv);
353
                                }
354
                        }
355

    
356
                        ((DefaultFLyrRaster)fLayer).setName(layerName);
357
                        //Assigns the MultifileProvider to the store
358
                        dataStore.setProvider((CoverageStoreProvider)provMultifile);
359

    
360
                        //It shows the files and bands in the panel
361
                        try {
362
                                bandSetupPanel.addFiles(dataStore);
363
                        } catch (NotInitializeException ex) {
364
                                RasterToolsUtil.messageBoxError("table_not_initialize", this, ex);
365
                        }
366
                        
367
                        ArrayList<File> uriList = new ArrayList<File>();
368
                        uriList.add(new File(paramFirstFile.getURI()));
369
                        for (int i = 0; i < fileList.size(); i++) {
370
                                uriList.add(fileList.get(i));
371
                        }
372
                        saveMultiFileLayer(layerName, paramFirstFile.getURI(), uriList);
373

    
374
                } catch (Exception exc) {
375
                        RasterToolsUtil.messageBoxError("addband_error", bandSetupPanel, exc);
376
                }
377
        }
378
        
379
        /**
380
         * Saves the new layer in disk
381
         * @param layerName
382
         * @param file
383
         * @param uriList
384
         * @throws IOException
385
         */
386
        private String saveMultiFileLayer(String layerName, String file, ArrayList<File> uriList) throws IOException {
387
                String path = file.substring(0, file.lastIndexOf(File.separator) + 1);
388
                path = path + layerName + ".mff";
389
                
390
                /*File filePath = new File(path);
391
                if(filePath.exists()) {
392
                        RasterToolsUtil.messageBoxInfo("file_exists_rename", bandSetupPanel);
393
                        filePath.renameTo(new File(path + "~"));
394
                }*/
395
                
396
                MultiFileFormat format = new MultiFileFormat();
397
                for (int i = 0; i < uriList.size(); i++) {
398
                        format.addFile(uriList.get(i));
399
                }
400
                format.setName(layerName);
401
                
402
                format.write(path);
403
                return path;
404
        }
405

    
406
        /**
407
         * Elimina una banda del raster. Si queda solo un fichero o no se ha
408
         * seleccionado ninguna banda no hace nada.
409
         *
410
         * @param e
411
         */
412
        private void delFileBand() {
413
                Object[] objects = bandSetupPanel.getFileList().getJList().getSelectedValues();
414
                RasterDataStore dataStore = fLayer.getDataStore();
415
                
416
                for (int i = objects.length - 1; i >= 0; i--) {
417
                        if (bandSetupPanel.getFileList().getNFiles() > 1) {
418
                                String pathName = objects[i].toString();
419
                                dataStore.removeFile(pathName);
420

    
421
                                String file = pathName.substring(pathName.lastIndexOf(File.separator) + 1);
422
                                file = file.substring(file.lastIndexOf("\\") + 1);
423
                                bandSetupPanel.removeFile(file);
424
                        }
425
                }
426
                
427
                setNewBandsPositionInRendering();
428
        }
429

    
430
        /**
431
         * Acciones a ejecutar cuando se aplica
432
         */
433
        public void apply() {
434
                if (enabled)
435
                        setNewBandsPositionInRendering();
436
        }
437

    
438
        /**
439
         * Asigna la posici?n de las bandas en el rederizado basandose en la selecci?n
440
         * hecho en la tabla de bandas.
441
         */
442
        public void setNewBandsPositionInRendering() {
443
                if (fLayer != null && fLayer.getRender() != null) {
444
                        fLayer.getRender().setRenderBands(new int[]{bandSetupPanel.getAssignedBand(RasterDataStore.RED_BAND),
445
                                        bandSetupPanel.getAssignedBand(RasterDataStore.GREEN_BAND),
446
                                        bandSetupPanel.getAssignedBand(RasterDataStore.BLUE_BAND)});
447
                        int alphaBand = bandSetupPanel.getAssignedBand(RasterDataStore.ALPHA_BAND);
448
                        // Ultima transparencia aplicada en el renderizador
449
                        Transparency gt = fLayer.getRender().getLastTransparency();
450
                        if(gt != null)
451
                                gt.setTransparencyBand(alphaBand);
452

    
453
                        // Transparencia del dataset
454
                        /*if(fLayer.getDataStore() != null) {
455
                                Transparency t = fLayer.getDataStore().getTransparency();
456
                                if(t != null)
457
                                        t.setTransparencyBand(alphaBand);
458
                        }*/
459
                        fLayer.getMapContext().invalidate();
460
                }
461
        }
462

    
463
        /**
464
         * Activa o desactiva la acci?n del panel
465
         * @param enabled true para activa y false para desactivar.
466
         */
467
        public void setEnabledPanelAction(boolean enabled) {
468
                this.enabled = enabled;
469
        }
470

    
471
}