Statistics
| Revision:

root / trunk / extensions / extRasterTools-SE / src / org / gvsig / rastertools / geolocation / listener / GeoLocationPanelListener.java @ 17503

History | View | Annotate | Download (11.1 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.event.KeyEvent;
24
import java.awt.event.KeyListener;
25
import java.awt.geom.AffineTransform;
26
import java.awt.geom.Rectangle2D;
27
import java.io.BufferedReader;
28
import java.io.FileInputStream;
29
import java.io.FileNotFoundException;
30
import java.io.IOException;
31
import java.io.InputStreamReader;
32
import java.util.EventObject;
33

    
34
import javax.swing.JFileChooser;
35

    
36
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
37
import org.gvsig.gui.beans.datainput.DataInputContainerListener;
38
import org.gvsig.raster.datastruct.Extent;
39
import org.gvsig.raster.util.ExtendedFileFilter;
40
import org.gvsig.raster.util.Historical;
41
import org.gvsig.raster.util.RasterToolsUtil;
42
import org.gvsig.rastertools.geolocation.ui.GeoLocationOpeningRasterPanel;
43
import org.gvsig.rastertools.geolocation.ui.GeoLocationPanel;
44
import org.gvsig.rastertools.geolocation.ui.GeolocationBaseClassPanel;
45

    
46
import com.iver.andami.PluginServices;
47
import com.iver.cit.gvsig.addlayer.fileopen.FileOpenWizard;
48
import com.iver.cit.gvsig.fmap.ViewPort;
49

    
50
/**
51
 * Listener para el panel de geolocalizaci?n.
52
 * @version 31/07/2007
53
 * @author Nacho Brodin (nachobrodin@gmail.com)
54
 *
55
 */
56
public class GeoLocationPanelListener implements ActionListener, DataInputContainerListener, KeyListener {
57

    
58
        private GeolocationBaseClassPanel        panel = null;
59
        private boolean                     enableValueChangeEvent = false;
60

    
61
        /**
62
         * Crea un nuevo <code>GeoLocationPanelListener</code>
63
         * @param panel
64
         */
65
        public GeoLocationPanelListener(GeolocationBaseClassPanel panel) {
66
                this.panel = panel;
67
        }
68

    
69
        /**
70
         * M?todo que se invoca cuando se disparan los eventos de los botones
71
         */
72
        public void actionPerformed(ActionEvent e) {
73
                if(e.getSource() == panel.getSaveButton()) {
74
                        if(RasterToolsUtil.messageBoxYesOrNot(PluginServices.getText(this,"aviso_write_transform"), panel)) {
75
                                try {
76
                                        panel.getLayer().saveGeoToRmf();
77
                                        panel.activeButtons();
78
                                } catch (IOException e1) {
79
                                        RasterToolsUtil.messageBoxError(PluginServices.getText(this,"error_salvando_rmf"), panel);
80
                                }
81
                                panel.setModify(false);
82
                        }
83
                        return;
84
                }
85

    
86
                //Asignamos la georreferenciaci?n que hay en ese momento en el dialogo
87
                if(e.getSource() == panel.getApplyButton()) {
88
                        try {
89
                                double ulx = Double.parseDouble(panel.getUlx().getValue());
90
                                double uly = Double.parseDouble(panel.getUly().getValue());
91
                                double psx = Double.parseDouble(panel.getPsx().getValue());
92
                                double psy = Double.parseDouble(panel.getPsy().getValue());
93
                                double rotx = Double.parseDouble(panel.getRotx().getValue());
94
                                double roty = Double.parseDouble(panel.getRoty().getValue());
95
                                if(psx == 0 || psy == 0)
96
                                        return;
97
                                AffineTransform at = new AffineTransform(psx, roty, rotx, psy, ulx, uly);
98
                                panel.getLayer().setAffineTransform(at);
99
                                if(panel.getMapCtrl() != null)
100
                                        panel.getMapCtrl().getMapContext().invalidate();
101
                                else {
102
                                        if(panel instanceof GeoLocationOpeningRasterPanel)
103
                                                PluginServices.getMDIManager().closeWindow(((GeoLocationOpeningRasterPanel)panel).getDialog());
104
                                }
105
                                                                        
106
                                return;
107
                        } catch(NumberFormatException ex) {
108
                                RasterToolsUtil.messageBoxError(PluginServices.getText(this,"error_transformacion"), panel);
109
                                return;
110
                        }
111
                }
112
                
113
                if(e.getSource() == panel.getCancelButton()) {
114
                        PluginServices.getMDIManager().closeWindow(((GeoLocationOpeningRasterPanel)panel).getDialog());
115
                }
116

    
117
                Historical hist = panel.getHistorical();
118
                if(hist == null)
119
                        return;
120

    
121
                AffineTransform at = null;
122

    
123
                //Cargamos la primera transformaci?n
124
                if(e.getSource() == panel.getFirstButton())
125
                        at = (AffineTransform)hist.getFirst();
126

    
127
                //Cargamos la transformaci?n anterior
128
                if(e.getSource() == panel.getBackButton())
129
                        at = (AffineTransform)hist.getBack();
130

    
131
                ////Cargamos la transformaci?n siguiente
132
                if(e.getSource() == panel.getNextButton())
133
                        at = (AffineTransform)hist.getNext();
134

    
135
                //Cargamos la georreferenciaci?n del raster
136
                if(e.getSource() == panel.getResetButton())
137
                        at = panel.getLayer().getDataSource().getOwnAffineTransform();
138

    
139
                //Cargar la georreferenciaci?n desde tfw
140
                if(e.getSource() == panel.getTfwLoad()) {
141
                        JFileChooser chooser = new JFileChooser(FileOpenWizard.getLastPath());
142
                        chooser.setDialogTitle(PluginServices.getText(this, "seleccionar_fichero"));
143
                        chooser.addChoosableFileFilter(new ExtendedFileFilter("tfw"));
144
                        chooser.addChoosableFileFilter(new ExtendedFileFilter("wld"));
145

    
146
                        ExtendedFileFilter allFilters = new ExtendedFileFilter();
147
                        allFilters.addExtension("tfw");
148
                        allFilters.addExtension("wld");
149
                        allFilters.setDescription(PluginServices.getText(this, "todos_soportados"));
150
                        chooser.addChoosableFileFilter(allFilters);
151
                        chooser.setFileFilter(allFilters);
152

    
153
                        int returnVal = chooser.showOpenDialog(panel);
154
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
155
                                String fName = chooser.getSelectedFile().toString();
156
                                at = readTfw(fName);
157
                        }
158
                }
159

    
160
                //Centrar el raster en la vista
161
                if(e.getSource() == panel.getCenterToView()) {
162
                        Extent extentView = calcCenterExtent(panel.getViewPort());
163
                        double x = extentView.minX();
164
                        double y = extentView.maxY();
165
                        double psX = extentView.width() / ((FLyrRasterSE)panel.getLayer()).getPxWidth();
166
                        double psY = -(extentView.height() / ((FLyrRasterSE)panel.getLayer()).getPxHeight());
167
                        at = new AffineTransform(psX, 0, 0, psY, x, y);
168
                        panel.setModify(true);
169
                }
170

    
171
                //Entrar? en el caso de que se haya seleccionado alguna transformaci?n
172
                if(at != null) {
173
                        panel.getLayer().setAT(at);
174
                        panel.loadTransform(at);
175
                        panel.activeButtons();
176
                        if(panel.getMapCtrl() != null)
177
                                panel.getMapCtrl().getMapContext().invalidate();
178
                }
179
        }
180

    
181
        /**
182
         * Control del cambio de valor dentro de las cajas de texto. Cuando esto ocurre tiene
183
         * el mismo efecto que el bot?n "Aplicar"
184
         * @param e EventObject
185
         */
186
        public void actionValueChanged(EventObject e) {
187
                if(isEnableValueChangeEvent() && panel instanceof GeoLocationPanel) {
188
                        ActionEvent ev = new ActionEvent(panel.getApplyButton(), 0, null);
189
                        actionPerformed(ev);
190
                }
191
        }
192

    
193
        /**
194
         * Obtiene el valor de la variable que informa sobre la activaci?n y desactivaci?n del evento de cambio de valor
195
         * dentro de un campo de texto
196
         * @return enableValueChangeEvent
197
         */
198
        public boolean isEnableValueChangeEvent() {
199
                return enableValueChangeEvent;
200
        }
201

    
202
        /**
203
         * Asigna el valor para la activaci?n y desactivaci?n del evento de cambio de valor
204
         * dentro de un campo de texto
205
         * @param enableValueChangeEvent
206
         */
207
        public void setEnableValueChangeEvent(boolean enableValueChangeEvent) {
208
                this.enableValueChangeEvent = enableValueChangeEvent;
209
        }
210

    
211
        /**
212
         * Centra el raster asociado a la capa en al extent del viewport pasado
213
         * por par?metro.
214
         * @param vp ViewPort
215
         * @return        Extent para la imagen
216
         */
217
        private Extent calcCenterExtent(ViewPort vp) {
218
                Extent tempExtent = null;
219
                double widthPxImg, heightPxImg;
220

    
221
                widthPxImg = ((FLyrRasterSE)panel.getLayer()).getPxWidth();
222
                heightPxImg = ((FLyrRasterSE)panel.getLayer()).getPxHeight();
223

    
224
                if(vp == null || vp.getAdjustedExtent() == null) {
225
                        vp = new ViewPort(null);
226
                        Rectangle2D r2d = new Rectangle2D.Double(0, 0, widthPxImg, heightPxImg);
227
                        vp.setExtent(r2d);
228
                        tempExtent = new Extent(0, 0, widthPxImg, heightPxImg);
229
                } else
230
                        tempExtent = new Extent(vp.getAdjustedExtent());
231

    
232
                double ulX = 0D, ulY = 0D, lrX = 0D, lrY = 0D;
233
                if(widthPxImg > heightPxImg) {
234
                        double widthView = tempExtent.maxX() - tempExtent.minX();
235
                        ulX = tempExtent.minX() + (widthView / 4);
236
                        lrX = ulX + (widthView / 2);
237
                        double newAlto = ((heightPxImg * (widthView / 2)) / widthPxImg);
238
                        double centroY = tempExtent.minY()+((tempExtent.maxY() - tempExtent.minY())/2);
239
                        ulY = centroY - (newAlto / 2);
240
                        lrY = centroY + (newAlto / 2);
241
                } else {
242
                        double heightView = tempExtent.maxY() - tempExtent.minY();
243
                        ulY = tempExtent.minY() + (heightView / 4);
244
                        lrY = ulY + (heightView / 2);
245
                        double newAncho = ((widthPxImg * (heightView / 2)) / heightPxImg);
246
                        double centroX = tempExtent.minX()+((tempExtent.maxX() - tempExtent.minX())/2);
247
                        ulX = centroX - (newAncho / 2);
248
                        lrX = centroX + (newAncho / 2);
249
                }
250
                return new Extent(ulX, ulY, lrX, lrY);
251
        }
252

    
253
        /**
254
         * Lee las coordenadas de un fichero de tfw con una transformaci?n y
255
         * devuelve la clase AffineTransform con dicha transformaci?n. Esta llamada gestiona los
256
         * errores producidos actuando en consecuencia. Muestra los mensajes al usuario y retorna
257
         * null en caso de tener problemas.
258
         * @param fName Nombre del fichero tfw
259
         * @return AffineTransform
260
         */
261
        private AffineTransform readTfw(String fName) {
262
                BufferedReader inGrf = null;
263
                double[] result = new double[6];
264
                try {
265
                        inGrf = new BufferedReader(new InputStreamReader(new FileInputStream(fName)));
266
                        String str = inGrf.readLine();
267
                        int count = 0;
268
                        while(str != null && count < 6) {
269
                                try {
270
                                        Double value =  new Double(str);
271
                                        result[count] = value.doubleValue();
272
                                } catch (NumberFormatException ex) {
273
                                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_file_not_valid"), panel, ex);
274
                                        return null;
275
                                }
276
                                str = inGrf.readLine();
277
                                count ++;
278
                        }
279
                } catch (FileNotFoundException e) {
280
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_file_not_found"), panel, e);
281
                        return null;
282
                } catch (IOException ex) {
283
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_lectura"), panel, ex);
284
                        return null;
285
                }
286
                return new AffineTransform(result[0], result[1], result[2], result[3], result[4], result[5]);
287
        }
288
        
289
        /*
290
         * (non-Javadoc)
291
         * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
292
         */
293
        public void keyPressed(KeyEvent e) {
294

    
295
        }
296

    
297
        /**
298
         * Capturamos el evento de pulsar la tecla Enter y cancel. Cuando pulsamos enter
299
         * ejecuta el evento del bot?n de aplicar y cuando pulsamos cancel cerramos el cuadro 
300
         * y no hacemos nada. 
301
         */
302
        public void keyReleased(KeyEvent e) {
303
                if(e.getKeyCode() == KeyEvent.VK_ENTER) {
304
                        ActionEvent ev = new ActionEvent(panel.getApplyButton(), 0, null);
305
                        actionPerformed(ev);
306
                }
307
                
308
                if(e.getKeyCode() == KeyEvent.VK_ESCAPE && panel.getCancelButton() != null) {
309
                        ActionEvent ev = new ActionEvent(panel.getCancelButton(), 0, null);
310
                        actionPerformed(ev);
311
                }
312
        }
313

    
314
        /*
315
         * (non-Javadoc)
316
         * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
317
         */
318
        public void keyTyped(KeyEvent e) {
319
        }
320
}