Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRemoteSensing / src / org / gvsig / remotesensing / decisiontrees / gui / listener / DecisionTreePanelListener.java @ 18578

History | View | Annotate | Download (15.8 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 Iba?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
package org.gvsig.remotesensing.decisiontrees.gui.listener;
41

    
42
import java.awt.Color;
43
import java.awt.event.ActionEvent;
44
import java.awt.event.ActionListener;
45
import java.awt.event.MouseEvent;
46
import java.awt.event.MouseListener;
47
import java.io.File;
48
import java.util.ArrayList;
49
import java.util.HashMap;
50
import java.util.Iterator;
51

    
52
import javax.swing.JFileChooser;
53

    
54
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
55
import org.gvsig.gui.beans.buttonspanel.ButtonsPanel;
56
import org.gvsig.gui.beans.buttonspanel.ButtonsPanelEvent;
57
import org.gvsig.gui.beans.buttonspanel.ButtonsPanelListener;
58
import org.gvsig.raster.IProcessActions;
59
import org.gvsig.raster.RasterProcess;
60
import org.gvsig.raster.buffer.BufferFactory;
61
import org.gvsig.raster.buffer.RasterBuffer;
62
import org.gvsig.raster.dataset.GeoRasterWriter;
63
import org.gvsig.raster.dataset.InvalidSetViewException;
64
import org.gvsig.raster.dataset.io.RasterDriverException;
65
import org.gvsig.raster.datastruct.ColorItem;
66
import org.gvsig.raster.grid.filter.FilterTypeException;
67
import org.gvsig.raster.util.RasterNotLoadException;
68
import org.gvsig.raster.util.RasterToolsUtil;
69

    
70
import org.gvsig.remotesensing.RemoteSensingUtils;
71
import org.gvsig.remotesensing.decisiontrees.CopyOfDecisionTreeProcess;
72
import org.gvsig.remotesensing.decisiontrees.DecisionTreeNode;
73
import org.gvsig.remotesensing.decisiontrees.gui.ClassEditorDialog;
74
import org.gvsig.remotesensing.decisiontrees.gui.DecisionTreePanel;
75
import org.gvsig.remotesensing.decisiontrees.gui.ExpressionEditorDialog;
76
import org.gvsig.remotesensing.gui.beans.OptionsPanel;
77
import org.jgraph.graph.DefaultGraphCell;
78

    
79
import com.iver.andami.PluginServices;
80
import com.iver.andami.Utilities;
81
import com.iver.cit.gvsig.addlayer.fileopen.FileOpenWizard;
82
import com.iver.cit.gvsig.fmap.layers.FLayer;
83
import com.iver.cit.gvsig.fmap.layers.FLayers;
84

    
85
/**
86
 * Listener del panel de ?rboles de decisi?n.
87
 * 
88
 * @author Diego Guerrero Sevilla (diego.guerrero@uclm.es)
89
 *
90
 */
91
public class DecisionTreePanelListener implements ButtonsPanelListener, ActionListener, MouseListener, IProcessActions {
92
        
93
        DecisionTreePanel decisionTreePanel = null;
94

    
95
        public DecisionTreePanelListener(DecisionTreePanel decisionTreePanel) {
96
                this.decisionTreePanel = decisionTreePanel;
97
        }
98

    
99
        public void actionPerformed(ActionEvent e) {
100
                if (e.getSource()==decisionTreePanel.getAddMenuItem()){
101
                        DefaultGraphCell cell = decisionTreePanel.getSelectedCell();
102
                        DecisionTreeNode node = (DecisionTreeNode)cell.getUserObject();
103
                        int classId = node.getClassID();
104
                        node.addChildren();
105
                        node.getLeftChild().setClassID(classId);
106
                        node.getRightChild().setClassID(decisionTreePanel.generateClassId());
107
                        decisionTreePanel.reloadGraph();
108
                }
109
                
110
                else if (e.getSource()==decisionTreePanel.getDeleteMenuItem()){
111
                        DefaultGraphCell cell = decisionTreePanel.getSelectedCell();
112
                        DecisionTreeNode node = (DecisionTreeNode)cell.getUserObject();
113
                        if(cell!=decisionTreePanel.getJGraph().getRoots()[0]){
114
                                node.deleteChildren();
115
                                decisionTreePanel.cleanClassColors();
116
                                node.setClassID(decisionTreePanel.generateClassId());
117
                                decisionTreePanel.reloadGraph();
118
                        }
119
                }
120
                
121
                else if (e.getSource()==decisionTreePanel.getExecuteMenuItem()){
122
                        DefaultGraphCell cell = decisionTreePanel.getSelectedCell();
123
                        DecisionTreeNode node = (DecisionTreeNode)cell.getUserObject();
124
                        executeTree(node);
125
                }
126
        }
127

    
128
        public void actionButtonPressed(ButtonsPanelEvent e) {
129
//                 Al pulsar Aceptar o Aplicar se ejecuta el aceptar del panel
130
                if (e.getButton() == ButtonsPanel.BUTTON_APPLY) {
131
                        executeTree(decisionTreePanel.getRoot());
132
                }
133

    
134
                // Al pulsar Cancelar la ventana se cierra y se refresca la vista
135
                if (e.getButton() == ButtonsPanel.BUTTON_CLOSE) {
136
                        close();
137
                }
138
        }
139
        
140
        private void close() {
141
                try {
142
                        PluginServices.getMDIManager().closeWindow(decisionTreePanel.getDecisionTreeDialog());
143
                } catch (ArrayIndexOutOfBoundsException e) {
144
                        //Si la ventana no se puede eliminar no hacemos nada
145
                }
146
                
147
        }
148

    
149
        public void mouseClicked(MouseEvent e) {
150
                // TODO Auto-generated method stub
151

    
152
        }
153

    
154
        public void mouseEntered(MouseEvent e) {
155
                // TODO Auto-generated method stub
156

    
157
        }
158

    
159
        public void mouseExited(MouseEvent e) {
160
                // TODO Auto-generated method stub
161

    
162
        }
163

    
164
        public void mousePressed(MouseEvent e) {
165
                if (e.getButton() ==  MouseEvent.BUTTON3){
166
                        showPopupMenu(e);
167
                }
168
                if (e.getClickCount() == 2) {
169
                        editCell(e);
170
                }
171
        }
172

    
173
        public void mouseReleased(MouseEvent e) {
174
                // TODO Auto-generated method stub
175

    
176
        }
177

    
178
        private void editCell(MouseEvent e) {
179
                int x = e.getX();
180
                int y = e.getY();
181
                DefaultGraphCell cell = (DefaultGraphCell) decisionTreePanel.getJGraph().getFirstCellForLocation(x, y);
182
                if (cell!=null){
183
                        decisionTreePanel.setSelectedCell(cell);
184
                        Object userObject = cell.getUserObject();
185
                        if(userObject instanceof DecisionTreeNode){
186
                                DecisionTreeNode node = (DecisionTreeNode)userObject;
187
                                
188
                                if(!node.isFinal()){
189
                                        ExpressionEditorDialog expressionEditorDialog = new ExpressionEditorDialog(600,250,decisionTreePanel);
190
                                        expressionEditorDialog.getExpressionEditorPanel().getCalculatorPanel().setPersistentVarTable(decisionTreePanel.getVarTable());
191
                                        PluginServices.getMDIManager().addWindow(expressionEditorDialog);
192
                                }
193
                                else{
194
                                        ClassEditorDialog classEditorDialog = new ClassEditorDialog(250,100,decisionTreePanel);
195
                                        PluginServices.getMDIManager().addWindow(classEditorDialog);
196
                                }
197
                                decisionTreePanel.reloadGraph();
198
                        }
199
                }
200
        }
201
        
202
        private void showPopupMenu(MouseEvent e) {
203
                int x = e.getX();
204
                int y = e.getY();
205
                DefaultGraphCell cell = (DefaultGraphCell) decisionTreePanel.getJGraph().getFirstCellForLocation(x, y);
206
                if (cell != null){
207
                        if(cell.getUserObject() instanceof DecisionTreeNode){
208
                                decisionTreePanel.getDeleteMenuItem().setVisible(true);
209
                                decisionTreePanel.getAddMenuItem().setVisible(true);
210
                                decisionTreePanel.getExecuteMenuItem().setVisible(true);
211
                                if(cell == decisionTreePanel.getJGraph().getRoots()[0])
212
                                        decisionTreePanel.getDeleteMenuItem().setVisible(false);
213
                                if(!((DecisionTreeNode)cell.getUserObject()).isFinal())
214
                                        decisionTreePanel.getAddMenuItem().setVisible(false);
215
                                else{
216
                                        decisionTreePanel.getDeleteMenuItem().setVisible(false);
217
                                        decisionTreePanel.getExecuteMenuItem().setVisible(false);
218
                                }
219
                                decisionTreePanel.setSelectedCell(cell);
220
                                decisionTreePanel.getJPopupMenu().show(e.getComponent(),  x, y);
221
                        }
222
                }
223
        }
224
        
225
        /**
226
         * Ejecuta el ?rbol desde el nodo indicado.
227
         * 
228
         * @param root Nodo que se considera raiz en la ejecuci?n de ?rbol.
229
         */
230
        private void executeTree(DecisionTreeNode root){
231
                //Comprobar que todas laa variables est?n asignadas:
232
                boolean allVarsAsigned = true;
233
                for (Iterator iter = decisionTreePanel.getVarTable().keySet().iterator(); iter.hasNext();) {
234
                        String varName = (String) iter.next();
235
                        String layerName = (String) decisionTreePanel.getVarTable().get(varName); 
236
                        if (layerName==null || layerName.equals("")){
237
                                allVarsAsigned = false;
238
                                break;
239
                        }
240
                }
241
                
242
                if (allVarsAsigned){
243
                        if (!root.hasError()){
244
                                
245
                                int nBand;
246
                                String layerBand;
247
                                String layerName;
248
                                FLyrRasterSE rasterLayer;
249
                                
250
                                String path = getFileSelected();
251
                                if (path == null)
252
                                        return;                
253
                                FLayers layers = decisionTreePanel.getView().getModel().getMapContext().getLayers();
254
                                // Extent de salida personalizado.
255
                                OptionsPanel outputOptionsPanel = decisionTreePanel.getOutputOptionsPanel();
256
                                if (outputOptionsPanel.getRButtom2().isSelected()){
257
                                        try{
258
                                                outputOptionsPanel.getOutputExtent().setXRange(Double.parseDouble(outputOptionsPanel.getJTextRangoX1().getText()),Double.parseDouble(outputOptionsPanel.getJTextRangoX2().getText()));
259
                                                outputOptionsPanel.getOutputExtent().setYRange(Double.parseDouble(outputOptionsPanel.getJTextRangoY1().getText()), Double.parseDouble(outputOptionsPanel.getJTextRangoY2().getText()));
260
                                                outputOptionsPanel.getOutputExtent().setCellSize(Double.parseDouble(outputOptionsPanel.getJTextCellSize().getText()));
261
                                        }catch (NumberFormatException  e) {
262
                                                RasterToolsUtil.messageBoxError(PluginServices.getText(this, "invalid_number"), this);
263
                                                return;
264
                                        }
265
                                }
266
                                //        Extent de salida a partir de una capa.
267
                                else if(outputOptionsPanel.getRButtom4().isSelected()){
268
                                        try {
269
                                                FLayer layer = layers.getLayer(outputOptionsPanel.getJComboCapas().getSelectedIndex());        
270
                                                outputOptionsPanel.getOutputExtent().setXRange(layer.getFullExtent().getMinX(),
271
                                                                layer.getFullExtent().getMaxX());
272
                                                outputOptionsPanel.getOutputExtent().setYRange(layer.getFullExtent().getMinY(),
273
                                                                layer.getFullExtent().getMaxY());
274
                                                outputOptionsPanel.getOutputExtent().setCellSize(Double.parseDouble(outputOptionsPanel.getJTextCellSize().getText()));                
275
                                                outputOptionsPanel.extentHasChanged();
276
                                        } catch (Exception ex) {
277
                                                ex.printStackTrace();
278
                                        }
279
                                }
280
                                
281
                                // Crear un HashMap con los rasterbuffers de entrada indexados por el nombre de variable.
282
                                RasterBuffer valor=null;
283
                                HashMap buffers = new HashMap();
284
                                for (Iterator iter = decisionTreePanel.getVarTable().keySet().iterator(); iter.hasNext();) {
285
                                        String varName = (String) iter.next();
286
                                        
287
                                        layerBand =  (String)decisionTreePanel.getVarTable().get(varName);
288
                                        layerName = layerBand.substring(0,layerBand.indexOf("["));
289
                                        nBand = Integer.valueOf(layerBand.substring(layerBand.lastIndexOf("Band")+4,layerBand.lastIndexOf("]"))).intValue();
290
                                        rasterLayer = (FLyrRasterSE)layers.getLayer(layerName);                
291
                                        BufferFactory bufferFactory= rasterLayer.getBufferFactory();
292
                                        
293
                                        double minX=0,minY=0,maxX=0,maxY=0;
294
                                        minX= outputOptionsPanel.getOutputExtent().getMin().getX();
295
                                        minY= outputOptionsPanel.getOutputExtent().getMin().getY();
296
                                        maxX= outputOptionsPanel.getOutputExtent().getMax().getX();
297
                                        maxY =outputOptionsPanel.getOutputExtent().getMax().getY();
298
                                        
299
                                        try {
300
                                                        bufferFactory.setAdjustToExtent(false);
301
                                                        bufferFactory.setDrawableBands(new int[]{nBand-1});
302
                                                        bufferFactory.setAreaOfInterest(minX,minY,maxX,maxY,outputOptionsPanel.getOutputExtent().getNX(),
303
                                                                        outputOptionsPanel.getOutputExtent().getNY());
304
                                                        valor=(RasterBuffer) bufferFactory.getRasterBuf();
305
                                                
306
                                        } catch (ArrayIndexOutOfBoundsException e) {
307
                                                RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e);
308
                                        } catch (InvalidSetViewException e) {
309
                                                        e.printStackTrace();
310
                                        } catch (InterruptedException e) {
311
                                                Thread.currentThread().interrupt();
312
                                        } catch (RasterDriverException e) {
313
                                                e.printStackTrace();
314
                                        }
315
                                
316
                                        buffers.put(varName,new Object[]{valor,new Integer(valor.getDataType())});
317
                                }        
318
                                //Ejecutar el proceso:
319
                                /*
320
                                String viewName = PluginServices.getMDIManager().getWindowInfo(decisionTreePanel.getView()).getTitle();
321
                                DecisionTreeProcess decisionTreeProcess = new DecisionTreeProcess(root, buffers, outputOptionsPanel.getOutputExtent(),
322
                                                viewName, path);
323
                                IncrementableTask incrementableTask = new IncrementableTask(decisionTreeProcess);
324
                                decisionTreeProcess.setIncrementableTask(incrementableTask);
325
                                incrementableTask.showWindow();
326
                                decisionTreeProcess.start();
327
                                incrementableTask.start();
328
                                */        
329
                                
330
                                //*********************************
331
                                String viewName = PluginServices.getMDIManager().getWindowInfo(decisionTreePanel.getView()).getTitle();
332
                                
333
                                RasterProcess decisionTreeProcess = new CopyOfDecisionTreeProcess();
334
                                decisionTreeProcess.setActions(this);
335
                                decisionTreeProcess.addParam("tree", root);
336
                                decisionTreeProcess.addParam("varsTable", buffers);
337
                                decisionTreeProcess.addParam("viewName", viewName);
338
                                decisionTreeProcess.addParam("filename", path);
339
                                decisionTreeProcess.addParam("resultExtent", outputOptionsPanel.getOutputExtent());
340
                                
341
                                decisionTreeProcess.start();
342
                        }
343
                }
344
                
345
                //TODO: Actualizar el nombre de capa del panel de opciones.
346
        }
347
        /**
348
         * @return string con el path del fichero de salida
349
         */
350
        public String getFileSelected() {
351
                String path = "";
352
                if (decisionTreePanel.getOutputOptionsPanel().getRadioFile().isSelected()) {
353
                        JFileChooser chooser = new JFileChooser(FileOpenWizard.getLastPath());
354
                        chooser.setDialogTitle(PluginServices.getText(this, "seleccionar_fichero"));
355

    
356
                        //A?adimos las extensiones que hayan sido registradas en el driver
357
                        String[] extList = GeoRasterWriter.getDriversExtensions();
358
                        for(int i=0;i<extList.length;i++)
359
                                chooser.addChoosableFileFilter(new WriterFilter(extList[i]));
360

    
361
                        if (chooser.showOpenDialog(decisionTreePanel) != JFileChooser.APPROVE_OPTION)
362
                                return null;
363

    
364
                        String fName = chooser.getSelectedFile().toString();
365
                        String ext = ((WriterFilter)chooser.getFileFilter()).getDescription();
366

    
367
                        ext = ext.toLowerCase().substring(ext.lastIndexOf(".") + 1, ext.length());
368

    
369
                        if ((fName != null) && !fName.equals(""))
370
                                if (!fName.endsWith("." + ext))
371
                                        fName = fName + "." + ext;
372

    
373
                        FileOpenWizard.setLastPath(chooser.getSelectedFile().getPath().substring(0, chooser.getSelectedFile().getPath().lastIndexOf(File.separator)));
374
                        path = fName;
375
                } else {
376
                        path = Utilities.createTempDirectory() + File.separator + decisionTreePanel.getOutputOptionsPanel().getJTextNombreCapa().getText() + ".tif";
377
                        decisionTreePanel.getOutputOptionsPanel().updateNewLayerText();
378
                }
379
                return path;
380
        }
381

    
382
        public void end(Object fileName) {
383
                String viewName = PluginServices.getMDIManager().getWindowInfo(decisionTreePanel.getView()).getTitle();
384
                try {
385
                        FLayer lyr = RasterToolsUtil.loadLayer(viewName,(String)fileName,null);
386
                        /*
387
                         * Asignar la leyenda a la nueva capa:
388
                         */
389
                        ArrayList colorItems = new ArrayList();
390
                        ColorItem colorItem = null;
391
                        HashMap classColors = decisionTreePanel.getClassColors();
392
                        for (Iterator iter = classColors.keySet().iterator(); iter.hasNext();) {
393
                                Integer classId = (Integer) iter.next();
394
                                colorItem = new ColorItem();
395
                                colorItem.setColor((Color)classColors.get(classId));
396
                                colorItem.setNameClass("Class "+classId.toString());
397
                                colorItem.setValue(classId.intValue());
398
                                colorItems.add(colorItem);
399
                        }
400
                        
401
                        RemoteSensingUtils.setLeyend(lyr, colorItems);
402
                        
403
                } catch (RasterNotLoadException e) {
404
                        RasterToolsUtil.messageBoxError("error_load_layer", this, e);
405
                } catch (FilterTypeException e) {
406
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_adding_leyend"), this, e);
407
                }
408
        }
409
        
410
        
411
        public void interrupted() {
412
        }
413
}
414

    
415
/**
416
 * @author Nacho Brodin <brodin_ign@gva.es>
417
 * Filtro para el selector de formatos de escritura
418
 */
419
class WriterFilter extends javax.swing.filechooser.FileFilter {
420
        private String                                filter;
421

    
422
        public WriterFilter(String fil) {
423
                this.filter = fil;
424
        }
425

    
426
        public boolean accept(File f) {
427
                return f.isDirectory() || f.getName().toLowerCase().endsWith("." + filter);
428
        }
429

    
430
        public String getDescription() {
431
                return "." + filter;
432
        }
433
}