Statistics
| Revision:

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

History | View | Annotate | Download (14.3 KB)

1 10950 bsanchez
/* 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 11033 bsanchez
import java.awt.Color;
22 11180 bsanchez
import java.awt.Component;
23 10950 bsanchez
import java.awt.event.ActionEvent;
24
import java.awt.event.ActionListener;
25 11116 bsanchez
import java.beans.PropertyChangeEvent;
26
import java.beans.PropertyChangeListener;
27 11033 bsanchez
import java.io.File;
28
import java.io.IOException;
29
import java.io.RandomAccessFile;
30 11180 bsanchez
import java.nio.channels.FileChannel;
31 11033 bsanchez
import java.nio.channels.WritableByteChannel;
32 10963 bsanchez
import java.util.ArrayList;
33 10950 bsanchez
34 11180 bsanchez
import javax.swing.JButton;
35 10950 bsanchez
import javax.swing.JComboBox;
36 11180 bsanchez
import javax.swing.JFileChooser;
37
import javax.swing.JOptionPane;
38 11116 bsanchez
import javax.swing.table.DefaultTableModel;
39 10950 bsanchez
40 11004 bsanchez
import org.gvsig.gui.beans.graphic.GraphicEvent;
41
import org.gvsig.gui.beans.graphic.GraphicListener;
42 10950 bsanchez
import org.gvsig.gui.beans.incrementabletask.IncrementableTask;
43 12383 nacho
import org.gvsig.raster.datastruct.Histogram;
44
import org.gvsig.raster.datastruct.HistogramClass;
45
import org.gvsig.raster.datastruct.HistogramException;
46
import org.gvsig.raster.hierarchy.IHistogramable;
47 13622 bsanchez
import org.gvsig.raster.util.RasterToolsUtil;
48 10950 bsanchez
import org.gvsig.rastertools.histogram.ui.HistogramPanel;
49 11180 bsanchez
50
import com.hardcode.driverManager.DriverLoadException;
51
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
52
import com.hardcode.gdbms.engine.data.DataSource;
53
import com.hardcode.gdbms.engine.data.DataSourceFactory;
54
import com.hardcode.gdbms.engine.data.NoSuchTableException;
55
import com.hardcode.gdbms.engine.values.Value;
56
import com.hardcode.gdbms.engine.values.ValueFactory;
57
import com.iver.andami.PluginServices;
58 12502 nacho
import com.iver.andami.messages.NotificationManager;
59 11180 bsanchez
import com.iver.cit.gvsig.ProjectExtension;
60
import com.iver.cit.gvsig.fmap.drivers.shp.DbaseFileHeaderNIO;
61
import com.iver.cit.gvsig.fmap.drivers.shp.DbaseFileWriterNIO;
62
import com.iver.cit.gvsig.fmap.edition.EditableAdapter;
63
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
64
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
65
import com.iver.cit.gvsig.project.ProjectFactory;
66
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
67
import com.iver.cit.gvsig.project.documents.table.gui.Table;
68 10950 bsanchez
/**
69
 * Listener para eventos del panel de histograma
70
 *
71
 * @version 20/03/2007
72
 * @author Nacho Brodin (brodin_ign@gva.es)
73 12369 bsanchez
 * @author BorSanZa - Borja Sanchez Zamorano (borja.sanchez@iver.es)
74 10950 bsanchez
 */
