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

History | View | Annotate | Download (17.5 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.serverexplorer.filesystem.swing.FilesystemExplorerWizardPanel;
53
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
54
import org.gvsig.fmap.dal.spi.DataStoreProvider;
55
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
56
import org.gvsig.gui.beans.buttonspanel.ButtonsPanelEvent;
57
import org.gvsig.gui.beans.buttonspanel.ButtonsPanelListener;
58
import org.gvsig.gui.beans.swing.JFileChooser;
59
import org.gvsig.gui.beans.table.exceptions.NotInitializeException;
60
import org.gvsig.raster.fmap.layers.DefaultFLyrRaster;
61
import org.gvsig.raster.fmap.layers.FLyrRaster;
62
import org.gvsig.raster.tools.app.basic.RasterExtension;
63
import org.gvsig.raster.tools.app.basic.RasterToolsUtil;
64
import org.gvsig.raster.tools.app.basic.raster.gui.wizard.DriverFileFilter;
65
import org.gvsig.raster.tools.multifile.io.MultiFileDataParameters;
66
import org.gvsig.raster.tools.multifile.io.MultiFileFormat;
67
import org.gvsig.raster.tools.multifile.io.MultiFileProvider;
68
import org.gvsig.tools.locator.LocatorException;
69

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

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

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

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

    
123
                return true;
124
        }
125

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

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

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

    
205
                bandSetupPanel.onlyApply();
206
        }
207

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

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

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

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

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

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

    
254
                // Creaci?n del dialogo para selecci?n de ficheros
255
                
256
                fileChooser = new JFileChooser(
257
                                FilesystemExplorerWizardPanel.OPEN_LAYER_FILE_CHOOSER_ID,
258
                                JFileChooser.getLastPath(FilesystemExplorerWizardPanel.OPEN_LAYER_FILE_CHOOSER_ID, null));
259
                fileChooser.setMultiSelectionEnabled(true);
260
                fileChooser.setAcceptAllFileFilterUsed(false);
261

    
262
                fileChooser.addChoosableFileFilter(new DriverFileFilter());
263

    
264
                int result = fileChooser.showOpenDialog(bandSetupPanel);
265

    
266
                if (result == JFileChooser.APPROVE_OPTION) {
267
                        RasterDataStore dataStore = fLayer.getDataStore();
268
                        File[] files = fileChooser.getSelectedFiles();
269

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

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

    
339
                try {
340
                        //It creates the new Multifile provider
341
                        DataServerExplorerParameters explParams = dataManager.createServerExplorerParameters(MultiFileProvider.NAME);
342
                        DataServerExplorer explorer = dataManager.openServerExplorer(MultiFileProvider.NAME, explParams);
343
                        MultiFileDataParameters newParamsMultifile = (MultiFileDataParameters)dataManager.createStoreParameters(explorer.getProviderName());
344
                        String path = paramFirstFile.getURI().substring(0, paramFirstFile.getURI().lastIndexOf(File.separator) + 1);
345
                        String fileURI = path + layerName + ".mff";
346
                        String rmfURI = path + layerName + ".rmf";
347
                        int counter = 0;
348
                        while(new File(fileURI).exists() || new File(rmfURI).exists()) {
349
                                fileURI = path + layerName + "_" + counter + ".mff";
350
                                rmfURI = path + layerName + "_" + counter + ".rmf";
351
                                counter ++;
352
                        }
353
                        if(counter > 0)
354
                                layerName += "_" + counter;
355
                        
356
                        newParamsMultifile.setURI(fileURI);
357
                        newParamsMultifile.addProvider(dataStore);
358
                        DataStoreProvider provMultifile = dataManager.createProvider((DataStoreProviderServices)dataStore, newParamsMultifile);
359

    
360
                        //And now it creates and adds the new ones
361
                        for (int i = 0; i < fileList.size(); i++) {
362
                                ArrayList<RasterDataParameters> storeParametersList = provServ.createParametersList(fileList.get(i).getAbsolutePath());
363
                                for (int j = 0; j < storeParametersList.size(); j++) {
364
                                        DataStoreProvider newFileProv = dataManager.createProvider((DataStoreProviderServices)dataStore, storeParametersList.get(j));
365
                                        newParamsMultifile.addProviderNotTiled(newFileProv);
366
                                }
367
                        }
368

    
369
                        ((DefaultFLyrRaster)fLayer).setName(layerName);
370
                        //Assigns the MultifileProvider to the store
371
                        dataStore.setProvider((CoverageStoreProvider)provMultifile);
372

    
373
                        //It shows the files and bands in the panel
374
                        try {
375
                                bandSetupPanel.addFiles(dataStore);
376
                        } catch (NotInitializeException ex) {
377
                                RasterToolsUtil.messageBoxError("table_not_initialize", this, ex);
378
                        }
379
                        
380
                        ArrayList<File> uriList = new ArrayList<File>();
381
                        uriList.add(new File(paramFirstFile.getURI()));
382
                        for (int i = 0; i < fileList.size(); i++) {
383
                                uriList.add(fileList.get(i));
384
                        }
385
                        saveMultiFileLayer(layerName, paramFirstFile.getURI(), uriList);
386

    
387
                } catch (Exception exc) {
388
                        RasterToolsUtil.messageBoxError("addband_error", bandSetupPanel, exc);
389
                }
390
        }
