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 @ 1817

History | View | Annotate | Download (18 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
import java.util.List;
32

    
33
import javax.swing.JOptionPane;
34

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

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

    
89
        /**
90
         * Constructor
91
         * @param bs Panel del selector de bandas
92
         * @param lyr Capa raster
93
         */
94
        public BandSelectorListener(BandSelectorPanel bs) {
95
                this.bandSetupPanel = bs;
96
                bs.getFileList().getJButtonAdd().addActionListener(this);
97
                bs.getFileList().getJButtonRemove().addActionListener(this);
98
                bs.getNumBandSelectorCombo().addActionListener(this);
99
        }
100

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

    
121
                // Si dos bandas coinciden, se dice que no es correcta la asignacion
122
                int list[] = { r, g, b, a };
123
                for (int i = 0; i <= 3; i++)
124
                        for (int j = 0; j <= 3; j++)
125
                                if ((i != j) && (list[i] == list[j]) && (list[i] > -1))
126
                                        return false;
127

    
128
                return true;
129
        }
130

    
131
        /**
132
         * Constructor
133
         * @param bs Panel del selector de bandas
134
         * @param lyr Capa raster
135
         */
136
        public void init(FLyrRaster lyr) {
137
                fLayer = lyr;
138
        }
139

    
140
        /**
141
         * Listener para la gesti?n de los botones de a?adir, eliminar fichero y
142
         * el combo de selecci?n de bandas.
143
         */
144
        public void actionPerformed(ActionEvent e) {
145

    
146
                if (e.getSource().equals(bandSetupPanel.getFileList().getJButtonAdd()))
147
                        addFileBand();
148

    
149
                if (e.getSource().equals(bandSetupPanel.getFileList().getJButtonRemove()))
150
                        delFileBand();
151

    
152
                if (e.getSource().equals(bandSetupPanel.getNumBandSelectorCombo())) {
153
                        String vBands = (String) bandSetupPanel.getNumBandSelectorCombo().getSelectedItem();
154
                        if (vBands != null) {
155
                                if (vBands.compareTo("3") == 0)
156
                                        bandSetupPanel.resetMode(3);
157

    
158
                                if (vBands.compareTo("2") == 0)
159
                                        bandSetupPanel.resetMode(2);
160

    
161
                                if (vBands.compareTo("1") == 0)
162
                                        bandSetupPanel.resetMode(1);
163
                        }
164
                }
165

    
166
                if (e.getSource().equals(bandSetupPanel.getSaveButton())) {
167
                        int rBand = bandSetupPanel.getAssignedBand(RasterDataStore.RED_BAND);
168
                        int gBand = bandSetupPanel.getAssignedBand(RasterDataStore.GREEN_BAND);
169
                        int bBand = bandSetupPanel.getAssignedBand(RasterDataStore.BLUE_BAND);
170
                        int aBand = bandSetupPanel.getAssignedBand(RasterDataStore.ALPHA_BAND);
171

    
172
                        if (!isCorrectAssignedBand(rBand, gBand, bBand, aBand)) {
173
                                RasterToolsUtil.messageBoxError(Messages.getText("combinacion_no_asignable"), bandSetupPanel);
174
                                return;
175
                        }
176

    
177
                        RasterToolsUtil.messageBoxYesOrNot(Messages.getText("color_interpretation_continue"), this);
178
                        RasterDataStore dataSource = fLayer.getDataStore();
179
                        if(dataSource == null) {
180
                                RasterToolsUtil.messageBoxError(Messages.getText("error_carga_capa"), bandSetupPanel);
181
                                return;
182
                        }
183

    
184
                        ColorInterpretation ci = dataSource.getColorInterpretation();
185
                        try {
186
                                // Combinaci?n GRAY
187
                                if ((rBand == gBand) && (rBand == bBand) && (rBand >= 0)) {
188
                                        for (int iBand = 0; iBand < bandSetupPanel.getARGBTable().getRowCount(); iBand++) {
189
                                                ci.setColorInterpValue(iBand, ColorInterpretation.UNDEF_BAND);
190
                                        }
191
                                        ci.setColorInterpValue(rBand, ColorInterpretation.GRAY_BAND);
192
                                        ci.setColorInterpValue(aBand, ColorInterpretation.ALPHA_BAND);
193
                                } else {
194
                                        // Combinaci?n RGB
195
                                        for (int iBand = 0; iBand < bandSetupPanel.getARGBTable().getRowCount(); iBand++)
196
                                                ci.setColorInterpValue(iBand, bandSetupPanel.getColorInterpretationByBand(iBand));
197
                                }
198
                                String fileName = fLayer.getDataStore().getName();
199
                                RasterLocator.getManager().getProviderServices().saveObjectToRmfFile(fileName, ci);
200
                        } catch (RmfSerializerException exc) {
201
                                RasterToolsUtil.messageBoxError(Messages.getText("error_salvando_rmf"), bandSetupPanel, exc);
202
                        } catch (NotInitializeException exc) {
203
                                RasterToolsUtil.messageBoxError(Messages.getText("table_not_initialize"), bandSetupPanel, exc);
204
                        }
205
                }
206

    
207
                if (!RasterExtension.autoRefreshView)
208
                        return;
209

    
210
                bandSetupPanel.onlyApply();
211
        }
