Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRasterTools-SE / src / org / gvsig / rastertools / geolocation / listener / GeoLocationPanelListener.java @ 16326

History | View | Annotate | Download (9.72 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2007 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.geolocation.listener;
20

    
21
import java.awt.event.ActionEvent;
22
import java.awt.event.ActionListener;
23
import java.awt.geom.AffineTransform;
24
import java.awt.geom.Rectangle2D;
25
import java.io.BufferedReader;
26
import java.io.File;
27
import java.io.FileInputStream;
28
import java.io.FileNotFoundException;
29
import java.io.IOException;
30
import java.io.InputStreamReader;
31
import java.util.EventObject;
32

    
33
import javax.swing.JFileChooser;
34

    
35
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
36
import org.gvsig.gui.beans.datainput.DataInputContainerListener;
37
import org.gvsig.raster.datastruct.Extent;
38
import org.gvsig.raster.util.Historical;
39
import org.gvsig.raster.util.RasterToolsUtil;
40
import org.gvsig.rastertools.geolocation.ui.GeoLocationPanel;
41

    
42
import com.iver.andami.PluginServices;
43
import com.iver.cit.gvsig.addlayer.fileopen.FileOpenWizard;
44
import com.iver.cit.gvsig.fmap.ViewPort;
45

    
46
/**
47
 * Listener para el panel de geolocalizaci?n.
48
 * @version 31/07/2007
49
 * @author Nacho Brodin (nachobrodin@gmail.com)
50
 *
51
 */
52
public class GeoLocationPanelListener implements ActionListener, DataInputContainerListener {
53
        
54
        private GeoLocationPanel        panel = null;
55
        private boolean             enableValueChangeEvent = false;
56
        
57
        /**
58
         * Crea un nuevo <code>GeoLocationPanelListener</code> 
59
         * @param panel
60
         */
61
        public GeoLocationPanelListener(GeoLocationPanel panel) {
62
                this.panel = panel;
63
        }
64

    
65
        /**
66
         * M?todo que se invoca cuando se disparan los eventos de los botones
67
         */
68
        public void actionPerformed(ActionEvent e) {
69
                if(e.getSource() == panel.getSaveButton()) {
70
                        if(RasterToolsUtil.messageBoxYesOrNot(PluginServices.getText(this,"aviso_write_transform"), panel)) {
71
                                try {
72
                                        panel.getLayer().saveGeoToRmf();
73
                                        panel.activeButtons();
74
                                } catch (IOException e1) {
75
                                        RasterToolsUtil.messageBoxError(PluginServices.getText(this,"error_salvando_rmf"), panel);
76
                                }
77
                                panel.setModify(false);
78
                        }
79
                        return;
80
                }
81
                
82
                //Asignamos la georreferenciaci?n que hay en ese momento en el dialogo
83
                if(e.getSource() == panel.getApplyButton()) {
84
                        try {
85
                                double ulx = Double.parseDouble(panel.getUlx().getValue());
86
                                double uly = Double.parseDouble(panel.getUly().getValue());
87
                                double psx = Double.parseDouble(panel.getPsx().getValue());
88
                                double psy = Double.parseDouble(panel.getPsy().getValue());
89
                                double rotx = Double.parseDouble(panel.getRotx().getValue());
90
                                double roty = Double.parseDouble(panel.getRoty().getValue());
91
                                AffineTransform at = new AffineTransform(psx, roty, rotx, psy, ulx, uly);
92
                                panel.getLayer().setAffineTransform(at);
93
                                panel.getMapCtrl().getMapContext().invalidate();
94
                                return;
95
                        } catch(NumberFormatException ex) {
96
                                RasterToolsUtil.messageBoxError(PluginServices.getText(this,"error_transformacion"), panel);
97
                                return;
98
                        }
99
                }
100
                
101
                Historical hist = panel.getHistorical();
102
                if(hist == null)
103
                        return;
104
                
105
                AffineTransform at = null;
106
                
107
                //Cargamos la primera transformaci?n
108
                if(e.getSource() == panel.getFirstButton()) 
109
                        at = (AffineTransform)hist.getFirst();
110
                                        
111
                //Cargamos la transformaci?n anterior
112
                if(e.getSource() == panel.getBackButton()) 
113
                        at = (AffineTransform)hist.getBack();
114
                                        
115
                ////Cargamos la transformaci?n siguiente
116
                if(e.getSource() == panel.getNextButton())
117
                        at = (AffineTransform)hist.getNext();
118

    
119
                //Cargamos la georreferenciaci?n del raster
120
                if(e.getSource() == panel.getResetButton())
121
                        at = panel.getLayer().getDataSource().getOwnAffineTransform();
122
                
123
                //Cargar la georreferenciaci?n desde tfw
124
                if(e.getSource() == panel.getTfwLoad()) {
125
                        JFileChooser chooser = new JFileChooser(FileOpenWizard.getLastPath());
126
                        chooser.setDialogTitle(PluginServices.getText(this, "seleccionar_fichero"));
127
                        chooser.addChoosableFileFilter(new GeorreferencingFileFilter("tfw"));
128
                        chooser.addChoosableFileFilter(new GeorreferencingFileFilter("wld"));
129
                        int returnVal = chooser.showOpenDialog(panel);
130
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
131
                                String fName = chooser.getSelectedFile().toString();
132
                                at = readTfw(fName);
133
                        }
134
                }
135
                
136
                //Centrar el raster en la vista
137
                if(e.getSource() == panel.getCenterToView()) {
138
                        Extent extentView = calcCenterExtent(panel.getViewPort());
139
                        double x = extentView.minX();
140
                        double y = extentView.maxY();
141
                        double psX = extentView.width() / ((FLyrRasterSE)panel.getLayer()).getPxWidth();
142
                        double psY = -(extentView.height() / ((FLyrRasterSE)panel.getLayer()).getPxHeight());
143
                        at = new AffineTransform(psX, 0, 0, psY, x, y);
144
                        panel.setModify(true);
145
                }
146
                
147
                //Entrar? en el caso de que se haya seleccionado alguna transformaci?n
148
                if(at != null) {
149
                        panel.getLayer().setAT(at);
150
                        panel.loadTransform(at);
151
                        panel.activeButtons();
152
                        panel.getMapCtrl().getMapContext().invalidate();
153
                }
154
        }
155
        
156
        /**
157
         * Control del cambio de valor dentro de las cajas de texto. Cuando esto ocurre tiene
158
         * el mismo efecto que el bot?n "Aplicar"
159
         * @param e EventObject
160
         */
161
        public void actionValueChanged(EventObject e) {
162
                if(isEnableValueChangeEvent()) {
163
                        ActionEvent ev = new ActionEvent(panel.getApplyButton(), 0, null);
164
                        actionPerformed(ev);
165
                }
166
        }
167

    
168
        /**
169
         * Obtiene el valor de la variable que informa sobre la activaci?n y desactivaci?n del evento de cambio de valor
170
         * dentro de un campo de texto
171
         * @return enableValueChangeEvent
172
         */
173
        public boolean isEnableValueChangeEvent() {
174
                return enableValueChangeEvent;
175
        }
176

    
177
        /**
178
         * Asigna el valor para la activaci?n y desactivaci?n del evento de cambio de valor
179
         * dentro de un campo de texto
180
         * @param enableValueChangeEvent
181
         */
182
        public void setEnableValueChangeEvent(boolean enableValueChangeEvent) {
183
                this.enableValueChangeEvent = enableValueChangeEvent;
184
        }
185
        
186
        /**
187
         * Centra el raster asociado a la capa en al extent del viewport pasado 
188
         * por par?metro. 
189
         * @param vp ViewPort
190
         * @return        Extent para la imagen
191
         */
192
        private Extent calcCenterExtent(ViewPort vp) {
193
                Extent tempExtent = null;
194
                double widthPxImg, heightPxImg;
195
                
196
                widthPxImg = ((FLyrRasterSE)panel.getLayer()).getPxWidth();
197
                heightPxImg = ((FLyrRasterSE)panel.getLayer()).getPxHeight();
198
                
199
                if(vp == null || vp.getAdjustedExtent() == null) {
200
                        vp = new ViewPort(null);
201
                        Rectangle2D r2d = new Rectangle2D.Double(0, 0, widthPxImg, heightPxImg);
202
                        vp.setExtent(r2d);
203
                        tempExtent = new Extent(0, 0, widthPxImg, heightPxImg);
204
                } else
205
                        tempExtent = new Extent(vp.getAdjustedExtent());
206

    
207
                double ulX = 0D, ulY = 0D, lrX = 0D, lrY = 0D;
208
                if(widthPxImg > heightPxImg) {
209
                        double widthView = tempExtent.maxX() - tempExtent.minX();
210
                        ulX = tempExtent.minX() + (widthView / 4);
211
                        lrX = ulX + (widthView / 2);
212
                        double newAlto = ((heightPxImg * (widthView / 2)) / widthPxImg);
213
                        double centroY = tempExtent.minY()+((tempExtent.maxY() - tempExtent.minY())/2);
214
                        ulY = centroY - (newAlto / 2);
215
                        lrY = centroY + (newAlto / 2);
216
                } else {
217
                        double heightView = tempExtent.maxY() - tempExtent.minY();
218
                        ulY = tempExtent.minY() + (heightView / 4);
219
                        lrY = ulY + (heightView / 2);
220
                        double newAncho = ((widthPxImg * (heightView / 2)) / heightPxImg);
221
                        double centroX = tempExtent.minX()+((tempExtent.maxX() - tempExtent.minX())/2);
222
                        ulX = centroX - (newAncho / 2);
223
                        lrX = centroX + (newAncho / 2);
224
                }
225
                return new Extent(ulX, ulY, lrX, lrY);
226
        }
227
        
228
        /**
229
         * Lee las coordenadas de un fichero de tfw con una transformaci?n y 
230
         * devuelve la clase AffineTransform con dicha transformaci?n. Esta llamada gestiona los
231
         * errores producidos actuando en consecuencia. Muestra los mensajes al usuario y retorna
232
         * null en caso de tener problemas.
233
         * @param fName Nombre del fichero tfw
234
         * @return AffineTransform
235
         */
236
        private AffineTransform readTfw(String fName) {
237
                BufferedReader inGrf = null;
238
                double[] result = new double[6];
239
                try {
240
                        inGrf = new BufferedReader(new InputStreamReader(new FileInputStream(fName)));
241
                        String str = inGrf.readLine();
242
                        int count = 0;
243
                        while(str != null && count < 6) {
244
                                try {
245
                                        Double value =  new Double(str);
246
                                        result[count] = value.doubleValue();
247
                                } catch (NumberFormatException ex) {
248
                                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_file_not_valid"), panel, ex);
249
                                        return null;
250
                                }
251
                                str = inGrf.readLine();
252
                                count ++;
253
                        }
254
                } catch (FileNotFoundException e) {
255
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_file_not_found"), panel, e);
256
                        return null;
257
                } catch (IOException ex) {
258
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_lectura"), panel, ex);
259
                        return null;
260
                }
261
                return new AffineTransform(result[0], result[1], result[2], result[3], result[4], result[5]);
262
        }
263
        
264
        /**
265
         * Filtro para el selector de formatos de georreferenciaci?n
266
         * @author Nacho Brodin (nachobrodin@gmail.com)
267
         */
268
        class GeorreferencingFileFilter extends javax.swing.filechooser.FileFilter {
269
                private String                                filter;
270

    
271
                public GeorreferencingFileFilter(String fil) {
272
                        this.filter = fil;
273
                }
274

    
275
                public boolean accept(File f) {
276
                        return f.isDirectory() || f.getName().toLowerCase().endsWith("." + filter);
277
                }
278

    
279
                public String getDescription() {
280
                        return "." + filter;
281
                }
282
        }
283
}