Statistics
| Revision:

root / trunk / extensions / extRasterTools-SE / src / org / gvsig / raster / gui / wizards / FileOpenRaster.java @ 20811

History | View | Annotate | Download (12.9 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.RasterProcess;
31
import org.gvsig.raster.UniqueProcessQueue;
32
import org.gvsig.raster.gui.wizards.projection.RasterProjectionActionsDialog;
33
import org.gvsig.raster.gui.wizards.projection.RasterProjectionActionsPanel;
34
import org.gvsig.raster.util.RasterToolsUtil;
35
import org.gvsig.raster.util.RasterUtilities;
36
import org.gvsig.rastertools.RasterModule;
37
import org.gvsig.rastertools.geolocation.ui.GeoLocationOpeningRasterDialog;
38
import org.gvsig.rastertools.overviews.OverviewsProcess;
39
import org.gvsig.rastertools.raw.ui.main.OpenRawFileDefaultView;
40
import org.kxml2.io.KXmlParser;
41
import org.xmlpull.v1.XmlPullParser;
42
import org.xmlpull.v1.XmlPullParserException;
43

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

    
73
        private ArrayList                     lyrsRaster             = new ArrayList();
74
        private RasterProjectionActionsDialog dialog                 = null;
75
        private MapControl                    mapControl             = null;
76
        private boolean                       firstTaskOverview      = true;
77
        private boolean                       execOverview           = false;
78
        
79
        /**
80
         * Constructor de FileOpenRaster
81
         */
82
        public FileOpenRaster() {
83
                getFileFilter().add(new DriverFileFilter());
84
                RasterProjectionActionsPanel.selectAllFiles = false;
85
        }
86

    
87
        /*
88
         * (non-Javadoc)
89
         * @see com.iver.cit.gvsig.addlayer.fileopen.AbstractFileOpen#pre()
90
         */
91
        public void pre() {
92
                firstTaskOverview = true;
93
        }
94
        
95
        /*
96
         * (non-Javadoc)
97
         * @see org.gvsig.raster.gui.wizards.IFileOpen#post(java.io.File[])
98
         */
99
        public File post(File file) {
100
                                
101
                //Si el fichero es raw lanzamos el dialogo de par?metros de raw
102
                if (RasterUtilities.getExtensionFromFileName(file.getAbsolutePath()).equals("raw")) {
103
                        OpenRawFileDefaultView view = new OpenRawFileDefaultView(file.getAbsolutePath());
104
                         file = view.getImageFile();
105
                }
106

    
107
                if(file == null || file.getAbsoluteFile() == null)
108
                        return null;
109
                
110
                //Si el fichero es vrt chequeamos que sea correcto
111
                if (RasterUtilities.getExtensionFromFileName(file.getAbsolutePath()).equals("vrt")) {
112
                        try {
113
                                checkFileVRT(file);
114
                        } catch (FileOpenVRTException e) {
115
                                RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_abrir_fichero") + " " + file.getName() + "\n\n" + PluginServices.getText(this, "informacion_adicional") + ":\n\n  " + e.getMessage(), this, e);
116
                                return null;
117
                        }
118
                }
119
                
120
                try {
121
                        FLyrRasterSE lyrRaster = null;
122
                        lyrRaster = FLyrRasterSE.createLayer(file.getName(), file, null);
123
                        
124
                        // Si hay que generar las overviews por el panel de preferencias
125
                        if (Configuration.getValue("overviews_ask_before_loading", Boolean.FALSE).booleanValue() == true) {
126
                                try {
127
                                        boolean generate = false;
128
                                        for (int i = 0; i < lyrRaster.getFileCount(); i++) {
129
                                                if (lyrRaster.getDataSource().getDataset(i)[0].getOverviewCount(0) == 0) {
130
                                                        generate = true;
131
                                                        break;
132
                                                }
133
                                        }
134
                                        if (generate) {
135
                                                if (firstTaskOverview) {
136
                                                        execOverview = RasterToolsUtil.messageBoxYesOrNot("generar_overviews", this);
137
                                                        firstTaskOverview = false;
138
                                                }
139
                                        
140
                                                if (execOverview) {
141
                                                        RasterProcess process = new OverviewsProcess();
142
                                                        process.addParam("layer", (FLyrRasterSE) lyrRaster);
143
                                                        UniqueProcessQueue.getSingleton().add(process);
144
                                                }
145
                                        }
146
                                } catch (Exception e) {
147
                                        // Si no se puede generar la overview no hacemos nada
148
                                }
149
                        }
150

    
151
                        //Mostramos el cuadro que pide la georreferenciaci?n si la capa no tiene y si la opci?n est? activa en preferencias
152
                        if(RasterModule.askCoordinates) {
153
                                if(        lyrRaster.getFullExtent().getMinX() == 0 && 
154
                                                lyrRaster.getFullExtent().getMinY() == 0 &&
155
                                                lyrRaster.getFullExtent().getMaxX() == ((FLyrRasterSE)lyrRaster).getPxWidth() &&
156
                                                lyrRaster.getFullExtent().getMaxY() == ((FLyrRasterSE)lyrRaster).getPxHeight()) {
157
                                        if(RasterToolsUtil.messageBoxYesOrNot(lyrRaster.getName() + "\n" + PluginServices.getText(this, "layer_without_georref"), null)) {
158
                                                GeoLocationOpeningRasterDialog gld = new GeoLocationOpeningRasterDialog(lyrRaster);
159
                                                PluginServices.getMDIManager().addWindow(gld);
160
                                        }
161
                                }
162
                        }
163
                        
164
                        //Opciones de proyecci?n
165
                        boolean compareProj = Configuration.getValue("general_ask_projection", Boolean.valueOf(false)).booleanValue();
166
                        if(compareProj)
167
                                compareProjections(lyrRaster, getMapControl());
168
                        else
169
                                actionList.add(new Integer(defaultActionLayer));
170
                        
171
                        lyrsRaster.add(lyrRaster);
172
                } catch (LoadLayerException e) {
173
                        RasterToolsUtil.messageBoxError("error_carga_capa", this, e);
174
                }
175
                                
176
                return super.post(file);
177
        }
178

    
179
        /*
180
         * (non-Javadoc)
181
         * @see org.gvsig.raster.gui.wizards.IFileOpen#execute(java.io.File[])
182
         */
183
        public Rectangle2D createLayer(File file, MapControl mapControl, String driverName, IProjection proj) {
184
                FLyrRasterSE lyr = null;
185
                this.mapControl = mapControl;
186
                String layerName = file.getName();
187
                int nLayer = -1;
188

    
189
                // Si hay capas en la lista la buscamos all?
190
                if (lyrsRaster.size() != 0) {
191
                        for (int i = 0; i < lyrsRaster.size(); i++) {
192
                                if (((FLyrRasterSE) lyrsRaster.get(i)).getName().equals(layerName)) {
193
                                        lyr = (FLyrRasterSE) lyrsRaster.get(i);
194
                                        lyr.setProjection(proj);
195
                                        nLayer = i;
196
                                }
197
                        }
198
                }
199
                
200
                // Si no hay capa la cargamos
201
                if (lyr == null) {
202
                        try {
203
                                lyr = FLyrRasterSE.createLayer(layerName, file, proj);
204
                                layerActions(defaultActionLayer, lyr);
205
                        } catch (LoadLayerException e) {
206
                                RasterToolsUtil.messageBoxError("error_carga_capa", this, e);
207
                        }
208
                }
209

    
210
                if (lyr != null) {
211
                        if (nLayer >= 0) {
212
                                Object obj = actionList.get(nLayer);
213
                                if (obj != null && obj instanceof Integer)
214
                                        layerActions(((Integer) obj).intValue(), lyr);
215
                        } else
216
                                layerActions(defaultActionLayer, lyr);
217
                        return lyr.getFullExtent();
218
                }
219

    
220
                return null;
221
        }
222
        
223
        /**
224
         * Compara las proyecciones de la vista y la capa. En caso de ser diferentes
225
         * pregunta por las opciones a realizar.
226
         * @param lyr
227
         * @param mapControl
228
         */
229
        private void compareProjections(FLyrRasterSE lyr, MapControl mapControl) {
230
                IProjection viewProj = mapControl.getProjection();
231
                IProjection lyrProj = lyr.readProjection();
232
                if(lyrProj == null) {
233
                        actionList.add(new Integer(defaultActionLayer));
234
                        return;
235
                }
236
                if(viewProj == null) {
237
                        mapControl.setProjection(lyrProj);
238
                        actionList.add(new Integer(defaultActionLayer));
239
                        return;
240
                }
241
                
242
                /*
243
                 * Si las proyecciones de vista y raster son distintas se lanza el dialogo de selecci?n de
244
                 * opciones. Este dialogo solo se lanza en caso de que el checkbox de aplicar a todos los 
245
                 * ficheros no haya sido marcado. En este caso para el resto de ficheros de esa selecci?n 
246
                 * se har? la misma acci?n que se hizo para el primero.
247
                 */
248
                if(!viewProj.getAbrev().endsWith(lyrProj.getAbrev())) {
249
                        if(!RasterProjectionActionsPanel.selectAllFiles) 
250
                                dialog = new RasterProjectionActionsDialog(lyr.getName());
251
                        int select = defaultActionLayer;
252
                        if(dialog != null)
253
                                select = dialog.getRasterProjectionActionsPanel().getSelection();
254
                        actionList.add(new Integer(select));
255
                        return;
256
                } 
257
                actionList.add(new Integer(defaultActionLayer));
258
        }
259

    
260
        /**
261
         * Acciones posibles cuando la proyecci?n de la capa es distinta de la de
262
         * la vista.
263
         * @param action Valor de la acci?n. Est? representado en RasterProjectionActionsPanel
264
         */
265
        private void layerActions(int action, FLyrRasterSE lyr) {
266
                //Cambia la proyecci?n de la vista y carga la capa
267
                if(action == CHANGE_VIEW_PROJECTION) {
268
                        if(lyr != null) {
269
                                mapControl.setProjection(lyr.readProjection());
270
                                lyr.setVisible(true);
271
                                mapControl.getMapContext().getLayers().addLayer(lyr);
272
                        }
273
                }
274
                //Ignora la proyecci?n de la capa y la carga
275
                if(action == IGNORE) {
276
                        if(lyr != null) {
277
                                lyr.setVisible(true);
278
                                mapControl.getMapContext().getLayers().addLayer(lyr);
279
                        }
280
                }
281
                //Reproyectando
282
                if(action == REPROJECT) {
283
                }
284
                //No carga
285
                if(action == NOTLOAD) {
286
                }
287
        }
288
        
289
        /**
290
         * Comprueba si un fichero VRT esta en correcto estado, en caso contrario
291
         * lanza una excepcion indicando el tipo de error en la apertura.
292
         *
293
         * @param file
294
         * @throws FileOpenVRTException
295
         */
296
        private void checkFileVRT(File file) throws FileOpenVRTException {
297
                KXmlParser parser = new KXmlParser();
298

    
299
                FileReader fileReader = null;
300
                try {
301
                        fileReader = new FileReader(file);
302
                        parser.setInput(fileReader);
303

    
304
                        parser.nextTag();
305

    
306
                        parser.require(XmlPullParser.START_TAG, null, "VRTDataset");
307

    
308
                        while (parser.nextTag () != XmlPullParser.END_TAG) {
309
                                parser.require(XmlPullParser.START_TAG, null, "VRTRasterBand");
310

    
311
                                String name;
312
                                while (parser.nextTag() != XmlPullParser.END_TAG) {
313
                                        parser.require(XmlPullParser.START_TAG, null, null);
314
                                        boolean relativePath = false;
315
                                        for (int i=0; i<parser.getAttributeCount(); i++) {
316
                                                if (parser.getAttributeName(i).equals("relativetoVRT") &&
317
                                                                parser.getAttributeValue(i).equals("1"))
318
                                                        relativePath = true;
319
                                        }
320
                                        name = parser.getName();
321
                                        String nameFile = parser.nextText();
322
                                        if (name.equals("SourceFilename")) {
323
                                                if (relativePath)
324
                                                        nameFile = file.getParent() + File.separator + nameFile;
325
                                                File tryFile = new File(nameFile);
326
                                                if (!tryFile.exists())
327
                                                        throw new FileOpenVRTException(PluginServices.getText(this, "no_existe_fichero") + " " + nameFile);
328
                                        }
329
                                        parser.require(XmlPullParser.END_TAG, null, name);
330
                                }
331

    
332
                                parser.require(XmlPullParser.END_TAG, null, "VRTRasterBand");
333
                        }
334
                        parser.require(XmlPullParser.END_TAG, null, "VRTDataset");
335
                        parser.next();
336
                        parser.require(XmlPullParser.END_DOCUMENT, null, null);
337
                } catch (XmlPullParserException e) {
338
                        throw new FileOpenVRTException(PluginServices.getText(this, "el_fichero")+ " " + file.getName().toString() + " " + PluginServices.getText(this, "esta_formato_desconocido"));
339
                } catch (IOException e) {
340
                        throw new FileOpenVRTException(PluginServices.getText(this, "no_puede_abrir_fichero") + " " + file.getName().toString());
341
                } finally {
342
                        if (fileReader != null)
343
                                try {
344
                                        fileReader.close();
345
                                } catch (IOException e) {
346
                                }
347
                }
348
        }
349
        
350
        /**
351
         * Obtiene el mapControl. La llamada createLayer recibe el MapControl por par?metro pero
352
         * ni pre() ni post() pueden tener acceso al MapControl a no ser que lo busquen ellos. 
353
         * @return MapControl
354
         */
355
        public MapControl getMapControl() {
356
                MapControl mapControl = null;
357
                IWindow[] w = PluginServices.getMDIManager().getAllWindows();
358

    
359
                // Obtiene la primera vista activa
360
                for (int i = 0; i < w.length; i++) {
361
                        if (w[i] instanceof BaseView && w[i].equals(PluginServices.getMDIManager().getActiveWindow()))
362
                                mapControl = ((BaseView) w[i]).getMapControl();
363
                }
364
                
365
                // Si no hay ninguna activa obtiene la primera vista aunque no est? activa
366
                if (mapControl == null) {
367
                        for (int i = 0; i < w.length; i++) {
368
                                if (w[i] instanceof BaseView)
369
                                        mapControl = ((BaseView) w[i]).getMapControl();
370
                        }
371
                }
372

    
373
                return mapControl;
374
        }
375
}