Statistics
| Revision:

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

History | View | Annotate | Download (12.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.io.File;
26
import java.io.IOException;
27
import java.io.RandomAccessFile;
28
import java.nio.channels.FileChannel;
29
import java.nio.channels.WritableByteChannel;
30
import java.util.ArrayList;
31

    
32
import javax.swing.JButton;
33
import javax.swing.JComboBox;
34
import javax.swing.JFileChooser;
35
import javax.swing.JOptionPane;
36

    
37
import org.gvsig.gui.beans.graphic.GraphicEvent;
38
import org.gvsig.gui.beans.graphic.GraphicListener;
39
import org.gvsig.gui.beans.incrementabletask.IncrementableTask;
40
import org.gvsig.raster.util.Histogram;
41
import org.gvsig.raster.util.IHistogramable;
42
import org.gvsig.rastertools.histogram.ui.HistogramPanel;
43

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

    
74
        public boolean                                                eventsEnabled = false;
75
        
76
        /**
77
         * Bandas que se est?n mostrando en el gr?fico. Se inicializa con las 3 bandas
78
         * RGB de la visualizaci?n. Este array puede tener m?s elementos ya que si las 
79
         * bandas no son de visualizaci?n (bandas de la imagen en disco) tendr? un elemento
80
         * por cada una. 
81
         */
82
        private boolean[]                                        showBands = null;
83
  private Color[]                                                bandsColor = {
84
                  Color.red,
85
                  Color.green,
86
                  Color.blue,
87
                  Color.cyan,
88
                  Color.black,
89
                  Color.darkGray,
90
                  Color.gray,
91
                  Color.magenta,
92
                  Color.yellow,
93
                  Color.orange,
94
                  Color.pink,
95
                  Color.lightGray};
96

    
97
        public HistogramPanelListener(HistogramPanel p){
98
                histogramPanel = p;
99
        }
100

    
101
        public void setControlListeners(){
102
                histogramPanel.getGraphicContainer().addValueChangedListener(this);
103
        }
104

    
105
        /**
106
         * Actualizar cuadro de estad?sticas
107
         */
108
        private void updateStatistic() {
109
                int first = (int) histogramPanel.getBoxesValues()[1];
110
                int end = (int) histogramPanel.getBoxesValues()[0];
111

    
112
                histogramPanel.setStatistic(getLastHistogram().getBasicStats((int) first, (int) end, showBands));
113
        }
114

    
115
        /**
116
         * Tratamiento de todos los eventos visuales.
117
         */
118
        public void actionPerformed(ActionEvent e) {
119
                if (!eventsEnabled) return;
120
                //--------------------------------------
121
                //Cambiar las bandas en el combo
122
                JComboBox cbb = histogramPanel.getJComboBands();
123
                if (e.getSource() == cbb) {
124
                        if (cbb.getSelectedItem() == null) return;
125
                        
126
                        if (cbb.getSelectedIndex() == 0)
127
                                for (int i = 0; i < showBands.length; i++)
128
                                        showBands[i] = true;
129
                        if (cbb.getSelectedItem().equals("R")) addOrRemoveGraphicBand(0);
130
                        if (cbb.getSelectedItem().equals("G")) addOrRemoveGraphicBand(1);
131
                        if (cbb.getSelectedItem().equals("B")) addOrRemoveGraphicBand(2);
132
                        for (int i = 0; i < showBands.length; i++)
133
                                if (cbb.getSelectedItem().equals("Band " + i))
134
                                        addOrRemoveGraphicBand(i);
135

    
136
                        updateGraphic();
137
                        updateStatistic();
138
                        return;
139
                }
140
                
141
                //--------------------------------------                
142
                //Limpiar
143
                if (e.getSource() == histogramPanel.getJButtonClear()) {
144
                        for (int i = 0; i < showBands.length; i++)
145
                                showBands[i] = false;
146
                        updateGraphic();
147
                        return;
148
                }
149
                
150
                //--------------------------------------
151
                //Selecci?n de fuente de datos del histograma
152
                JComboBox cbo = histogramPanel.getJComboBoxOrigen();
153
                if (e.getSource() == cbo) {
154
                        showHistogram();
155
                        return;
156
                }
157
                                
158
                //--------------------------------------
159
                //Selecci?n de histograma acumulado y no acumulado
160
                JComboBox cbt = histogramPanel.getJComboBoxTipo();
161
                if (e.getSource() == cbt) {
162
                        updateStatistic();
163
                        updateGraphic();
164
                        return;
165
                }
166
                
167
                //--------------------------------------
168
                // Boton Crear Tabla
169
                JButton table = histogramPanel.getBCreateTable();
170
                if (e.getSource() == table) {
171
                        try {
172
//                        -------Mostrar un fileChooser------------------
173
                                String fName;
174
                                JFileChooser chooser = new JFileChooser();
175
                                chooser.setDialogTitle(PluginServices.getText(this, "guardar_tabla"));
176
                            
177
                                int returnVal = chooser.showOpenDialog(histogramPanel);
178
                                if (returnVal == JFileChooser.APPROVE_OPTION) {
179
                                        fName = chooser.getSelectedFile().toString();
180
                                        if (!fName.endsWith(".dbf"))
181
                                                fName += ".dbf";
182
                             
183
                                        //-------------Crear el dbf----------------------
184
                            
185
                                        DbaseFileWriterNIO dbfWrite = null;
186
                                        DbaseFileHeaderNIO myHeader;
187
                                        Value[] record;
188
                                
189
                                        long histogram[][]= getLastHistogram().getHistogram();
190
                                        int numBands = histogram.length;
191
                                        int numRecors = histogram[0].length;
192
                                
193
                                        File file = new File(fName);
194
                                
195
                                        String names[] = new String[numBands+1];
196
                                        int types[] = new int [numBands+1];
197
                                        int lengths[] = new int [numBands+1];
198
                                
199
                                        names[0]="Value";
200
                                        types[0]=4;
201
                                        lengths[0]=15;
202
                                        for (int band = 0; band < numBands; band++){
203
                                                names[band+1]="Band"+band;
204
                                                types[band+1]=4;
205
                                                lengths[band+1]=15;
206
                                        }
207
                                
208
                                        myHeader = DbaseFileHeaderNIO.createDbaseHeader(names,types,lengths);
209
        
210
                                        myHeader.setNumRecords(numRecors);
211
                                        dbfWrite = new DbaseFileWriterNIO(myHeader, (FileChannel) getWriteChannel(file.getPath()));
212
                                        record = new Value[numBands+1];
213
        
214
                                        for (int j = 0; j < numRecors; j++) {
215
                                                record[0] = ValueFactory.createValue(j);
216
                                                for (int r = 0; r < numBands; r++) {
217
                                                        record[r+1] = ValueFactory.createValue(histogram[r][j]);
218
                                                }
219
        
220
                                                dbfWrite.write(record);
221
                                        }
222
        
223
                                        dbfWrite.close();
224
                            
225
                                        //------------A?adir el dbf al proyecto--------------
226
                                        ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
227
                                        String name = file.getName();
228
                                        LayerFactory.getDataSourceFactory().addFileDataSource("gdbms dbf driver", name, fName);
229
                                        DataSource dataSource;
230
                                        dataSource = LayerFactory.getDataSourceFactory().createRandomDataSource(name, DataSourceFactory.AUTOMATIC_OPENING);
231
                                        
232
                                        SelectableDataSource sds = new SelectableDataSource(dataSource);
233
                                        EditableAdapter auxea=new EditableAdapter();
234
                                        auxea.setOriginalDataSource(sds);
235
                                        ProjectTable projectTable = ProjectFactory.createTable(name, auxea);
236
                                        //ext.getProject().addTable(projectTable);
237
                                        ext.getProject().addDocument(projectTable);
238
                                        
239
                                        Table t = new Table();
240
                                        t.setModel(projectTable);
241
                                        //projectTable.setAndamiWindow(t);
242
                                        PluginServices.getMDIManager().addWindow(t);
243
                                }
244
                        } catch (IOException e1) {
245
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),histogramPanel.getName() + " " + PluginServices.getText(this,"table_not_create"));
246
                        } catch (DriverLoadException e1) {
247
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),histogramPanel.getName() + " " + PluginServices.getText(this,"table_not_create"));
248
                        } catch (NoSuchTableException e1) {
249
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),histogramPanel.getName() + " " + PluginServices.getText(this,"table_not_create"));
250
                        } catch (ReadDriverException e1) {
251
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),histogramPanel.getName() + " " + PluginServices.getText(this,"table_not_create"));
252
                        }