75 11116 bsanchez
public class HistogramPanelListener implements GraphicListener, ActionListener, PropertyChangeListener {
76 13646 bsanchez
        private HistogramPanel histogramPanel = null;
77
        private Histogram      lastHistogram  = null;
78 10950 bsanchez
79 13646 bsanchez
        public boolean         eventsEnabled  = false;
80 12369 bsanchez
81 11042 bsanchez
        /**
82 13646 bsanchez
   * Bandas que se est?n mostrando en el gr?fico. Se inicializa con las 3 bandas
83
   * RGB de la visualizaci?n. Este array puede tener m?s elementos ya que si las
84
   * bandas no son de visualizaci?n (bandas de la imagen en disco) tendr? un
85
   * elemento por cada una.
86
   */
87
        private boolean[]      showBands      = null;
88 11070 bsanchez
89 12369 bsanchez
        private Color[]                                                bandsColor = {
90
                        Color.red,
91
                        Color.green,
92
                        Color.blue,
93
                        Color.cyan,
94
                        Color.black,
95
                        Color.darkGray,
96
                        Color.gray,
97
                        Color.magenta,
98
                        Color.yellow,
99
                        Color.orange};
100 11068 bsanchez
101 10950 bsanchez
        public HistogramPanelListener(HistogramPanel p){
102 10981 bsanchez
                histogramPanel = p;
103 10950 bsanchez
        }
104 12369 bsanchez
105 11116 bsanchez
        public HistogramPanel getHistogramPanel() {
106
                return histogramPanel;
107
        }
108 12369 bsanchez
109 10950 bsanchez
        public void setControlListeners(){
110 11116 bsanchez
                getHistogramPanel().getGraphicContainer().addValueChangedListener(this);
111 10950 bsanchez
        }
112 11068 bsanchez
113
        /**
114
         * Actualizar cuadro de estad?sticas
115
         */
116 10950 bsanchez
        private void updateStatistic() {
117 13646 bsanchez
                double first = getHistogramPanel().getGraphicContainer().getX1();
118
                double end = getHistogramPanel().getGraphicContainer().getX2();
119 11033 bsanchez
120 13646 bsanchez
                getHistogramPanel().setStatistic(getLastHistogram().getBasicStats(first, end, showBands));
121 10950 bsanchez
        }
122
123 11068 bsanchez
        /**
124
         * Tratamiento de todos los eventos visuales.
125
         */
126 10950 bsanchez
        public void actionPerformed(ActionEvent e) {
127 11042 bsanchez
                if (!eventsEnabled) return;
128 12369 bsanchez
129 11444 bsanchez
                // Boton de desmarcar todas las bandas
130 11228 bsanchez
                if (e.getSource() == getHistogramPanel().getButtonClean()) {
131 11441 bsanchez
                        getHistogramPanel().refreshBands(false);
132 11202 bsanchez
                        for (int i = 0; i < showBands.length; i++)
133
                                showBands[i] = false;
134
                        updateStatistic();
135
                        updateGraphic();
136
                        return;
137
                }
138
139 11444 bsanchez
                // Boton de marcar todas las bandas
140 11228 bsanchez
                if (e.getSource() == getHistogramPanel().getButtonShowAll()) {
141 11441 bsanchez
                        getHistogramPanel().refreshBands(true);
142 11202 bsanchez
                        for (int i = 0; i < showBands.length; i++)
143
                                showBands[i] = true;
144
                        updateStatistic();
145
                        updateGraphic();
146
                        return;
147
                }
148
149 10950 bsanchez
                //--------------------------------------
150
                //Selecci?n de fuente de datos del histograma
151 11228 bsanchez
                JComboBox cbo = getHistogramPanel().getComboBoxSource();
152 11042 bsanchez
                if (e.getSource() == cbo) {
153 10997 bsanchez
                        showHistogram();
154 10981 bsanchez
                        return;
155 10950 bsanchez
                }
156 12369 bsanchez
157 11444 bsanchez
                // Checkbox de eliminas extremos
158 11443 bsanchez
                if (e.getSource() == getHistogramPanel().getCBDeleteEdges()) {
159
                        updateGraphic();
160
                        return;
161
                }
162 12369 bsanchez
163 10950 bsanchez
                //--------------------------------------
164
                //Selecci?n de histograma acumulado y no acumulado
165 11228 bsanchez
                JComboBox cbt = getHistogramPanel().getComboBoxType();
166 11042 bsanchez
                if (e.getSource() == cbt) {
167 10997 bsanchez
                        updateStatistic();
168
                        updateGraphic();
169 10981 bsanchez
                        return;
170 10950 bsanchez
                }
171 12369 bsanchez
172 11033 bsanchez
                //--------------------------------------
173
                // Boton Crear Tabla
174 11116 bsanchez
                JButton table = getHistogramPanel().getBCreateTable();
175 11033 bsanchez
                if (e.getSource() == table) {
176
                        try {
177
//                        -------Mostrar un fileChooser------------------
178
                                String fName;
179
                                JFileChooser chooser = new JFileChooser();
180
                                chooser.setDialogTitle(PluginServices.getText(this, "guardar_tabla"));
181 12369 bsanchez
182 11116 bsanchez
                                int returnVal = chooser.showOpenDialog(getHistogramPanel());
183 11033 bsanchez
                                if (returnVal == JFileChooser.APPROVE_OPTION) {
184
                                        fName = chooser.getSelectedFile().toString();
185
                                        if (!fName.endsWith(".dbf"))
186
                                                fName += ".dbf";
187 12369 bsanchez
188 11033 bsanchez
                                        //-------------Crear el dbf----------------------
189 12369 bsanchez
190 11033 bsanchez
                                        DbaseFileWriterNIO dbfWrite = null;
191
                                        DbaseFileHeaderNIO myHeader;
192
                                        Value[] record;
193 12369 bsanchez
194 11180 bsanchez
                                        HistogramClass[][] histogram = getLastHistogram().getHistogram();
195 11033 bsanchez
                                        int numBands = histogram.length;
196
                                        int numRecors = histogram[0].length;
197 12369 bsanchez
198 11033 bsanchez
                                        File file = new File(fName);
199 12369 bsanchez
200 11033 bsanchez
                                        String names[] = new String[numBands+1];
201
                                        int types[] = new int [numBands+1];
202
                                        int lengths[] = new int [numBands+1];
203 12369 bsanchez
204 11033 bsanchez
                                        names[0]="Value";
205
                                        types[0]=4;
206
                                        lengths[0]=15;
207
                                        for (int band = 0; band < numBands; band++){
208
                                                names[band+1]="Band"+band;
209
                                                types[band+1]=4;
210
                                                lengths[band+1]=15;
211
                                        }
212 12369 bsanchez
213 11033 bsanchez
                                        myHeader = DbaseFileHeaderNIO.createDbaseHeader(names,types,lengths);
214 12369 bsanchez
215 11033 bsanchez
                                        myHeader.setNumRecords(numRecors);
216
                                        dbfWrite = new DbaseFileWriterNIO(myHeader, (FileChannel) getWriteChannel(file.getPath()));
217
                                        record = new Value[numBands+1];
218 12369 bsanchez
219 11033 bsanchez
                                        for (int j = 0; j < numRecors; j++) {
220
                                                record[0] = ValueFactory.createValue(j);
221
                                                for (int r = 0; r < numBands; r++) {
222 11180 bsanchez
                                                        record[r+1] = ValueFactory.createValue(histogram[r][j].getValue());
223 11033 bsanchez
                                                }
224 12369 bsanchez
225 11033 bsanchez
                                                dbfWrite.write(record);
226
                                        }
227 12369 bsanchez
228 11033 bsanchez
                                        dbfWrite.close();
229 12369 bsanchez
230 11033 bsanchez
                                        //------------A?adir el dbf al proyecto--------------
231
                                        ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
232
                                        String name = file.getName();
233
                                        LayerFactory.getDataSourceFactory().addFileDataSource("gdbms dbf driver", name, fName);
234
                                        DataSource dataSource;
235
                                        dataSource = LayerFactory.getDataSourceFactory().createRandomDataSource(name, DataSourceFactory.AUTOMATIC_OPENING);
236 12369 bsanchez
237 11033 bsanchez
                                        SelectableDataSource sds = new SelectableDataSource(dataSource);
238
                                        EditableAdapter auxea=new EditableAdapter();
239
                                        auxea.setOriginalDataSource(sds);
240
                                        ProjectTable projectTable = ProjectFactory.createTable(name, auxea);
241
                                        //ext.getProject().addTable(projectTable);
242
                                        ext.getProject().addDocument(projectTable);
243 12369 bsanchez
244 11033 bsanchez
                                        Table t = new Table();
245
                                        t.setModel(projectTable);
246
                                        //projectTable.setAndamiWindow(t);
247
                                        PluginServices.getMDIManager().addWindow(t);
248
                                }
249
                        } catch (IOException e1) {
250 11116 bsanchez
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),getHistogramPanel().getName() + " " + PluginServices.getText(this,"table_not_create"));
251 11033 bsanchez
                        } catch (DriverLoadException e1) {
252 11116 bsanchez
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),getHistogramPanel().getName() + " " + PluginServices.getText(this,"table_not_create"));
253 11033 bsanchez
                        } catch (NoSuchTableException e1) {
254 11116 bsanchez
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),getHistogramPanel().getName() + " " + PluginServices.getText(this,"table_not_create"));
255 11033 bsanchez
                        } catch (ReadDriverException e1) {
256 11116 bsanchez
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),getHistogramPanel().getName() + " " + PluginServices.getText(this,"table_not_create"));
257 11033 bsanchez
                        }