212

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

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

    
235
                double widthNewFile = (extentNewFile.getMax().getX() - extentNewFile.getMin().getX());
236
                double heightNewFile = (extentNewFile.getMax().getY() - extentNewFile.getMin().getY());
237

    
238
                if ((widthNewFile - extentOrigin.getWidth()) > 1.0 || (widthNewFile - extentOrigin.getWidth()) < -1.0 || (heightNewFile - extentOrigin.getHeight()) > 1.0
239
                                || (heightNewFile - extentOrigin.getHeight()) < -1.0) {
240
                        return false;
241
                }
242

    
243
                if ((extentNewFile.getMax().getX() - extentNewFile.getMin().getX()) != extentOrigin.getWidth()
244
                                || (extentNewFile.getMax().getY() - extentNewFile.getMin().getY()) != extentOrigin.getHeight()) {
245
                        return false;
246
                }
247

    
248
                dataStore.close();
249
                return true;
250
        }
251
        
252
        /**
253
         * A?ade una banda al raster
254
         * @param e
255
         */
256
        private void addFileBand() {
257
                // String[] driverNames = null;
258

    
259
                // Creaci?n del dialogo para selecci?n de ficheros
260
                
261
                fileChooser = new JFileChooser(
262
                                FilesystemExplorerWizardPanel.OPEN_LAYER_FILE_CHOOSER_ID,
263
                                JFileChooser.getLastPath(FilesystemExplorerWizardPanel.OPEN_LAYER_FILE_CHOOSER_ID, null));
264
                fileChooser.setMultiSelectionEnabled(true);
265
                fileChooser.setAcceptAllFileFilterUsed(false);
266

    
267
                fileChooser.addChoosableFileFilter(new DriverFileFilter());
268

    
269
                int result = fileChooser.showOpenDialog(bandSetupPanel);
270

    
271
                if (result == JFileChooser.APPROVE_OPTION) {
272
                        RasterDataStore dataStore = fLayer.getDataStore();
273
                        File[] files = fileChooser.getSelectedFiles();
274

    
275
                        JFileChooser.setLastPath(FilesystemExplorerWizardPanel.OPEN_LAYER_FILE_CHOOSER_ID, files[0]);
276
                        
277
                        fileList = new ArrayList<File>();
278
                        
279
                        for (int i = 0; i < files.length; i++) {
280
                                //Checks that the file does not exist
281
                                String[] uris = dataStore.getURIByProvider();
282
                                boolean exists = false;
283
                                for (int j = 0; j < uris.length; j++) {
284
                                        if (uris[j].endsWith(files[i].getName())) {
285
                                                RasterToolsUtil.messageBoxError( Messages.getText("fichero_existe") + ": " + files[i].getAbsolutePath(), bandSetupPanel);
286
                                                exists = true;
287
                                                break;
288
                                        }
289
                                }
290
                                if(!exists)
291
                                        fileList.add(files[i]);
292
                        }
293
                        
294
                        for (int i = fileList.size() - 1; i >= 0; i--) {
295
                                //Checks extents
296
                                try {
297
                                        if(!checkNewFile(fileList.get(i).getAbsolutePath())) {
298
                                                JOptionPane.showMessageDialog(null, Messages.getText("extents_no_coincidentes") +  " " + files[i].getAbsolutePath(), "", JOptionPane.ERROR_MESSAGE);
299
                                                fileList.remove(i);
300
                                        }
301
                                } catch (Exception e) {
302
                                        log.debug("Problems check the bounding boxes", e);
303
                                }
304
                        }
305
                        
306
                        if(dataStore.isTiled()) {
307
                                if(!RasterToolsUtil.messageBoxYesOrNot(Messages.getText("store_tiled"), this)) {
308
                                        return;
309
                                }
310
                        }
311
                        
312
                        if(dataStore.isMultiFile()) {
313
                                for (int i = 0; i < fileList.size(); i++) {
314
                                        try {
315
                                                dataStore.addFile(fileList.get(i).getAbsolutePath());
316
                                        } catch (InvalidSourceException e) {
317
                                                RasterToolsUtil.messageBoxError(Messages.getText("addband_error"), bandSetupPanel, e);
318
                                        }
319
                                }
320
                                
321
                                dataStore.setProvider(dataStore.getProvider());
322
                                
323
                                //It shows the files and bands in the panel
324
                                try {
325
                                        bandSetupPanel.addFiles(dataStore);
326
                                } catch (NotInitializeException e) {
327
                                        RasterToolsUtil.messageBoxError("table_not_initialize", this, e);
328
                                }
329
                        } else {
330
                                //New layer name
331
                                WindowInfo wi = PluginServices.getMDIManager().getActiveWindow().getWindowInfo();
332
                                LayerNameDialog dialog = new LayerNameDialog(new Point2D.Double(wi.getX(), wi.getY()), 300, 80, this);
333
                                RasterToolsUtil.addWindow(dialog);
334
                        }
335
                }
336
        }
