Statistics
| Revision:

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

History | View | Annotate | Download (11.7 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.dataset.serializer.RmfSerializerException;
39
import org.gvsig.raster.datastruct.Extent;
40
import org.gvsig.raster.util.ExtendedFileFilter;
41
import org.gvsig.raster.util.Historical;
42
import org.gvsig.raster.util.RasterToolsUtil;
43
import org.gvsig.rastertools.geolocation.ui.GeoLocationDialog;
44
import org.gvsig.rastertools.geolocation.ui.GeoLocationOpeningRasterPanel;
45
import org.gvsig.rastertools.geolocation.ui.GeoLocationPanel;
46
import org.gvsig.rastertools.geolocation.ui.GeolocationBaseClassPanel;
47

    
48
import com.iver.andami.PluginServices;
49
import com.iver.cit.gvsig.addlayer.fileopen.FileOpenWizard;
50
import com.iver.cit.gvsig.fmap.MapControl;
51
import com.iver.cit.gvsig.fmap.ViewPort;
52
import com.iver.cit.gvsig.project.documents.view.gui.BaseView;
53

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

    
62
        private GeolocationBaseClassPanel        panel                  = null;
63
        private boolean                     enableValueChangeEvent = false;
64
        private GeoLocationDialog           dialog                 = null;
65

    
66
        /**
67
         * Crea un nuevo <code>GeoLocationPanelListener</code>
68
         * @param panel
69
         */
70
        public GeoLocationPanelListener(GeolocationBaseClassPanel panel, GeoLocationDialog dialog) {
71
                this.dialog = dialog;
72
                this.panel = panel;
73
        }
74

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

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

    
124
                Historical hist = panel.getHistorical();
125
                if(hist == null)
126
                        return;
127

    
128
                AffineTransform at = null;
129

    
130
                //Cargamos la primera transformaci?n
131
                if(e.getSource() == panel.getFirstButton())
132
                        at = (AffineTransform)hist.getFirst();
133

    
134
                //Cargamos la transformaci?n anterior
135
                if(e.getSource() == panel.getBackButton())
136
                        at = (AffineTransform)hist.getBack();
137

    
138
                ////Cargamos la transformaci?n siguiente
139
                if(e.getSource() == panel.getNextButton())
140
                        at = (AffineTransform)hist.getNext();
141

    
142
                //Cargamos la georreferenciaci?n del raster
143
                if(e.getSource() == panel.getResetButton())
144
                        at = panel.getLayer().getDataSource().getOwnAffineTransform();
145

    
146
                //Cargar la georreferenciaci?n desde tfw
147
                if(e.getSource() == panel.getTfwLoad()) {
148
                        JFileChooser chooser = new JFileChooser(FileOpenWizard.getLastPath());
149
                        chooser.setDialogTitle(PluginServices.getText(this, "seleccionar_fichero"));
150
                        chooser.addChoosableFileFilter(new ExtendedFileFilter("tfw"));
151
                        chooser.addChoosableFileFilter(new ExtendedFileFilter("wld"));
152

    
153
                        ExtendedFileFilter allFilters = new ExtendedFileFilter();
154
                        allFilters.addExtension("tfw");
155
                        allFilters.addExtension("wld");
156
                        allFilters.setDescription(PluginServices.getText(this, "todos_soportados"));
157
                        chooser.addChoosableFileFilter(allFilters);
158
                        chooser.setFileFilter(allFilters);
159

    
160
                        int returnVal = chooser.showOpenDialog(panel);
161
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
162
                                String fName = chooser.getSelectedFile().toString();
163
                                at = readTfw(fName);
164
                        }
165
                }
166

    
167
                //Centrar el raster en la vista
168
                if(e.getSource() == panel.getCenterToView()) {
169
                        Extent extentView = calcCenterExtent(panel.getViewPort());
170
                        double x = extentView.minX();
171
                        double y = extentView.maxY();
172
                        double psX = extentView.width() / ((FLyrRasterSE)panel.getLayer()).getPxWidth();
173
                        double psY = -(extentView.height() / ((FLyrRasterSE)panel.getLayer()).getPxHeight());
174
                        at = new AffineTransform(psX, 0, 0, psY, x, y);
175
                        panel.setModify(true);
176
                }
177
                
178
                //Recuperar el foco
179
                if(e.getSource() == panel.getFocus()) {
180
                        if(dialog != null) {
181
                                BaseView theView = dialog.getAssociateView();
182
                                MapControl mapCtrl = theView.getMapControl();
183
                                mapCtrl.setTool("geoPan");
184
                        }
185
                }
186

    
187
                //Entrar? en el caso de que se haya seleccionado alguna transformaci?n