258
                }
259 10950 bsanchez
        }
260
261 11068 bsanchez
        /**
262
         * Actualizar la variable de las bandas visibles y su componente visual.
263
         */
264 11042 bsanchez
        private void refreshBands() {
265 11441 bsanchez
                getHistogramPanel().refreshBands(true);
266 11068 bsanchez
                showBands = new boolean[getLastHistogram().getNumBands()];
267 11042 bsanchez
                for (int i = 0; i < showBands.length; i++)
268
                        showBands[i] = true;
269
        }
270 12369 bsanchez
271 11068 bsanchez
        /**
272
         * Lanza los dos threads para procesar el histograma y visualizar la
273
         * ventana de incremento
274
         */
275 10950 bsanchez
        public void showHistogram() {
276 12369 bsanchez
                if (getHistogramPanel().getComboBoxSource().getSelectedIndex() < 0)
277 12307 nacho
                        return;
278 11042 bsanchez
279 12307 nacho
                int dataSrc = getHistogramPanel().getComboBoxSource().getSelectedIndex();
280
                IHistogramable iaux = (IHistogramable) ((ArrayList) getHistogramPanel().getComboSource().get(dataSrc)).get(0);
281 11441 bsanchez
282
                if (lastHistogram == null) {
283
                        try {
284
                                setNewHistogram(iaux.getHistogram());
285
                        } catch (HistogramException e) {
286 13932 nacho
                                RasterToolsUtil.messageBoxError("histogram_error", histogramPanel, e);
287
                                return;
288 13409 nacho
                        } catch (InterruptedException e) {
289
290 11441 bsanchez
                        }
291
                        return;
292
                }
293 12369 bsanchez
294 11283 nacho
                HistogramProcess histogramProcess = new HistogramProcess(iaux, this);
295
                IncrementableTask incrementableTask = new IncrementableTask(histogramProcess);
296 11042 bsanchez
                histogramProcess.setIncrementableTask(incrementableTask);
297 10950 bsanchez
                incrementableTask.showWindow();
298 11065 bsanchez
                iaux.resetPercent();
299 11042 bsanchez
                histogramProcess.start();
300
                incrementableTask.start();
301 10950 bsanchez
        }