337
        
338
        /**
339
         * Catchs the events from LayerNameDialog to get the name of the new layer
340
         */
341
        public void actionButtonPressed(ButtonsPanelEvent e) {
342
                String layerName = (String)e.getSource();
343
        
344
                RasterDataStore dataStore = fLayer.getDataStore();
345
                RasterDataParameters paramFirstFile = (RasterDataParameters)dataStore.getParameters();//(RasterDataParameters)((RasterProvider)dataStore.getProvider()).getDataParameters();
346
                
347
                ProviderServices provServ = RasterLocator.getManager().getProviderServices();
348
                DataManagerProviderServices dataManager = (DataManagerProviderServices)DALLocator.getDataManager();
349

    
350
                try {
351
                        //It creates the new Multifile provider
352
                        DataServerExplorerParameters explParams = dataManager.createServerExplorerParameters(MultiFileProvider.NAME);
353
                        DataServerExplorer explorer = dataManager.openServerExplorer(MultiFileProvider.NAME, explParams);
354
                        MultiFileDataParameters newParamsMultifile = (MultiFileDataParameters)dataManager.createStoreParameters(explorer.getProviderName());
355
                        String path = paramFirstFile.getURI().substring(0, paramFirstFile.getURI().lastIndexOf(File.separator) + 1);
356
                        String fileURI = path + layerName + ".mff";
357
                        String rmfURI = path + layerName + ".rmf";
358
                        int counter = 0;
359
                        while(new File(fileURI).exists() || new File(rmfURI).exists()) {
360
                                fileURI = path + layerName + "_" + counter + ".mff";
361
                                rmfURI = path + layerName + "_" + counter + ".rmf";
362
                                counter ++;
363
                        }
364
                        if(counter > 0)
365
                                layerName += "_" + counter;
366
                        
367
                        newParamsMultifile.setURI(fileURI);
368
                        newParamsMultifile.addProvider(dataStore);
369
                        DataStoreProvider provMultifile = dataManager.createProvider((DataStoreProviderServices)dataStore, newParamsMultifile);
370

    
371
                        //And now it creates and adds the new ones
372
                        for (int i = 0; i < fileList.size(); i++) {
373
                                ArrayList<RasterDataParameters> storeParametersList = provServ.createParametersList(fileList.get(i).getAbsolutePath());
374
                                for (int j = 0; j < storeParametersList.size(); j++) {
375
                                        DataStoreProvider newFileProv = dataManager.createProvider((DataStoreProviderServices)dataStore, storeParametersList.get(j));
376
                                        newParamsMultifile.addProviderNotTiled(newFileProv);
377
                                }
378
                        }
379

    
380
                        ((DefaultFLyrRaster)fLayer).setName(layerName);
381
                        //Assigns the MultifileProvider to the store
382
                        dataStore.setProvider((CoverageStoreProvider)provMultifile);
383

    
384
                        //It shows the files and bands in the panel
385
                        try {
386
                                bandSetupPanel.addFiles(dataStore);
387
                        } catch (NotInitializeException ex) {
388
                                RasterToolsUtil.messageBoxError(Messages.getText("table_not_initialize"), this, ex);
389
                        }
390
                        
391
                        ArrayList<File> uriList = new ArrayList<File>();
392
                        uriList.add(new File(paramFirstFile.getURI()));
393
                        for (int i = 0; i < fileList.size(); i++) {
394
                                uriList.add(fileList.get(i));
395
                        }
396
                        saveMultiFileLayer(layerName, paramFirstFile.getURI(), uriList);
397

    
398
                } catch (Exception exc) {
399
                        RasterToolsUtil.messageBoxError(Messages.getText("addband_error"), bandSetupPanel, exc);
400
                }
401
        }
