Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRasterTools-SE / src / org / gvsig / raster / gui / wizards / FileOpenRaster.java @ 20043

History | View | Annotate | Download (11.6 KB)

1
/* 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.raster.gui.wizards;
20

    
21
import java.awt.geom.Rectangle2D;
22
import java.io.File;
23
import java.io.FileReader;
24
import java.io.IOException;
25
import java.util.ArrayList;
26

    
27
import org.cresques.cts.IProjection;
28
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
29
import org.gvsig.raster.Configuration;
30
import org.gvsig.raster.gui.wizards.projection.RasterProjectionActionsDialog;
31
import org.gvsig.raster.gui.wizards.projection.RasterProjectionActionsPanel;
32
import org.gvsig.raster.util.RasterToolsUtil;
33
import org.gvsig.raster.util.RasterUtilities;
34
import org.gvsig.rastertools.RasterModule;
35
import org.gvsig.rastertools.geolocation.ui.GeoLocationOpeningRasterDialog;
36
import org.gvsig.rastertools.raw.ui.main.OpenRawFileDefaultView;
37
import org.kxml2.io.KXmlParser;
38
import org.xmlpull.v1.XmlPullParser;
39
import org.xmlpull.v1.XmlPullParserException;
40

    
41
import com.iver.andami.PluginServices;
42
import com.iver.andami.ui.mdiManager.IWindow;
43
import com.iver.cit.gvsig.addlayer.fileopen.AbstractFileOpen;
44
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
45
import com.iver.cit.gvsig.fmap.MapControl;
46
import com.iver.cit.gvsig.project.documents.view.gui.BaseView;
47
/**
48
 * Clase que indicar? que ficheros puede tratar al panel de apertura de
49
 * ficheros
50
 *
51
 * @version 04/09/2007
52
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
53
 */