302 11068 bsanchez
303 10950 bsanchez
        /**
304 11004 bsanchez
         * A?ade o elimina una banda de la visualizaci?n. Si la banda se est? visualizando
305
         * se elimina y si no entonces se muestra
306
         * @param band banda a visualizar o borrar del gr?fico
307
         */
308
        public void addOrRemoveGraphicBand(int band){
309 11033 bsanchez
                if (band > showBands.length) return;
310 11004 bsanchez
                showBands[band] = !showBands[band];
311
        }
312
313 11068 bsanchez
        /**
314
         * Actualiza la grafica con los datos que ya teniamos del histograma.
315
         */
316 10981 bsanchez
        private void updateGraphic() {
317 11191 bsanchez
                if (getLastHistogram() == null) return;
318 11228 bsanchez
                HistogramClass[][] histogramClass = getLastHistogram().getHistogramByType(Histogram.getType(getHistogramPanel().getComboBoxType().getSelectedIndex()));
319 11151 bsanchez
                if (histogramClass == null) return;
320 10981 bsanchez
321 11151 bsanchez
                double[][][] datos = new double[histogramClass.length][histogramClass[0].length][2];
322
                for (int iBand=0; iBand < histogramClass.length; iBand++) {
323
                        for (int i=0; i<histogramClass[iBand].length; i++) {
324
                                datos[iBand][i][0] = histogramClass[iBand][i].getMin();
325 11180 bsanchez
                                datos[iBand][i][1] = histogramClass[iBand][i].getValue();
326 11151 bsanchez
                        }
327
                }
328
329 11441 bsanchez
                // Definimos el principio y final de la grafica, sirve para descartar valores.
330
                int first = (int) getHistogramPanel().getBoxesValues(false)[1];
331
                int end = (int) getHistogramPanel().getBoxesValues(false)[0];
332 10981 bsanchez
333 11441 bsanchez
                // Si hay que eliminar los limites, quitamos el ultimo y primer valor de la grafica
334 11443 bsanchez
                if (getHistogramPanel().getCBDeleteEdges().isSelected()) {
335
                        if ((first + 1) <= end)
336
                                first++;
337
                        if ((end - 1) >= first)
338
                                end--;
339
                }
340 11441 bsanchez
341 11004 bsanchez
                int bandCount = 0;
342
                for (int i = 0; i < showBands.length; i++) {
343
                        if (showBands[i]) bandCount++;
344
                }
345 10997 bsanchez
346 11151 bsanchez
                double[][][] newHistogram = new double[bandCount][end - first][2];
347 11004 bsanchez
                String[] bandNames = new String[bandCount];
348 12369 bsanchez
349 11151 bsanchez
                bandCount = datos.length;
350 10997 bsanchez
351 11004 bsanchez
                int numBand = 0;
352 11151 bsanchez
                for (int iBand = 0; iBand < datos.length; iBand++) {
353 11004 bsanchez
                        if (!showBands[iBand]) continue;
354 12369 bsanchez
355 11151 bsanchez
                        for (int j=first; j<end; j++) {
356
                                newHistogram[numBand][j-first][0] = datos[iBand][j][0];
357
                                newHistogram[numBand][j-first][1] = datos[iBand][j][1];
358
                        }
359 11116 bsanchez
                        bandNames[numBand] = (String) ((DefaultTableModel) getHistogramPanel().getJTableBands().getModel()).getValueAt(iBand, 1);
360 11004 bsanchez
361 11116 bsanchez
                        getHistogramPanel().getGraphicContainer().setBandColor(numBand, bandsColor[iBand % bandsColor.length]);
362 11033 bsanchez
363 11004 bsanchez
                        numBand++;
364 10981 bsanchez
                }
365
366 11116 bsanchez
                getHistogramPanel().getGraphicContainer().getPGraphic().setNewChart(newHistogram, bandNames);
367 10981 bsanchez
        }
