Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRemoteSensing / src / org / gvsig / remotesensing / gridmath / gui / listener / GridMathPanelListener.java @ 20872

History | View | Annotate | Download (12.3 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Instituto de Desarrollo Regional 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
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   Instituto de Desarrollo Regional (Universidad de Castilla La-Mancha)
34
 *   Campus Universitario s/n
35
 *   02071 Alabacete
36
 *   Spain
37
 *
38
 *   +34 967 599 200
39
 */
40

    
41
package org.gvsig.remotesensing.gridmath.gui.listener;
42

    
43
import java.io.File;
44
import java.util.Iterator;
45

    
46
import javax.swing.JFileChooser;
47
import javax.swing.event.TableModelEvent;
48
import javax.swing.event.TableModelListener;
49

    
50
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
51
import org.gvsig.gui.beans.buttonspanel.ButtonsPanel;
52
import org.gvsig.gui.beans.buttonspanel.ButtonsPanelEvent;
53
import org.gvsig.gui.beans.buttonspanel.ButtonsPanelListener;
54
import org.gvsig.raster.RasterLibrary;
55
import org.gvsig.raster.buffer.BufferFactory;
56
import org.gvsig.raster.buffer.RasterBuffer;
57
import org.gvsig.raster.dataset.GeoRasterWriter;
58
import org.gvsig.raster.dataset.InvalidSetViewException;
59
import org.gvsig.raster.dataset.io.RasterDriverException;
60
import org.gvsig.raster.util.ExtendedFileFilter;
61
import org.gvsig.raster.util.RasterToolsUtil;
62
import org.gvsig.remotesensing.gridmath.ErrorSintaxisException;
63
import org.gvsig.remotesensing.gridmath.GridMathProcess;
64
import org.gvsig.remotesensing.gridmath.NoAssignedVarsException;
65
import org.gvsig.remotesensing.gridmath.NoVarsException;
66
import org.gvsig.remotesensing.gridmath.gui.GridMathPanel;
67
import org.nfunk.jep.JEP;
68
import org.nfunk.jep.Variable;
69

    
70
import com.iver.andami.PluginServices;
71
import com.iver.andami.Utilities;
72
import com.iver.cit.gvsig.addlayer.fileopen.FileOpenWizard;
73
import com.iver.cit.gvsig.fmap.layers.FLayer;
74
import com.iver.cit.gvsig.fmap.layers.FLayers;
75

    
76

    
77
/**
78
 * Listener para el panel de la calculadora de bandas
79
 * 
80
 * @author Diego Guerrero Sevilla (diego.guerrero@uclm.es)
81
 * @author Alejandro Mu?oz S?nchez        (alejandro.munoz@uclm.es)
82
 * @version 19/10/2007 
83
 */
84
public class GridMathPanelListener implements ButtonsPanelListener, TableModelListener {
85
        
86
        private GridMathPanel gridMathPanel = null;
87
        private boolean canClose = false;
88

    
89
        
90
        /**
91
         * Constructor
92
         * @param calculatorPanel
93
         */
94
        public GridMathPanelListener(GridMathPanel calculatorPanel) {
95
                this.gridMathPanel = calculatorPanel;
96
        
97
        }
98

    
99

    
100
        /*
101
         * (non-Javadoc)
102
         * @see org.gvsig.gui.beans.buttonspanel.ButtonsPanelListener#actionButtonPressed(org.gvsig.gui.beans.buttonspanel.ButtonsPanelEvent)
103
         */
104
        public void actionButtonPressed(ButtonsPanelEvent e) {
105
                // Bot?n de Aceptar
106
                
107
                        if (e.getButton() == ButtonsPanel.BUTTON_ACCEPT) {
108
                                aplicar();
109
                                if(canClose)
110
                                        close();
111
                        }
112
                        // Bot?n de Aplicar
113
                        if (e.getButton() == ButtonsPanel.BUTTON_APPLY) {
114
                                aplicar();
115
                        }
116
        
117

    
118
                // Bot?n de Cerrar
119
                if (e.getButton() == ButtonsPanel.BUTTON_CANCEL) {
120
                        close();
121
                }
122
        }
123

    
124
        
125
         /**        
126
         *        Acciones al aplicar. Comprobar que la lista de variables no es vacia, que todas las variables
127
         *  estan asignadas, y que la expresi?n es correcta. Si se cumplen los requisitos se lanza el calculo.
128
         */
129
        private void aplicar(){
130
        
131
                try{
132
        
133
                canClose = false;
134
                if (gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getRowCount()>0){
135
                        boolean allAsigned=true;
136
        
137
                        // Comprobar que todas las variables estan asignadas
138
                        for (int i=0; i<gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getRowCount(); i++){
139
                                if (gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getValueAt(i,1).toString().equals(""))
140
                                { allAsigned=false; break;}
141
                        }
142
        
143
                        if (allAsigned){
144
                                if(!gridMathPanel.getCalculatorPanel().getParser().hasError()){
145
                                        canClose  = true;
146
                                        calculate();
147
                                }
148
                                else{
149
                                        throw new ErrorSintaxisException();
150
                                }
151
                        }else{                        
152
                                throw new NoAssignedVarsException();
153
                        }
154
                
155
                }else {
156
                        throw new NoVarsException();
157
                        }
158
                } catch (ErrorSintaxisException exc) {
159
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "bad_expresion"), this);
160
                }catch (NoAssignedVarsException exc){
161
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this,"variables_sin_asignar"),this);
162
                }catch (NoVarsException exc){
163
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this,"no_variables"),this);
164
                }
