Statistics
| Revision:

root / branches / v2_0_0_prep / extensions / extRasterTools-SE / src / org / gvsig / rastertools / geolocation / listener / GeoLocationPanelListener.java @ 31496

History | View | Annotate | Download (12.4 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 org.gvsig.andami.PluginServices;
35
import org.gvsig.app.project.documents.view.gui.AbstractViewPanel;
36
import org.gvsig.fmap.geom.GeometryLocator;
37
import org.gvsig.fmap.geom.GeometryManager;
38
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
39
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
40
import org.gvsig.fmap.geom.primitive.Envelope;
41
import org.gvsig.fmap.mapcontext.ViewPort;
42
import org.gvsig.fmap.mapcontrol.MapControl;
43
import org.gvsig.gui.beans.datainput.DataInputContainerListener;
44
import org.gvsig.gui.beans.swing.JFileChooser;
45
import org.gvsig.raster.dataset.serializer.RmfSerializerException;
46
import org.gvsig.raster.datastruct.Extent;
47
import org.gvsig.raster.util.ExtendedFileFilter;
48
import org.gvsig.raster.util.Historical;
49
import org.gvsig.raster.util.RasterToolsUtil;
50
import org.gvsig.rastertools.geolocation.ui.GeoLocationDialog;
51
import org.gvsig.rastertools.geolocation.ui.GeoLocationOpeningRasterPanel;
52
import org.gvsig.rastertools.geolocation.ui.GeoLocationPanel;
53
import org.gvsig.rastertools.geolocation.ui.GeolocationBaseClassPanel;
54
import org.slf4j.Logger;
55
import org.slf4j.LoggerFactory;
56

    
57

    
58
/**
59
 * Listener para el panel de geolocalizaci?n.
60
 * @version 31/07/2007
61
 * @author Nacho Brodin (nachobrodin@gmail.com)
62
 *
63
 */
64
public class GeoLocationPanelListener implements ActionListener, DataInputContainerListener, KeyListener {
65
        private static final GeometryManager         geomManager                         = GeometryLocator.getGeometryManager();
66
        private static final Logger                         logger                                = LoggerFactory.getLogger(GeoLocationPanelListener.class);
67
        private GeolocationBaseClassPanel                panel                                         = null;
68
        private boolean                             enableValueChangeEvent         = false;
69
        private GeoLocationDialog               dialog                  = null;
70

    
71
        /**
72
         * Crea un nuevo <code>GeoLocationPanelListener</code>
73
         * @param panel
74
         */
75
        public GeoLocationPanelListener(GeolocationBaseClassPanel panel, GeoLocationDialog dialog) {
76
                this.dialog = dialog;
77
                this.panel = panel;
78
        }
79

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

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

    
122
                if(e.getSource() == panel.getCancelButton())
123
                        PluginServices.getMDIManager().closeWindow(((GeoLocationOpeningRasterPanel)panel).getDialog());
124

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

    
129
                AffineTransform at = null;
130

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

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

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

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

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

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

    
161
                        int returnVal = chooser.showOpenDialog(panel);
162
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
163
                                String fName = chooser.getSelectedFile().toString();
164
                                at = readTfw(fName);
165
                        }
166
                        JFileChooser.setLastPath("GEO_LOCATION_PANEL_LISTENER", chooser.getSelectedFile());
167
                }
168

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

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

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

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

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

    
239
                widthPxImg = (panel.getLayer()).getPxWidth();
240
                heightPxImg = (panel.getLayer()).getPxHeight();
241

    
242
                if(vp == null || vp.getAdjustedExtent() == null) {
243
                        vp = new ViewPort(null);
244
                        Envelope r2d;
245
                        try {
246
                                r2d = geomManager.createEnvelope(0, 0, widthPxImg,
247
                                                heightPxImg, SUBTYPES.GEOM2D);
248
                                vp.setEnvelope(r2d);
249
                        } catch (CreateEnvelopeException e) {
250
                                logger.error("Error creating the envelope", e);
251
                        }                        
252
                        tempExtent = new Extent(0, 0, widthPxImg, heightPxImg);
253
                } else{
254
                        Envelope env=vp.getAdjustedExtent();
255
                        tempExtent = new Extent(new Rectangle2D.Double(env.getMinimum(0),env.getMinimum(1),env.getLength(0),env.getLength(1)));
256
                }
257

    
258
                double ulX = 0D, ulY = 0D, lrX = 0D, lrY = 0D;
259
                if(widthPxImg > heightPxImg) {
260
                        double widthView = tempExtent.maxX() - tempExtent.minX();
261
                        ulX = tempExtent.minX() + (widthView / 4);
262
                        lrX = ulX + (widthView / 2);
263
                        double newAlto = ((heightPxImg * (widthView / 2)) / widthPxImg);
264
                        double centroY = tempExtent.minY()+((tempExtent.maxY() - tempExtent.minY())/2);
265
                        ulY = centroY - (newAlto / 2);
266
                        lrY = centroY + (newAlto / 2);
267
                } else {
268
                        double heightView = tempExtent.maxY() - tempExtent.minY();
269
                        ulY = tempExtent.minY() + (heightView / 4);
270
                        lrY = ulY + (heightView / 2);
271
                        double newAncho = ((widthPxImg * (heightView / 2)) / heightPxImg);
272
                        double centroX = tempExtent.minX()+((tempExtent.maxX() - tempExtent.minX())/2);
273
                        ulX = centroX - (newAncho / 2);
274
                        lrX = centroX + (newAncho / 2);
275
                }
276
                return new Extent(ulX, ulY, lrX, lrY);
277
        }
278

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

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

    
321
        }
322

    
323
        /**
324
         * Capturamos el evento de pulsar la tecla Enter y cancel. Cuando pulsamos enter
325
         * ejecuta el evento del bot?n de aplicar y cuando pulsamos cancel cerramos el cuadro
326
         * y no hacemos nada.
327
         */
328
        public void keyReleased(KeyEvent e) {
329
                if(e.getKeyCode() == KeyEvent.VK_ENTER) {
330
                        ActionEvent ev = new ActionEvent(panel.getApplyButton(), 0, null);
331
                        actionPerformed(ev);
332
                }
333

    
334
                if(e.getKeyCode() == KeyEvent.VK_ESCAPE && panel.getCancelButton() != null) {
335
                        ActionEvent ev = new ActionEvent(panel.getCancelButton(), 0, null);
336
                        actionPerformed(ev);
337
                }
338
        }
339

    
340
        /*
341
         * (non-Javadoc)
342
         * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
343
         */
344
        public void keyTyped(KeyEvent e) {
345
        }
346
}