368 10997 bsanchez
369 11068 bsanchez
        /**
370
         * Definir el nuevo histograma, metodo pu?blico para ser invocado desde
371
         * histogramProcess
372
         * @param histograma nuevo
373
         */
374 11042 bsanchez
        public void setNewHistogram(Histogram value) {
375 11116 bsanchez
                getHistogramPanel().panelInizialited = false;
376 11042 bsanchez
                eventsEnabled = false;
377
                lastHistogram = value;
378
                refreshBands();
379 10981 bsanchez
                updateGraphic();
380 11444 bsanchez
                updateStatistic();
381 10970 bsanchez
382 11042 bsanchez
                // Activo la ejecucion de los eventos porque seguro que ya tenemos un histograma
383
                eventsEnabled = true;
384 11116 bsanchez
                getHistogramPanel().panelInizialited = true;
385 10970 bsanchez
        }
386
387 11068 bsanchez
        /**
388
         * Obtener ?ltimo histograma
389
         * @return Histogram
390
         */
391
        public Histogram getLastHistogram() {
392 11042 bsanchez
                return lastHistogram;
393 10970 bsanchez
        }
394 11004 bsanchez
395 11068 bsanchez
        /**
396
         * Eventos de los BoxValues
397
         */
398 11004 bsanchez
        public void actionValueChanged(GraphicEvent e) {
399 11444 bsanchez
                updateStatistic();
400 11004 bsanchez
        }
401 12369 bsanchez
402 11068 bsanchez
        /**
403
         * Proceso para guardar una estadistica en un fichero.
404
         * @param path
405
         * @return
406
         * @throws IOException
407
         */
408
        private WritableByteChannel getWriteChannel(String path) throws IOException {
409 11033 bsanchez
                WritableByteChannel channel;
410 12369 bsanchez
411 11033 bsanchez
                File f = new File(path);
412 12369 bsanchez
413 11033 bsanchez
                if (!f.exists()) {
414
                        System.out.println("Creando fichero " + f.getAbsolutePath());
415 12369 bsanchez
416 11033 bsanchez
                        if (!f.createNewFile()) {
417
                                throw new IOException("Cannot create file " + f);
418
                        }
419
                }
420 12369 bsanchez
421 11033 bsanchez
                RandomAccessFile raf = new RandomAccessFile(f, "rw");
422
                channel = raf.getChannel();
423 12369 bsanchez
424 11033 bsanchez
                return channel;
425
        }
426 11116 bsanchez
427 11444 bsanchez
        /**
428
         *  Cuando se selecciona/deselecciona una banda
429
         */
430 11116 bsanchez
        public void propertyChange(PropertyChangeEvent evt) {
431
                if (!eventsEnabled) return;
432
                int countRow = ((DefaultTableModel) histogramPanel.getJTableBands().getModel()).getRowCount();
433
                for (int i=0; i<countRow; i++) {
434
                        showBands[i] = ((Boolean) ((DefaultTableModel) histogramPanel.getJTableBands().getModel()).getValueAt(i, 0)).booleanValue();
435
                }
436
                updateGraphic();
437
                updateStatistic();
438
        }
439 10950 bsanchez
}