Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRasterTools-SE / src / org / gvsig / rastertools / histogram / HistogramPanelListener.java @ 11228

History | View | Annotate | Download (13.7 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
*
3
* Copyright (C) 2005 IVER T.I. 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
package org.gvsig.rastertools.histogram;
20

    
21
import java.awt.Color;
22
import java.awt.Component;
23
import java.awt.event.ActionEvent;
24
import java.awt.event.ActionListener;
25
import java.beans.PropertyChangeEvent;
26
import java.beans.PropertyChangeListener;
27
import java.io.File;
28
import java.io.IOException;
29
import java.io.RandomAccessFile;
30
import java.nio.channels.FileChannel;
31
import java.nio.channels.WritableByteChannel;
32
import java.util.ArrayList;
33

    
34
import javax.swing.JButton;
35
import javax.swing.JComboBox;
36
import javax.swing.JFileChooser;
37
import javax.swing.JOptionPane;
38
import javax.swing.table.DefaultTableModel;
39

    
40
import org.gvsig.gui.beans.graphic.GraphicEvent;
41
import org.gvsig.gui.beans.graphic.GraphicListener;
42
import org.gvsig.gui.beans.incrementabletask.IncrementableTask;
43
import org.gvsig.raster.util.Histogram;
44
import org.gvsig.raster.util.HistogramClass;
45
import org.gvsig.raster.util.IHistogramable;
46
import org.gvsig.rastertools.histogram.ui.HistogramPanel;
47

    
48
import com.hardcode.driverManager.DriverLoadException;
49
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
50
import com.hardcode.gdbms.engine.data.DataSource;
51
import com.hardcode.gdbms.engine.data.DataSourceFactory;
52
import com.hardcode.gdbms.engine.data.NoSuchTableException;
53
import com.hardcode.gdbms.engine.values.Value;
54
import com.hardcode.gdbms.engine.values.ValueFactory;
55
import com.iver.andami.PluginServices;
56
import com.iver.cit.gvsig.ProjectExtension;
57
import com.iver.cit.gvsig.fmap.drivers.shp.DbaseFileHeaderNIO;
58
import com.iver.cit.gvsig.fmap.drivers.shp.DbaseFileWriterNIO;
59
import com.iver.cit.gvsig.fmap.edition.EditableAdapter;
60
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
61
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
62
import com.iver.cit.gvsig.project.ProjectFactory;
63
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
64
import com.iver.cit.gvsig.project.documents.table.gui.Table;
65
/**
66
 * Listener para eventos del panel de histograma
67
 *
68
 * @version 20/03/2007
69
 * @author Nacho Brodin (brodin_ign@gva.es)
70
 * @author Borja Sanchez Zamorano (borja.sanchez@iver.es)
71
 */
72
public class HistogramPanelListener implements GraphicListener, ActionListener, PropertyChangeListener {
73
        private HistogramPanel                histogramPanel = null;
74
        private IncrementableTask        incrementableTask = null;
75
        private HistogramProcess        histogramProcess = null;
76
        private Histogram                                        lastHistogram = null;
77

    
78
        public boolean                                                eventsEnabled = false;
79
        
80
        /**
81
         * Bandas que se est?n mostrando en el gr?fico. Se inicializa con las 3 bandas
82
         * RGB de la visualizaci?n. Este array puede tener m?s elementos ya que si las 
83
         * bandas no son de visualizaci?n (bandas de la imagen en disco) tendr? un elemento
84
         * por cada una. 
85
         */
86
        private boolean[]                                        showBands = null;
87

    
88
  private Color[]                                                bandsColor = {
89
                  Color.red,
90
                  Color.green,
91
                  Color.blue,
92
                  Color.cyan,
93
                  Color.black,
94
                  Color.darkGray,
95
                  Color.gray,
96
                  Color.magenta,
97
                  Color.yellow,
98
                  Color.orange};
99

    
100
        public HistogramPanelListener(HistogramPanel p){
101
                histogramPanel = p;
102
        }
103
        
104
        public HistogramPanel getHistogramPanel() {
105
                return histogramPanel;
106
        }
107
        
108
        public void setControlListeners(){
109
                getHistogramPanel().getGraphicContainer().addValueChangedListener(this);
110
        }
111

    
112
        /**
113
         * Actualizar cuadro de estad?sticas
114
         */
115
        private void updateStatistic() {
116
                int first = (int) getHistogramPanel().getBoxesValues()[1];
117
                int end = (int) getHistogramPanel().getBoxesValues()[0];
118

    
119
                getHistogramPanel().setStatistic(getLastHistogram().getBasicStats((int) first, (int) end, showBands));
120
        }
121

    
122
        /**
123
         * Tratamiento de todos los eventos visuales.
124
         */
125
        public void actionPerformed(ActionEvent e) {
126
                if (!eventsEnabled) return;
127
                
128
                if (e.getSource() == getHistogramPanel().getButtonClean()) {
129
                        getHistogramPanel().refreshBands();
130
                        for (int i = 0; i < showBands.length; i++)
131
                                showBands[i] = false;
132
                        updateStatistic();
133
                        updateGraphic();
134
                        return;
135
                }
136

    
137
                if (e.getSource() == getHistogramPanel().getButtonShowAll()) {
138
                        getHistogramPanel().refreshBands();
139
                        for (int i = 0; i < showBands.length; i++)
140
                                showBands[i] = true;
141
                        updateStatistic();
142
                        updateGraphic();
143
                        return;
144
                }
145

    
146
                //--------------------------------------
147
                //Selecci?n de fuente de datos del histograma
148
                JComboBox cbo = getHistogramPanel().getComboBoxSource();
149
                if (e.getSource() == cbo) {
150
                        showHistogram();
151
                        return;
152
                }
153
                                
154
                //--------------------------------------
155
                //Selecci?n de histograma acumulado y no acumulado
156
                JComboBox cbt = getHistogramPanel().getComboBoxType();
157
                if (e.getSource() == cbt) {
158
                        updateStatistic();
159
                        updateGraphic();
160
                        return;
161
                }
162
                
163
                //--------------------------------------
164
                // Boton Crear Tabla
165

    
166
                JButton table = getHistogramPanel().getBCreateTable();
167
                if (e.getSource() == table) {
168
                        try {
169
//                        -------Mostrar un fileChooser------------------
170
                                String fName;
171
                                JFileChooser chooser = new JFileChooser();
172
                                chooser.setDialogTitle(PluginServices.getText(this, "guardar_tabla"));
173
                            
174
                                int returnVal = chooser.showOpenDialog(getHistogramPanel());
175
                                if (returnVal == JFileChooser.APPROVE_OPTION) {
176
                                        fName = chooser.getSelectedFile().toString();
177
                                        if (!fName.endsWith(".dbf"))
178
                                                fName += ".dbf";
179
                             
180
                                        //-------------Crear el dbf----------------------
181
                            
182
                                        DbaseFileWriterNIO dbfWrite = null;
183
                                        DbaseFileHeaderNIO myHeader;
184
                                        Value[] record;
185
                                
186
                                        HistogramClass[][] histogram = getLastHistogram().getHistogram();
187
                                        int numBands = histogram.length;
188
                                        int numRecors = histogram[0].length;
189
                                
190
                                        File file = new File(fName);
191
                                
192
                                        String names[] = new String[numBands+1];
193
                                        int types[] = new int [numBands+1];
194
                                        int lengths[] = new int [numBands+1];
195
                                
196
                                        names[0]="Value";
197
                                        types[0]=4;
198
                                        lengths[0]=15;
199
                                        for (int band = 0; band < numBands; band++){
200
                                                names[band+1]="Band"+band;
201
                                                types[band+1]=4;
202
                                                lengths[band+1]=15;
203
                                        }
204
                                
205
                                        myHeader = DbaseFileHeaderNIO.createDbaseHeader(names,types,lengths);
206
        
207
                                        myHeader.setNumRecords(numRecors);
208
                                        dbfWrite = new DbaseFileWriterNIO(myHeader, (FileChannel) getWriteChannel(file.getPath()));
209
                                        record = new Value[numBands+1];
210
        
211
                                        for (int j = 0; j < numRecors; j++) {
212
                                                record[0] = ValueFactory.createValue(j);
213
                                                for (int r = 0; r < numBands; r++) {
214
                                                        record[r+1] = ValueFactory.createValue(histogram[r][j].getValue());
215
                                                }
216
        
217
                                                dbfWrite.write(record);
218
                                        }
219
        
220
                                        dbfWrite.close();
221
                            
222
                                        //------------A?adir el dbf al proyecto--------------
223
                                        ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
224
                                        String name = file.getName();
225
                                        LayerFactory.getDataSourceFactory().addFileDataSource("gdbms dbf driver", name, fName);
226
                                        DataSource dataSource;
227
                                        dataSource = LayerFactory.getDataSourceFactory().createRandomDataSource(name, DataSourceFactory.AUTOMATIC_OPENING);
228
                                        
229
                                        SelectableDataSource sds = new SelectableDataSource(dataSource);
230
                                        EditableAdapter auxea=new EditableAdapter();
231
                                        auxea.setOriginalDataSource(sds);
232
                                        ProjectTable projectTable = ProjectFactory.createTable(name, auxea);
233
                                        //ext.getProject().addTable(projectTable);
234
                                        ext.getProject().addDocument(projectTable);
235
                                        
236
                                        Table t = new Table();
237
                                        t.setModel(projectTable);
238
                                        //projectTable.setAndamiWindow(t);
239
                                        PluginServices.getMDIManager().addWindow(t);
240
                                }
241
                        } catch (IOException e1) {
242
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),getHistogramPanel().getName() + " " + PluginServices.getText(this,"table_not_create"));
243
                        } catch (DriverLoadException e1) {
244
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),getHistogramPanel().getName() + " " + PluginServices.getText(this,"table_not_create"));
245
                        } catch (NoSuchTableException e1) {
246
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),getHistogramPanel().getName() + " " + PluginServices.getText(this,"table_not_create"));
247
                        } catch (ReadDriverException e1) {
248
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),getHistogramPanel().getName() + " " + PluginServices.getText(this,"table_not_create"));
249
                        }
