Statistics
| Revision:

root / trunk / extensions / extRasterTools-SE / src / org / gvsig / rastertools / histogram / HistogramPanelListener.java @ 11180

History | View | Annotate | Download (13.2 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
                //--------------------------------------
129
                //Selecci?n de fuente de datos del histograma
130
                JComboBox cbo = getHistogramPanel().getJComboBoxOrigen();
131
                if (e.getSource() == cbo) {
132
                        showHistogram();
133
                        return;
134
                }
135
                                
136
                //--------------------------------------
137
                //Selecci?n de histograma acumulado y no acumulado
138
                JComboBox cbt = getHistogramPanel().getJComboBoxTipo();
139
                if (e.getSource() == cbt) {
140
                        updateStatistic();
141
                        updateGraphic();
142
                        return;
143
                }
144
                
145
                //--------------------------------------
146
                // Boton Crear Tabla
147

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

    
234
        }
235

    
236
        /**
237
         * Actualizar la variable de las bandas visibles y su componente visual.
238
         */
239
        private void refreshBands() {
240
                getHistogramPanel().refreshBands();
241
                showBands = new boolean[getLastHistogram().getNumBands()];
242
                for (int i = 0; i < showBands.length; i++)
243
                        showBands[i] = true;
244
        }
245
        
246
        /**
247
         * Lanza los dos threads para procesar el histograma y visualizar la
248
         * ventana de incremento
249
         */
250
        public void showHistogram() {
251
                if (getHistogramPanel().getJComboBoxOrigen().getSelectedIndex() < 0) return;
252

    
253
                IHistogramable iaux = (IHistogramable) ((ArrayList) getHistogramPanel().getComboSource().get(getHistogramPanel().getJComboBoxOrigen().getSelectedIndex())).get(0);
254
                histogramProcess = new HistogramProcess(iaux, this);
255
                incrementableTask = new IncrementableTask(histogramProcess);
256
                histogramProcess.setIncrementableTask(incrementableTask);
257
                incrementableTask.showWindow();
258
                iaux.resetPercent();
259
                histogramProcess.start();
260
                incrementableTask.start();
261
        }
262

    
263
        /**
264
         * A?ade o elimina una banda de la visualizaci?n. Si la banda se est? visualizando
265
         * se elimina y si no entonces se muestra
266
         * @param band banda a visualizar o borrar del gr?fico
267
         */
268
        public void addOrRemoveGraphicBand(int band){
269
                if (band > showBands.length) return;
270
                showBands[band] = !showBands[band];
271
        }
272

    
273
        /**
274
         * Actualiza la grafica con los datos que ya teniamos del histograma.
275
         */
276
        private void updateGraphic() {
277
                HistogramClass[][] histogramClass = getLastHistogram().getHistogramByType(Histogram.getType(getHistogramPanel().getJComboBoxTipo().getSelectedIndex()));
278
                if (histogramClass == null) return;
279

    
280
                double[][][] datos = new double[histogramClass.length][histogramClass[0].length][2];
281
                for (int iBand=0; iBand < histogramClass.length; iBand++) {
282
                        for (int i=0; i<histogramClass[iBand].length; i++) {
283
                                datos[iBand][i][0] = histogramClass[iBand][i].getMin();
284
                                datos[iBand][i][1] = histogramClass[iBand][i].getValue();
285
                        }
286
                }
287

    
288
//                long[][] auxHistogram = getLastHistogram().getHistogramByType(Histogram.getType(getHistogramPanel().getJComboBoxTipo().getSelectedIndex()));
289
//                if (auxHistogram == null) return;
290

    
291
                int first = (int) getHistogramPanel().getBoxesValues()[1];
292
                int end = (int) getHistogramPanel().getBoxesValues()[0];
293

    
294
                int bandCount = 0;
295
                for (int i = 0; i < showBands.length; i++) {
296
                        if (showBands[i]) bandCount++;
297
                }
298

    
299
                double[][][] newHistogram = new double[bandCount][end - first][2];
300
                String[] bandNames = new String[bandCount];
301
                
302
                bandCount = datos.length;
303

    
304
                int numBand = 0;
305
                for (int iBand = 0; iBand < datos.length; iBand++) {
306
                        if (!showBands[iBand]) continue;
307
                        
308
                        for (int j=first; j<end; j++) {
309
                                newHistogram[numBand][j-first][0] = datos[iBand][j][0];
310
                                newHistogram[numBand][j-first][1] = datos[iBand][j][1];
311
                        }
312
                        bandNames[numBand] = (String) ((DefaultTableModel) getHistogramPanel().getJTableBands().getModel()).getValueAt(iBand, 1);
313

    
314
                        getHistogramPanel().getGraphicContainer().setBandColor(numBand, bandsColor[iBand % bandsColor.length]);
315

    
316
                        numBand++;
317
                }
318

    
319
                getHistogramPanel().getGraphicContainer().getPGraphic().setNewChart(newHistogram, bandNames);
320
                updateStatistic();
321
        }
322

    
323
        /**
324
         * Definir el nuevo histograma, metodo pu?blico para ser invocado desde
325
         * histogramProcess
326
         * @param histograma nuevo
327
         */
328
        public void setNewHistogram(Histogram value) {
329
                getHistogramPanel().panelInizialited = false;
330
                eventsEnabled = false;
331
                lastHistogram = value;
332
                refreshBands();
333
                updateGraphic();
334
                
335
                incrementableTask = null;
336
                histogramProcess = null;
337

    
338
                // Activo la ejecucion de los eventos porque seguro que ya tenemos un histograma
339
                eventsEnabled = true;
340
                getHistogramPanel().panelInizialited = true;
341
        }
342

    
343
        /**
344
         * Obtener ?ltimo histograma
345
         * @return Histogram
346
         */
347
        public Histogram getLastHistogram() {
348
                return lastHistogram;
349
        }
350

    
351
        /**
352
         * Eventos de los BoxValues
353
         */
354
        public void actionValueChanged(GraphicEvent e) {
355
                updateGraphic();
356
        }
357
        
358
        /**
359
         * Proceso para guardar una estadistica en un fichero.
360
         * @param path
361
         * @return
362
         * @throws IOException
363
         */
364
        private WritableByteChannel getWriteChannel(String path) throws IOException {
365
                WritableByteChannel channel;
366
                
367
                File f = new File(path);
368
                
369
                if (!f.exists()) {
370
                        System.out.println("Creando fichero " + f.getAbsolutePath());
371
                        
372
                        if (!f.createNewFile()) {
373
                                throw new IOException("Cannot create file " + f);
374
                        }
375
                }
376
                
377
                RandomAccessFile raf = new RandomAccessFile(f, "rw");
378
                channel = raf.getChannel();
379
                
380
                return channel;
381
        }
382

    
383
        public void propertyChange(PropertyChangeEvent evt) {
384
                if (!eventsEnabled) return;
385
                int countRow = ((DefaultTableModel) histogramPanel.getJTableBands().getModel()).getRowCount();
386
                for (int i=0; i<countRow; i++) {
387
                        showBands[i] = ((Boolean) ((DefaultTableModel) histogramPanel.getJTableBands().getModel()).getValueAt(i, 0)).booleanValue();
388
                }
389
                updateGraphic();
390
                updateStatistic();
391
        }
392
}