Statistics
| Revision:

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

History | View | Annotate | Download (12.5 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.IHistogramable;
45
import org.gvsig.rastertools.histogram.ui.HistogramPanel;
46

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

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

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

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

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

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

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

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

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

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

    
270
        /**
271
         * Actualiza la grafica con los datos que ya teniamos del histograma.
272
         */
273
        private void updateGraphic() {
274
                long[][] auxHistogram = getLastHistogram().getHistogramByType(Histogram.getType(getHistogramPanel().getJComboBoxTipo().getSelectedIndex()));
275
                if (auxHistogram == null) return;
276

    
277
                int first = (int) getHistogramPanel().getBoxesValues()[1];
278
                int end = (int) getHistogramPanel().getBoxesValues()[0];
279

    
280
                int bandCount = 0;
281
                for (int i = 0; i < showBands.length; i++) {
282
                        if (showBands[i]) bandCount++;
283
                }
284

    
285
                int[][] newHistogram = new int[bandCount][end - first];
286
                String[] bandNames = new String[bandCount];
287
                
288
                bandCount = auxHistogram.length;
289

    
290
                int numBand = 0;
291
                for (int iBand = 0; iBand < auxHistogram.length; iBand++) {
292
                        if (!showBands[iBand]) continue;
293
                        
294
                        for (int j=first; j<end; j++)
295
                                newHistogram[numBand][j-first] = (int) auxHistogram[iBand][j];
296
                        bandNames[numBand] = (String) ((DefaultTableModel) getHistogramPanel().getJTableBands().getModel()).getValueAt(iBand, 1);
297

    
298
                        getHistogramPanel().getGraphicContainer().setBandColor(numBand, bandsColor[iBand % bandsColor.length]);
299

    
300
                        numBand++;
301
                }
302

    
303
                getHistogramPanel().getGraphicContainer().getPGraphic().setNewChart(newHistogram, bandNames);
304
                updateStatistic();
305
        }
306

    
307
        /**
308
         * Definir el nuevo histograma, metodo pu?blico para ser invocado desde
309
         * histogramProcess
310
         * @param histograma nuevo
311
         */
312
        public void setNewHistogram(Histogram value) {
313
                getHistogramPanel().panelInizialited = false;
314
                eventsEnabled = false;
315
                lastHistogram = value;
316
                refreshBands();
317
                updateGraphic();
318
                
319
                incrementableTask = null;
320
                histogramProcess = null;
321

    
322
                // Activo la ejecucion de los eventos porque seguro que ya tenemos un histograma
323
                eventsEnabled = true;
324
                getHistogramPanel().panelInizialited = true;
325
        }
326

    
327
        /**
328
         * Obtener ?ltimo histograma
329
         * @return Histogram
330
         */
331
        public Histogram getLastHistogram() {
332
                return lastHistogram;
333
        }
334

    
335
        /**
336
         * Eventos de los BoxValues
337
         */
338
        public void actionValueChanged(GraphicEvent e) {
339
                updateGraphic();
340
        }
341
        
342
        /**
343
         * Proceso para guardar una estadistica en un fichero.
344
         * @param path
345
         * @return
346
         * @throws IOException
347
         */
348
        private WritableByteChannel getWriteChannel(String path) throws IOException {
349
                WritableByteChannel channel;
350
                
351
                File f = new File(path);
352
                
353
                if (!f.exists()) {
354
                        System.out.println("Creando fichero " + f.getAbsolutePath());
355
                        
356
                        if (!f.createNewFile()) {
357
                                throw new IOException("Cannot create file " + f);
358
                        }
359
                }
360
                
361
                RandomAccessFile raf = new RandomAccessFile(f, "rw");
362
                channel = raf.getChannel();
363
                
364
                return channel;
365
        }
366

    
367
        public void propertyChange(PropertyChangeEvent evt) {
368
                if (!eventsEnabled) return;
369
                int countRow = ((DefaultTableModel) histogramPanel.getJTableBands().getModel()).getRowCount();
370
                for (int i=0; i<countRow; i++) {
371
                        showBands[i] = ((Boolean) ((DefaultTableModel) histogramPanel.getJTableBands().getModel()).getValueAt(i, 0)).booleanValue();
372
                }
373
                updateGraphic();
374
                updateStatistic();
375
        }
376
}