250
                }
251

    
252
        }
253

    
254
        /**
255
         * Actualizar la variable de las bandas visibles y su componente visual.
256
         */
257
        private void refreshBands() {
258
                getHistogramPanel().refreshBands();
259
                showBands = new boolean[getLastHistogram().getNumBands()];
260
                for (int i = 0; i < showBands.length; i++)
261
                        showBands[i] = true;
262
        }
263
        
264
        /**
265
         * Lanza los dos threads para procesar el histograma y visualizar la
266
         * ventana de incremento
267
         */
268
        public void showHistogram() {
269
                if (getHistogramPanel().getComboBoxSource().getSelectedIndex() < 0) return;
270

    
271
                IHistogramable iaux = (IHistogramable) ((ArrayList) getHistogramPanel().getComboSource().get(getHistogramPanel().getComboBoxSource().getSelectedIndex())).get(0);
272
                histogramProcess = new HistogramProcess(iaux, this);
273
                incrementableTask = new IncrementableTask(histogramProcess);
274
                histogramProcess.setIncrementableTask(incrementableTask);
275
                incrementableTask.showWindow();
276
                iaux.resetPercent();
277
                histogramProcess.start();
278
                incrementableTask.start();
279
        }
280

    
281
        /**
282
         * A?ade o elimina una banda de la visualizaci?n. Si la banda se est? visualizando
283
         * se elimina y si no entonces se muestra
284
         * @param band banda a visualizar o borrar del gr?fico
285
         */