165
        }
166
        
167
        
168
        /**
169
         * M?todo que construye el HasMap con los params y lanza el proceso para el 
170
         * calculo del raster resultante. 
171
         * 
172
         */
173
        private void calculate(){
174

    
175
                int nBand;
176
                String layerBand;
177
                String layerName;
178
                FLyrRasterSE rasterLayer;
179
        
180
                String path = getFileSelected();
181
                if (path == null)
182
                        return;                
183
                FLayers layers = gridMathPanel.getView().getModel().getMapContext().getLayers();
184
                
185
                // Extent de salida personalizado.
186
                if (gridMathPanel.getOptionsPanel().getRButtom2().isSelected()){
187
                        try{
188
                        gridMathPanel.getOutputExtent().setXRange(Double.parseDouble(gridMathPanel.getOptionsPanel().getJTextRangoX1().getText()),Double.parseDouble(gridMathPanel.getOptionsPanel().getJTextRangoX2().getText()));
189
                        gridMathPanel.getOutputExtent().setYRange(Double.parseDouble(gridMathPanel.getOptionsPanel().getJTextRangoY1().getText()), Double.parseDouble(gridMathPanel.getOptionsPanel().getJTextRangoY2().getText()));
190
                        gridMathPanel.getOutputExtent().setCellSizeX(Double.parseDouble(gridMathPanel.getOptionsPanel().getJTextCellSizeX().getText()));
191
                        gridMathPanel.getOutputExtent().setCellSizeY(Double.parseDouble(gridMathPanel.getOptionsPanel().getJTextCellSizeY().getText()));
192
                        }catch (NumberFormatException  e) {
193
                                RasterToolsUtil.messageBoxError(PluginServices.getText(this, "invalid_number"), this);
194
                                return;
195
                        }
196
                }
197
                //        Extent de salida a partir de una capa.
198
                else if(gridMathPanel.getOptionsPanel().getRButtom4().isSelected()){
199
                        try {
200
                                FLayer layer = layers.getLayer(gridMathPanel.getOptionsPanel().getJComboCapas().getSelectedIndex());        
201
                                gridMathPanel.getOutputExtent().setXRange(layer.getFullExtent().getMinX(),
202
                                                layer.getFullExtent().getMaxX());
203
                                gridMathPanel.getOutputExtent().setYRange(layer.getFullExtent().getMinY(),
204
                                                layer.getFullExtent().getMaxY());
205
                                gridMathPanel.getOutputExtent().setCellSize(Double.parseDouble(gridMathPanel.getOptionsPanel().getJTextCellSizeX().getText()));                
206
                                gridMathPanel.getOptionsPanel().extentHasChanged();
207
                        } catch (Exception ex) {
208
                                ex.printStackTrace();
209
                        }
210
                }
211
                gridMathPanel.getGridMath().setResultExtent(gridMathPanel.getOutputExtent());
212
                
213
                 //Rellenar el HasMap con el buffer corespondiente a cada variable
214
                
215
                RasterBuffer valor=null;
216
                for (int i=0;i<gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getRowCount();i++){
217
                        
218
                        layerBand= gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getValueAt(i,1).toString();
219
                        layerName = layerBand.substring(0,layerBand.indexOf("["));
220
                        nBand = Integer.valueOf(layerBand.substring(layerBand.lastIndexOf("Band")+4,layerBand.lastIndexOf("]"))).intValue();
221
                        rasterLayer = (FLyrRasterSE)layers.getLayer(layerName);                
222
                        BufferFactory bufferFactory= rasterLayer.getBufferFactory();
223
                        
224
                        double minX=0,minY=0,maxX=0,maxY=0;
225
                        minX= gridMathPanel.getOutputExtent().getMin().getX();
226
                        minY= gridMathPanel.getOutputExtent().getMin().getY();
227
                        maxX= gridMathPanel.getOutputExtent().getMax().getX();
228
                        maxY =gridMathPanel.getOutputExtent().getMax().getY();
229
                        
230
                        try {
231
                                        bufferFactory.setAdjustToExtent(false);
232
                                        bufferFactory.setDrawableBands(new int[]{nBand-1});
233
                                        bufferFactory.setAreaOfInterest(minX,minY,maxX,maxY,gridMathPanel.getOutputExtent().getNX(),gridMathPanel.getOutputExtent().getNY());
234
                                        valor=(RasterBuffer) bufferFactory.getRasterBuf();
235
                                
236
                        } catch (ArrayIndexOutOfBoundsException e) {
237
                                RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e);
238
                        } catch (InvalidSetViewException e) {
239
                                        e.printStackTrace();
240
                        } catch (InterruptedException e) {
241
                                Thread.currentThread().interrupt();
242
                        } catch (RasterDriverException e) {
243
                                e.printStackTrace();
244
                        }
245
        
246
                        gridMathPanel.getCalculatorPanel().getQWindowsHash().put(gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getValueAt(i,0).toString(),new Object[]{valor,new Integer(valor.getDataType())});
247
                        
248
                }                                