54
public class FileOpenRaster extends AbstractFileOpen {
55
        public static int                         CHANGE_VIEW_PROJECTION = 0;
56
        public static int                         REPROJECT              = 1;
57
        public static int                         IGNORE                 = 2;
58
        public static int                         NOTLOAD                = 3;
59
        /**
60
         * Acci?n a realizar con la capa. Por defecto ignora la proyecci?n y la carga en la vista
61
         * pero esta opci?n puede ser cambiada por el usuario desde el dialogo.
62
         */
63
        public static int                         defaultActionLayer     = IGNORE;
64
        /**
65
         * Lista de acciones. Una por capa a a?adir.
66
         */
67
        private ArrayList                         actionList             = new ArrayList();;
68
        
69
        private ArrayList                         lyrsRaster             = new ArrayList();
70
        private RasterProjectionActionsDialog     dialog                 = null;
71
        private MapControl                        mapControl             = null;
72
        
73
        /**
74
         * Constructor de FileOpenRaster
75
         */
76
        public FileOpenRaster() {
77
                getFileFilter().add(new DriverFileFilter());
78
                RasterProjectionActionsPanel.selectAllFiles = false;
79
        }
80

    
81
        /*
82
         * (non-Javadoc)
83
         * @see org.gvsig.raster.gui.wizards.IFileOpen#post(java.io.File[])
84
         */
85
        public File post(File file) {
86
                                
87
                //Si el fichero es raw lanzamos el dialogo de par?metros de raw
88
                if (RasterUtilities.getExtensionFromFileName(file.getAbsolutePath()).equals("raw")) {
89
                        OpenRawFileDefaultView view = new OpenRawFileDefaultView(file.getAbsolutePath());
90
                         file = view.getImageFile();
91
                }
92

    
93
                //Si el fichero es vrt chequeamos que sea correcto
94
                if (RasterUtilities.getExtensionFromFileName(file.getAbsolutePath()).equals("vrt")) {
95
                        try {
96
                                checkFileVRT(file);
97
                        } catch (FileOpenVRTException e) {
98
                                RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_abrir_fichero") + " " + file.getName() + "\n\n" + PluginServices.getText(this, "informacion_adicional") + ":\n\n  " + e.getMessage(), this, e);
99
                                return null;
100
                        }
101
                }
102
                
103
                try {
104
                        FLyrRasterSE lyrRaster = null;
105
                        lyrRaster = FLyrRasterSE.createLayer(file.getName(), file, null);
106
                        
107
                        //Mostramos el cuadro que pide la georreferenciaci?n si la capa no tiene y si la opci?n est? activa en preferencias
108
                        if(RasterModule.askCoordinates) {
109
                                if(        lyrRaster.getFullExtent().getMinX() == 0 && 
110
                                                lyrRaster.getFullExtent().getMinY() == 0 &&
111
                                                lyrRaster.getFullExtent().getMaxX() == ((FLyrRasterSE)lyrRaster).getPxWidth() &&
112
                                                lyrRaster.getFullExtent().getMaxY() == ((FLyrRasterSE)lyrRaster).getPxHeight()) {
113
                                        if(RasterToolsUtil.messageBoxYesOrNot(lyrRaster.getName() + "\n" + PluginServices.getText(this, "layer_without_georref"), null)) {
114
                                                GeoLocationOpeningRasterDialog gld = new GeoLocationOpeningRasterDialog(lyrRaster);
115
                                                PluginServices.getMDIManager().addWindow(gld);
116
                                        }
117
                                }
118
                        }
119
                        
120
                        //Opciones de proyecci?n
121
                        boolean compareProj = Configuration.getValue("general_ask_projection", Boolean.valueOf(false)).booleanValue();
122
                        if(compareProj)
123
                                compareProjections(lyrRaster, getMapControl());
124
                        else
125
                                actionList.add(new Integer(defaultActionLayer));
126
                        
127
                        lyrsRaster.add(lyrRaster);
128
                } catch (LoadLayerException e) {
129
                        RasterToolsUtil.messageBoxError("error_carga_capa", this, e);
130
                }
131
                                
132
                return super.post(file);
133
        }
134

    
135
        /*
136
         * (non-Javadoc)
137
         * @see org.gvsig.raster.gui.wizards.IFileOpen#execute(java.io.File[])
138
         */
139
        public Rectangle2D createLayer(File file, MapControl mapControl, String driverName, IProjection proj) {
140
                FLyrRasterSE lyr = null;
141
                this.mapControl = mapControl;
142
                String layerName = file.getName();
143
                int nLayer = -1;
144
                
145
                //Si hay capas en la lista la buscamos all?
146
                if(lyrsRaster.size() != 0) {   
147
                        for (int i = 0; i < lyrsRaster.size(); i++) {
148
                                if(((FLyrRasterSE)lyrsRaster.get(i)).getName().equals(layerName)) {
149
                                        lyr = (FLyrRasterSE)lyrsRaster.get(i);
150
                                        lyr.setProjection(proj);
151
                                        nLayer = i;
152
                                }
153
                        }
154
                }
155
                
156
                //Si no hay capa la cargamos
157
                if(lyr == null) {
158
                        try {
159
                                lyr = FLyrRasterSE.createLayer(layerName, file, proj);
160
                                layerActions(defaultActionLayer, lyr);
161
                        } catch (LoadLayerException e) {
162
                                RasterToolsUtil.messageBoxError("error_carga_capa", this, e);
163
                        }
164
                }
165
                
166
                if(lyr != null) {
167
                        if(nLayer >= 0) {
168
                                Object obj = actionList.get(nLayer);
169
                                if(obj != null && obj instanceof Integer)
170
                                        layerActions(((Integer)obj).intValue(), lyr);
171
                        } else
172
                                layerActions(defaultActionLayer, lyr);
173
                        return lyr.getFullExtent();
174
                }
175
                                                
176
                return null;
177
        }
178
        
179
        /**
180
         * Compara las proyecciones de la vista y la capa. En caso de ser diferentes
181
         * pregunta por las opciones a realizar.
182
         * @param lyr
183
         * @param mapControl
184
         */
185
        private void compareProjections(FLyrRasterSE lyr, MapControl mapControl) {
186
                IProjection viewProj = mapControl.getProjection();
187
                IProjection lyrProj = lyr.readProjection();
188
                if(lyrProj == null) {
189
                        actionList.add(new Integer(defaultActionLayer));
190
                        return;
191
                }
192
                if(viewProj == null) {
193
                        mapControl.setProjection(lyrProj);
194
                        actionList.add(new Integer(defaultActionLayer));
195
                        return;
196
                }
197
                
198
                /*
199
                 * Si las proyecciones de vista y raster son distintas se lanza el dialogo de selecci?n de
200
                 * opciones. Este dialogo solo se lanza en caso de que el checkbox de aplicar a todos los 
201
                 * ficheros no haya sido marcado. En este caso para el resto de ficheros de esa selecci?n 
202
                 * se har? la misma acci?n que se hizo para el primero.
203
                 */
204
                if(!viewProj.getAbrev().endsWith(lyrProj.getAbrev())) {
205
                        if(!RasterProjectionActionsPanel.selectAllFiles) 
206
                                dialog = new RasterProjectionActionsDialog(lyr.getName());
207
                        int select = defaultActionLayer;
208
                        if(dialog != null)
209
                                select = dialog.getRasterProjectionActionsPanel().getSelection();
210
                        actionList.add(new Integer(select));
211
                        return;
212
                } 
213
                actionList.add(new Integer(defaultActionLayer));
214
        }
215

    
216
        /**
217
         * Acciones posibles cuando la proyecci?n de la capa es distinta de la de
218
         * la vista.
219
         * @param action Valor de la acci?n. Est? representado en RasterProjectionActionsPanel
220
         */
221
        private void layerActions(int action, FLyrRasterSE lyr) {
222
                //Cambia la proyecci?n de la vista y carga la capa
223
                if(action == CHANGE_VIEW_PROJECTION) {
224
                        if(lyr != null) {
225
                                mapControl.setProjection(lyr.readProjection());
226
                                lyr.setVisible(true);
227
                                mapControl.getMapContext().getLayers().addLayer(lyr);
228
                        }
229
                }
230
                //Ignora la proyecci?n de la capa y la carga
231
                if(action == IGNORE) {
232
                        if(lyr != null) {
233
                                lyr.setVisible(true);
234
                                mapControl.getMapContext().getLayers().addLayer(lyr);
235
                        }
236
                }
237
                //Reproyectando
238
                if(action == REPROJECT) {
239
                }
240
                //No carga
241
                if(action == NOTLOAD) {
242
                }
243
        }
244
        
245
        /**
246
         * Comprueba si un fichero VRT esta en correcto estado, en caso contrario
247
         * lanza una excepcion indicando el tipo de error en la apertura.
248
         *
249
         * @param file
250
         * @throws FileOpenVRTException
251
         */
252
        private void checkFileVRT(File file) throws FileOpenVRTException {
253
                KXmlParser parser = new KXmlParser();
254

    
255
                FileReader fileReader = null;
256
                try {
257
                        fileReader = new FileReader(file);
258
                        parser.setInput(fileReader);
259

    
260
                        parser.nextTag();
261

    
262
                        parser.require(XmlPullParser.START_TAG, null, "VRTDataset");
263

    
264
                        while (parser.nextTag () != XmlPullParser.END_TAG) {
265
                                parser.require(XmlPullParser.START_TAG, null, "VRTRasterBand");
266

    
267
                                String name;
268
                                while (parser.nextTag() != XmlPullParser.END_TAG) {
269
                                        parser.require(XmlPullParser.START_TAG, null, null);
270
                                        boolean relativePath = false;
271
                                        for (int i=0; i<parser.getAttributeCount(); i++) {
272
                                                if (parser.getAttributeName(i).equals("relativetoVRT") &&
273
                                                                parser.getAttributeValue(i).equals("1"))
274
                                                        relativePath = true;
275
                                        }
276
                                        name = parser.getName();
277
                                        String nameFile = parser.nextText();
278
                                        if (name.equals("SourceFilename")) {
279
                                                if (relativePath)
280
                                                        nameFile = file.getParent() + File.separator + nameFile;
281
                                                File tryFile = new File(nameFile);
282
                                                if (!tryFile.exists())
283
                                                        throw new FileOpenVRTException(PluginServices.getText(this, "no_existe_fichero") + " " + nameFile);
284
                                        }
285
                                        parser.require(XmlPullParser.END_TAG, null, name);
286
                                }
287

    
288
                                parser.require(XmlPullParser.END_TAG, null, "VRTRasterBand");
289
                        }
290
                        parser.require(XmlPullParser.END_TAG, null, "VRTDataset");
291
                        parser.next();
292
                        parser.require(XmlPullParser.END_DOCUMENT, null, null);
293
                } catch (XmlPullParserException e) {
294
                        throw new FileOpenVRTException(PluginServices.getText(this, "el_fichero")+ " " + file.getName().toString() + " " + PluginServices.getText(this, "esta_formato_desconocido"));
295
                } catch (IOException e) {
296
                        throw new FileOpenVRTException(PluginServices.getText(this, "no_puede_abrir_fichero") + " " + file.getName().toString());
297
                } finally {
298
                        if (fileReader != null)
299
                                try {
300
                                        fileReader.close();
301
                                } catch (IOException e) {
302
                                }
303
                }
304
        }
305
        
306
        /**
307
         * Obtiene el mapControl. La llamada createLayer recibe el MapControl por par?metro pero
308
         * ni pre() ni post() pueden tener acceso al MapControl a no ser que lo busquen ellos. 
309
         * @return MapControl
310
         */
311
        public MapControl getMapControl() {
312
                MapControl mapControl = null;
313
                IWindow[] w = PluginServices.getMDIManager().getAllWindows();
314

    
315
                // Obtiene la primera vista activa
316
                for (int i = 0; i < w.length; i++) {
317
                        if (w[i] instanceof BaseView && w[i].equals(PluginServices.getMDIManager().getActiveWindow()))
318
                                mapControl = ((BaseView) w[i]).getMapControl();
319
                }
320
                
321
                // Si no hay ninguna activa obtiene la primera vista aunque no est? activa
322
                if (mapControl == null) {
323
                        for (int i = 0; i < w.length; i++) {
324
                                if (w[i] instanceof BaseView)
325
                                        mapControl = ((BaseView) w[i]).getMapControl();
326
                        }
327
                }
328

    
329
                return mapControl;
330
        }
331
}