286
        public void addOrRemoveGraphicBand(int band){
287
                if (band > showBands.length) return;
288
                showBands[band] = !showBands[band];
289
        }
290

    
291
        /**
292
         * Actualiza la grafica con los datos que ya teniamos del histograma.
293
         */
294
        private void updateGraphic() {
295
                if (getLastHistogram() == null) return;
296
                HistogramClass[][] histogramClass = getLastHistogram().getHistogramByType(Histogram.getType(getHistogramPanel().getComboBoxType().getSelectedIndex()));
297
                if (histogramClass == null) return;
298

    
299
                double[][][] datos = new double[histogramClass.length][histogramClass[0].length][2];
300
                for (int iBand=0; iBand < histogramClass.length; iBand++) {
301
                        for (int i=0; i<histogramClass[iBand].length; i++) {
302
                                datos[iBand][i][0] = histogramClass[iBand][i].getMin();
303
                                datos[iBand][i][1] = histogramClass[iBand][i].getValue();
304
                        }
305
                }
306

    
307
//                long[][] auxHistogram = getLastHistogram().getHistogramByType(Histogram.getType(getHistogramPanel().getJComboBoxTipo().getSelectedIndex()));
308
//                if (auxHistogram == null) return;
309

    
310
                int first = (int) getHistogramPanel().getBoxesValues()[1];
311
                int end = (int) getHistogramPanel().getBoxesValues()[0];
312

    
313
                int bandCount = 0;
314
                for (int i = 0; i < showBands.length; i++) {
315
                        if (showBands[i]) bandCount++;
316
                }
317

    
318
                double[][][] newHistogram = new double[bandCount][end - first][2];
319
                String[] bandNames = new String[bandCount];
320
                
321
                bandCount = datos.length;
322

    
323
                int numBand = 0;
324
                for (int iBand = 0; iBand < datos.length; iBand++) {
325
                        if (!showBands[iBand]) continue;
326
                        
327
                        for (int j=first; j<end; j++) {
328
                                newHistogram[numBand][j-first][0] = datos[iBand][j][0];
329
                                newHistogram[numBand][j-first][1] = datos[iBand][j][1];
330
                        }
331
                        bandNames[numBand] = (String) ((DefaultTableModel) getHistogramPanel().getJTableBands().getModel()).getValueAt(iBand, 1);
332

    
333
                        getHistogramPanel().getGraphicContainer().setBandColor(numBand, bandsColor[iBand % bandsColor.length]);
334

    
335
                        numBand++;
336
                }
337

    
338
                getHistogramPanel().getGraphicContainer().getPGraphic().setNewChart(newHistogram, bandNames);
339
                updateStatistic();
340
        }