188
                if(at != null) {
189
                        panel.getLayer().setAT(at);
190
                        panel.loadTransform(at);
191
                        panel.activeButtons();
192
                        if(panel.getMapCtrl() != null)
193
                                panel.getMapCtrl().getMapContext().invalidate();
194
                }
195
        }
196
        
197
        /**
198
         * Control del cambio de valor dentro de las cajas de texto. Cuando esto ocurre tiene
199
         * el mismo efecto que el bot?n "Aplicar"
200
         * @param e EventObject
201
         */
202
        public void actionValueChanged(EventObject e) {
203
                if(isEnableValueChangeEvent() && panel instanceof GeoLocationPanel) {
204
                        ActionEvent ev = new ActionEvent(panel.getApplyButton(), 0, null);
205
                        actionPerformed(ev);
206
                }
207
        }
208

    
209
        /**
210
         * Obtiene el valor de la variable que informa sobre la activaci?n y desactivaci?n del evento de cambio de valor
211
         * dentro de un campo de texto
212
         * @return enableValueChangeEvent
213
         */
214
        public boolean isEnableValueChangeEvent() {
215
                return enableValueChangeEvent;
216
        }
217

    
218
        /**
219
         * Asigna el valor para la activaci?n y desactivaci?n del evento de cambio de valor
220
         * dentro de un campo de texto
221
         * @param enableValueChangeEvent
222
         */
223
        public void setEnableValueChangeEvent(boolean enableValueChangeEvent) {
224
                this.enableValueChangeEvent = enableValueChangeEvent;
225
        }
226

    
227
        /**
228
         * Centra el raster asociado a la capa en al extent del viewport pasado
229
         * por par?metro.
230
         * @param vp ViewPort
231
         * @return        Extent para la imagen
232
         */
233
        private Extent calcCenterExtent(ViewPort vp) {
234
                Extent tempExtent = null;
235
                double widthPxImg, heightPxImg;
236

    
237
                widthPxImg = ((FLyrRasterSE)panel.getLayer()).getPxWidth();
238
                heightPxImg = ((FLyrRasterSE)panel.getLayer()).getPxHeight();
239

    
240
                if(vp == null || vp.getAdjustedExtent() == null) {
241
                        vp = new ViewPort(null);
242
                        Rectangle2D r2d = new Rectangle2D.Double(0, 0, widthPxImg, heightPxImg);
243
                        vp.setExtent(r2d);
244
                        tempExtent = new Extent(0, 0, widthPxImg, heightPxImg);
245
                } else
246
                        tempExtent = new Extent(vp.getAdjustedExtent());
247

    
248
                double ulX = 0D, ulY = 0D, lrX = 0D, lrY = 0D;
249
                if(widthPxImg > heightPxImg) {
250
                        double widthView = tempExtent.maxX() - tempExtent.minX();
251
                        ulX = tempExtent.minX() + (widthView / 4);
252
                        lrX = ulX + (widthView / 2);
253
                        double newAlto = ((heightPxImg * (widthView / 2)) / widthPxImg);
254
                        double centroY = tempExtent.minY()+((tempExtent.maxY() - tempExtent.minY())/2);
255
                        ulY = centroY - (newAlto / 2);
256
                        lrY = centroY + (newAlto / 2);
257
                } else {
258
                        double heightView = tempExtent.maxY() - tempExtent.minY();
259
                        ulY = tempExtent.minY() + (heightView / 4);
260
                        lrY = ulY + (heightView / 2);
261
                        double newAncho = ((widthPxImg * (heightView / 2)) / heightPxImg);
262
                        double centroX = tempExtent.minX()+((tempExtent.maxX() - tempExtent.minX())/2);
263
                        ulX = centroX - (newAncho / 2);
264
                        lrX = centroX + (newAncho / 2);
265
                }
266
                return new Extent(ulX, ulY, lrX, lrY);
267
        }
268

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

    
311
        }
312

    
313
        /**
314
         * Capturamos el evento de pulsar la tecla Enter y cancel. Cuando pulsamos enter
315
         * ejecuta el evento del bot?n de aplicar y cuando pulsamos cancel cerramos el cuadro 
316
         * y no hacemos nada. 
317
         */
318
        public void keyReleased(KeyEvent e) {
319
                if(e.getKeyCode() == KeyEvent.VK_ENTER) {
320
                        ActionEvent ev = new ActionEvent(panel.getApplyButton(), 0, null);
321
                        actionPerformed(ev);
322
                }
323
                
324
                if(e.getKeyCode() == KeyEvent.VK_ESCAPE && panel.getCancelButton() != null) {
325
                        ActionEvent ev = new ActionEvent(panel.getCancelButton(), 0, null);
326
                        actionPerformed(ev);
327
                }
328
        }
329

    
330
        /*
331
         * (non-Javadoc)
332
         * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
333
         */
334
        public void keyTyped(KeyEvent e) {
335
        }
336
}