249
                gridMathPanel.getGridMath().setParams(gridMathPanel.getCalculatorPanel().getQWindowsHash());
250
                
251
                
252
                /*
253
                Comprobar que todas las variables que intervienen en la expresion 
254
                estan en el HasMap de parametros.
255
                 */
256
                JEP parser = new JEP();
257
                parser.setAllowUndeclared(true);
258
                parser.addStandardFunctions();
259
                parser.parseExpression(gridMathPanel.getCalculatorPanel().getJTextExpression().getText());
260
        
261
                for (Iterator iter = parser.getSymbolTable().values().iterator(); iter.hasNext();) {
262
                        Variable variable = (Variable) iter.next();        
263
                        if (!gridMathPanel.getGridMath().getParams().containsKey(variable.getName())){
264
                                        RasterToolsUtil.messageBoxError(PluginServices.getText(this,"variables_sin_asignar"),this);
265
                                        return;
266
                                }
267
                }
268
                                
269
                 // Lanzar el proceso de c?lculo.
270
                GridMathProcess process = new GridMathProcess();
271
                process.addParam("expresion",gridMathPanel.getCalculatorPanel().getJTextExpression().getText());        
272
                process.addParam("params",gridMathPanel.getGridMath().getParams());        
273
                process.addParam("extent",gridMathPanel.getOutputExtent());
274
                process.addParam("mapcontext",gridMathPanel.getView().getModel().getMapContext());
275
                process.addParam("filepath", path);
276
            process.start();
277
        
278
        }
279
        
280
        
281
        /**
282
         * Acciones al cerrar
283
         */
284
        private void close() {
285
                PluginServices.getMDIManager().closeWindow(gridMathPanel.getCalculatorDialog());
286
        }
287
        
288

    
289
        public void tableChanged(TableModelEvent e) {
290
                gridMathPanel.getOptionsPanel().InicializarOpcion();
291
        }
292
        
293
        /**
294
         * Devuelve la ruta del fichero donde se va a guardar, en caso de guardarse
295
         * en memoria, calcula el nombre sin preguntar y devuelve la ruta.
296
         * @return string con la ruta de salida
297
         */
298
        public String getFileSelected() {
299
                String path = "";
300
                if (gridMathPanel.getOptionsPanel().getRadioFile().isSelected()) {
301
                        JFileChooser chooser = new JFileChooser(FileOpenWizard.getLastPath());
302
                        chooser.setDialogTitle(PluginServices.getText(this, "seleccionar_fichero"));
303
                        //A?adimos las extensiones que hayan sido registradas en el driver
304
                        String[] extList = GeoRasterWriter.getDriversExtensions();
305
                        for(int i=0;i<extList.length;i++)
306
                                chooser.addChoosableFileFilter(new ExtendedFileFilter(extList[i]));
307

    
308
                        if (chooser.showOpenDialog(gridMathPanel.getOptionsPanel()) != JFileChooser.APPROVE_OPTION)
309
                                return null;
310

    
311
                        FileOpenWizard.setLastPath(chooser.getSelectedFile().getPath().substring(0, chooser.getSelectedFile().getPath().lastIndexOf(File.separator)));
312
                        ExtendedFileFilter fileFilter = (ExtendedFileFilter) chooser.getFileFilter();
313
                        path = fileFilter.getNormalizedFilename(chooser.getSelectedFile());
314
                } else {
315
                        String file = gridMathPanel.getOptionsPanel().getJTextNombreCapa().getText();
316
                        path = Utilities.createTempDirectory() + File.separator + gridMathPanel.getOptionsPanel().getJTextNombreCapa().getText() + ".tif";
317
                        if(file.compareTo(RasterLibrary.getOnlyLayerName()) == 0) 
318
                                RasterLibrary.usesOnlyLayerName();
319
                        gridMathPanel.getOptionsPanel().updateNewLayerText();
320
                }
321
                
322
                return path;
323
        }
324
        
325
}
326

    
327
/**
328
 * @author Nacho Brodin <brodin_ign@gva.es>
329
 * Filtro para el selector de formatos de escritura
330
 */
331
class WriterFilter extends javax.swing.filechooser.FileFilter {
332
        private String                                filter;
333

    
334
        public WriterFilter(String fil) {
335
                this.filter = fil;
336
        }
337

    
338
        public boolean accept(File f) {
339
                return f.isDirectory() || f.getName().toLowerCase().endsWith("." + filter);
340
        }
341

    
342
        public String getDescription() {
343
                return "." + filter;
344
        }
345
}