341

    
342
        /**
343
         * Definir el nuevo histograma, metodo pu?blico para ser invocado desde
344
         * histogramProcess
345
         * @param histograma nuevo
346
         */
347
        public void setNewHistogram(Histogram value) {
348
                getHistogramPanel().panelInizialited = false;
349
                eventsEnabled = false;
350
                lastHistogram = value;
351
                refreshBands();
352
                updateGraphic();
353
                
354
                incrementableTask = null;
355
                histogramProcess = null;
356

    
357
                // Activo la ejecucion de los eventos porque seguro que ya tenemos un histograma
358
                eventsEnabled = true;
359
                getHistogramPanel().panelInizialited = true;
360
        }
361

    
362
        /**
363
         * Obtener ?ltimo histograma
364
         * @return Histogram
365
         */
366
        public Histogram getLastHistogram() {
367
                return lastHistogram;
368
        }
369

    
370
        /**
371
         * Eventos de los BoxValues
372
         */
373
        public void actionValueChanged(GraphicEvent e) {
374
                updateGraphic();
375
        }
376
        
377
        /**
378
         * Proceso para guardar una estadistica en un fichero.
379
         * @param path
380
         * @return
381
         * @throws IOException
382
         */
383
        private WritableByteChannel getWriteChannel(String path) throws IOException {
384
                WritableByteChannel channel;
385
                
386
                File f = new File(path);
387
                
388
                if (!f.exists()) {
389
                        System.out.println("Creando fichero " + f.getAbsolutePath());
390
                        
391
                        if (!f.createNewFile()) {
392
                                throw new IOException("Cannot create file " + f);
393
                        }
394
                }
395
                
396
                RandomAccessFile raf = new RandomAccessFile(f, "rw");
397
                channel = raf.getChannel();
398
                
399
                return channel;
400
        }
401

    
402
        public void propertyChange(PropertyChangeEvent evt) {
403
                if (!eventsEnabled) return;
404
                int countRow = ((DefaultTableModel) histogramPanel.getJTableBands().getModel()).getRowCount();
405
                for (int i=0; i<countRow; i++) {
406
                        showBands[i] = ((Boolean) ((DefaultTableModel) histogramPanel.getJTableBands().getModel()).getValueAt(i, 0)).booleanValue();
407
                }
408
                updateGraphic();
409
                updateStatistic();
410
        }
411
}