402
        
403
        /**
404
         * Saves the new layer in disk
405
         * @param layerName
406
         * @param file
407
         * @param uriList
408
         * @throws IOException
409
         */
410
        private String saveMultiFileLayer(String layerName, String file, ArrayList<File> uriList) throws IOException {
411
                String path = file.substring(0, file.lastIndexOf(File.separator) + 1);
412
                path = path + layerName + ".mff";
413
                
414
                /*File filePath = new File(path);
415
                if(filePath.exists()) {
416
                        RasterToolsUtil.messageBoxInfo("file_exists_rename", bandSetupPanel);
417
                        filePath.renameTo(new File(path + "~"));
418
                }*/
419
                
420
                MultiFileFormat format = new MultiFileFormat();
421
                for (int i = 0; i < uriList.size(); i++) {
422
                        format.addFile(uriList.get(i));
423
                }
424
                format.setName(layerName);
425
                
426
                format.write(path);
427
                return path;
428
        }
429

    
430
        /**
431
         * Elimina una banda del raster. Si queda solo un fichero o no se ha
432
         * seleccionado ninguna banda no hace nada.
433
         *
434
         * @param e
435
         */
436
        private void delFileBand() {
437
                Object[] objects = bandSetupPanel.getFileList().getJList().getSelectedValues();
438
                RasterDataStore dataStore = fLayer.getDataStore();
439
                
440
                for (int i = objects.length - 1; i >= 0; i--) {
441
                        if (bandSetupPanel.getFileList().getNFiles() > 1) {
442
                                String pathName = objects[i].toString();
443
                                dataStore.removeFile(pathName);
444

    
445
                                String file = pathName.substring(pathName.lastIndexOf(File.separator) + 1);
446
                                file = file.substring(file.lastIndexOf("\\") + 1);
447
                                bandSetupPanel.removeFile(file);
448
                        }
449
                }
450
                
451
                setNewBandsPositionInRendering();
452
        }
453

    
454
        /**
455
         * Acciones a ejecutar cuando se aplica
456
         */
457
        public void apply() {
458
                if (enabled)
459
                        setNewBandsPositionInRendering();
460
        }
461

    
462
        /**
463
         * Asigna la posici?n de las bandas en el rederizado basandose en la selecci?n
464
         * hecho en la tabla de bandas.
465
         */
466
        public void setNewBandsPositionInRendering() {
467
                if (fLayer != null && fLayer.getRender() != null) {
468
                        fLayer.getRender().setRenderBands(new int[]{bandSetupPanel.getAssignedBand(RasterDataStore.RED_BAND),
469
                                        bandSetupPanel.getAssignedBand(RasterDataStore.GREEN_BAND),
470
                                        bandSetupPanel.getAssignedBand(RasterDataStore.BLUE_BAND)});
471
                        int alphaBand = bandSetupPanel.getAssignedBand(RasterDataStore.ALPHA_BAND);
472
                        // Ultima transparencia aplicada en el renderizador
473
                        Transparency gt = fLayer.getRender().getLastTransparency();
474
                        if(gt != null)
475
                                gt.setTransparencyBand(alphaBand);
476

    
477
                        // Transparencia del dataset
478
                        /*if(fLayer.getDataStore() != null) {
479
                                Transparency t = fLayer.getDataStore().getTransparency();
480
                                if(t != null)
481
                                        t.setTransparencyBand(alphaBand);
482
                        }*/
483
                        fLayer.getMapContext().invalidate();
484
                }
485
        }
486

    
487
        /**
488
         * Activa o desactiva la acci?n del panel
489
         * @param enabled true para activa y false para desactivar.
490
         */
491
        public void setEnabledPanelAction(boolean enabled) {
492
                this.enabled = enabled;
493
        }
494

    
495
}