Statistics
| Revision:

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

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

    
84
  private Color[]                                                bandsColor = {
85
                  Color.red,
86
                  Color.green,
87
                  Color.blue,
88
                  Color.cyan,
89
                  Color.black,
90
                  Color.darkGray,
91
                  Color.gray,
92
                  Color.magenta,
93
                  Color.yellow,
94
                  Color.orange};
95

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
322
                        numBand++;
323
                }
324

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

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

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

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

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