253
                }
254
        }
255

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

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

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

    
293
        /**
294
         * Actualiza la grafica con los datos que ya teniamos del histograma.
295
         */
296
        private void updateGraphic() {
297
                long[][] auxHistogram = getLastHistogram().getHistogramByType(Histogram.getType(histogramPanel.getJComboBoxTipo().getSelectedIndex()));
298
                if (auxHistogram == null) return;
299

    
300
                int first = (int) histogramPanel.getBoxesValues()[1];
301
                int end = (int) histogramPanel.getBoxesValues()[0];
302

    
303
                int bandCount = 0;
304
                for (int i = 0; i < showBands.length; i++) {
305
                        if (showBands[i]) bandCount++;
306
                }
307

    
308
                int[][] newHistogram = new int[bandCount][end - first];
309
                String[] bandNames = new String[bandCount];
310
                
311
                bandCount = auxHistogram.length;
312

    
313
                int numBand = 0;
314
                for (int iBand = 0; iBand < auxHistogram.length; iBand++) {
315
                        if (!showBands[iBand]) continue;
316
                        
317
                        for (int j=first; j<end; j++)
318
                                newHistogram[numBand][j-first] = (int) auxHistogram[iBand][j];
319
                        bandNames[numBand] = iBand + "";
320

    
321
                        histogramPanel.getGraphicContainer().setBandColor(numBand, bandsColor[iBand % bandsColor.length]);
322

    
323
                        numBand++;
324
                }
325

    
326
                histogramPanel.getGraphicContainer().getPGraphic().setNewChart(newHistogram, bandNames);
327
                updateStatistic();
328
        }
329

    
330
        /**
331
         * Definir el nuevo histograma, metodo pu?blico para ser invocado desde
332
         * histogramProcess
333
         * @param histograma nuevo
334
         */
335
        public void setNewHistogram(Histogram value) {
336
                histogramPanel.panelInizialited = false;
337
                eventsEnabled = false;
338
                lastHistogram = value;
339
                refreshBands();
340
                updateGraphic();
341
                
342
                incrementableTask = null;
343
                histogramProcess = null;
344

    
345
                // Activo la ejecucion de los eventos porque seguro que ya tenemos un histograma
346
                eventsEnabled = true;
347
                histogramPanel.panelInizialited = true;
348
        }
349

    
350
        /**
351
         * Obtener ?ltimo histograma
352
         * @return Histogram
353
         */
354
        public Histogram getLastHistogram() {
355
                return lastHistogram;
356
        }
357

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