391
        
392
        /**
393
         * Saves the new layer in disk
394
         * @param layerName
395
         * @param file
396
         * @param uriList
397
         * @throws IOException
398
         */
399
        private String saveMultiFileLayer(String layerName, String file, ArrayList<File> uriList) throws IOException {
400
                String path = file.substring(0, file.lastIndexOf(File.separator) + 1);
401
                path = path + layerName + ".mff";
402
                
403
                /*File filePath = new File(path);
404
                if(filePath.exists()) {
405
                        RasterToolsUtil.messageBoxInfo("file_exists_rename", bandSetupPanel);
406
                        filePath.renameTo(new File(path + "~"));
407
                }*/
408
                
409
                MultiFileFormat format = new MultiFileFormat();
410
                for (int i = 0; i < uriList.size(); i++) {
411
                        format.addFile(uriList.get(i));
412
                }
413
                format.setName(layerName);
414
                
415
                format.write(path);
416
                return path;
417
        }
418

    
419
        /**
420
         * Elimina una banda del raster. Si queda solo un fichero o no se ha
421
         * seleccionado ninguna banda no hace nada.
422
         *
423
         * @param e
424
         */
425
        private void delFileBand() {
426
                Object[] objects = bandSetupPanel.getFileList().getJList().getSelectedValues();
427
                RasterDataStore dataStore = fLayer.getDataStore();
428
                
429
                for (int i = objects.length - 1; i >= 0; i--) {
430
                        if (bandSetupPanel.getFileList().getNFiles() > 1) {
431
                                String pathName = objects[i].toString();
432
                                dataStore.removeFile(pathName);
433

    
434
                                String file = pathName.substring(pathName.lastIndexOf(File.separator) + 1);
435
                                file = file.substring(file.lastIndexOf("\\") + 1);
436
                                bandSetupPanel.removeFile(file);
437
                        }
438
                }
439
                
440
                setNewBandsPositionInRendering();
441
        }
442

    
443
        /**
444
         * Acciones a ejecutar cuando se aplica
445
         */
446
        public void apply() {
447
                if (enabled)
448
                        setNewBandsPositionInRendering();
449
        }
450

    
451
        /**
452
         * Asigna la posici?n de las bandas en el rederizado basandose en la selecci?n
453
         * hecho en la tabla de bandas.
454
         */
455
        public void setNewBandsPositionInRendering() {
456
                if (fLayer != null && fLayer.getRender() != null) {
457
                        fLayer.getRender().setRenderBands(new int[]{bandSetupPanel.getAssignedBand(RasterDataStore.RED_BAND),
458
                                        bandSetupPanel.getAssignedBand(RasterDataStore.GREEN_BAND),
459
                                        bandSetupPanel.getAssignedBand(RasterDataStore.BLUE_BAND)});
460
                        int alphaBand = bandSetupPanel.getAssignedBand(RasterDataStore.ALPHA_BAND);
461
                        // Ultima transparencia aplicada en el renderizador
462
                        Transparency gt = fLayer.getRender().getLastTransparency();
463
                        if(gt != null)
464
                                gt.setTransparencyBand(alphaBand);
465

    
466
                        // Transparencia del dataset
467
                        /*if(fLayer.getDataStore() != null) {
468
                                Transparency t = fLayer.getDataStore().getTransparency();
469
                                if(t != null)
470
                                        t.setTransparencyBand(alphaBand);
471
                        }*/
472
                        fLayer.getMapContext().invalidate();
473
                }
474
        }
475

    
476
        /**
477
         * Activa o desactiva la acci?n del panel
478
         * @param enabled true para activa y false para desactivar.
479
         */
480
        public void setEnabledPanelAction(boolean enabled) {
481
                this.enabled = enabled;
482
        }
483

    
484
}