Statistics
| Revision:

root / branches / v2_0_0_prep / extensions / extRasterTools-SE / src / org / gvsig / raster / gui / wizards / FileOpenRaster.java @ 31496

History | View | Annotate | Download (13.5 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.io.File;
22
import java.io.FileReader;
23
import java.io.IOException;
24
import java.util.ArrayList;
25

    
26
import javax.swing.filechooser.FileFilter;
27

    
28
import org.cresques.cts.IProjection;
29
import org.gvsig.andami.PluginServices;
30
import org.gvsig.andami.ui.mdiManager.IWindow;
31
import org.gvsig.app.project.documents.view.gui.AbstractViewPanel;
32
import org.gvsig.app.project.documents.view.gui.DefaultViewPanel;
33
import org.gvsig.fmap.geom.primitive.Envelope;
34
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
35
import org.gvsig.fmap.mapcontrol.MapControl;
36
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
37
import org.gvsig.raster.Configuration;
38
import org.gvsig.raster.gui.wizards.projection.RasterProjectionActionsDialog;
39
import org.gvsig.raster.gui.wizards.projection.RasterProjectionActionsPanel;
40
import org.gvsig.raster.util.RasterToolsUtil;
41
import org.gvsig.raster.util.RasterUtilities;
42
import org.gvsig.rastertools.RasterModule;
43
import org.gvsig.rastertools.geolocation.ui.GeoLocationOpeningRasterDialog;
44
import org.gvsig.rastertools.raw.ui.main.OpenRawFileDefaultView;
45
import org.gvsig.rastertools.reproject.ui.LayerReprojectPanel;
46
import org.kxml2.io.KXmlParser;
47
import org.xmlpull.v1.XmlPullParser;
48
import org.xmlpull.v1.XmlPullParserException;
49

    
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

    
77
        /**
78
         * Constructor de FileOpenRaster
79
         */
80
        public FileOpenRaster() {
81
                getFileFilter().add(new DriverFileFilter());
82
                RasterProjectionActionsPanel.selectAllFiles = false;
83
        }
84

    
85
        /*
86
         * (non-Javadoc)
87
         * @see org.gvsig.raster.gui.wizards.IFileOpen#post(java.io.File[])
88
         */
89
        public File post(File file) {
90

    
91
                //Si el fichero es raw lanzamos el dialogo de par?metros de raw
92
                if (RasterUtilities.getExtensionFromFileName(file.getAbsolutePath()).equals("raw")) {
93
                        OpenRawFileDefaultView view = new OpenRawFileDefaultView(file.getAbsolutePath());
94
                         file = view.getImageFile();
95
                }
96

    
97
                if(file == null || file.getAbsoluteFile() == null) {
98
                        return null;
99
                }
100

    
101
                //Si el fichero es vrt chequeamos que sea correcto
102
                if (RasterUtilities.getExtensionFromFileName(file.getAbsolutePath()).equals("vrt")) {
103
                        try {
104
                                checkFileVRT(file);
105
                        } catch (FileOpenVRTException e) {
106
                                RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_abrir_fichero") + " " + file.getName() + "\n\n" + PluginServices.getText(this, "informacion_adicional") + ":\n\n  " + e.getMessage(), this, e);
107
                                return null;
108
                        }
109
                }
110

    
111
                try {
112
                        FLyrRasterSE lyrRaster = null;
113
                        lyrRaster = FLyrRasterSE.createLayer(file.getName(), file, null);
114

    
115
                        // Si hay que generar las overviews por el panel de preferencias
116
//                        if (Configuration.getValue("overviews_ask_before_loading", Boolean.FALSE).booleanValue() == true) {
117
//                                try {
118
//                                        boolean generate = false;
119
//                                        for (int i = 0; i < lyrRaster.getFileCount(); i++) {
120
//                                                if (lyrRaster.getDataSource().getDataset(i)[0].getOverviewCount(0) == 0) {
121
//                                                        generate = true;
122
//                                                        break;
123
//                                                }
124
//                                        }
125
//                                        if (generate) {
126
//                                                if (firstTaskOverview) {
127
//                                                        execOverview = RasterToolsUtil.messageBoxYesOrNot("generar_overviews", this);
128
//                                                        firstTaskOverview = false;
129
//                                                }
130
//
131
//                                                if (execOverview) {
132
//                                                        RasterProcess process = new OverviewsProcess();
133
//                                                        process.setCancelable(false);
134
//                                                        process.addParam("layer", (FLyrRasterSE) lyrRaster);
135
//                                                        UniqueProcessQueue.getSingleton().add(process);
136
//                                                }
137
//                                        }
138
//                                } catch (Exception e) {
139
//                                        // Si no se puede generar la overview no hacemos nada
140
//                                }
141
//                        }
142

    
143
                        //Mostramos el cuadro que pide la georreferenciaci?n si la capa no tiene y si la opci?n est? activa en preferencias
144
                        if(RasterModule.askCoordinates) {
145
                                if(        lyrRaster.getFullEnvelope().getMinimum(0) == 0 &&
146
                                                lyrRaster.getFullEnvelope().getMinimum(1) == 0 &&
147
                                                lyrRaster.getFullEnvelope().getMaximum(0) == (lyrRaster).getPxWidth() &&
148
                                                lyrRaster.getFullEnvelope().getMaximum(1) == (lyrRaster).getPxHeight()) {
149
                                        if(RasterToolsUtil.messageBoxYesOrNot(lyrRaster.getName() + "\n" + PluginServices.getText(this, "layer_without_georref"), null)) {
150
                                                GeoLocationOpeningRasterDialog gld = new GeoLocationOpeningRasterDialog(lyrRaster);
151
                                                PluginServices.getMDIManager().addWindow(gld);
152
                                        }
153
                                }
154
                        }
155

    
156
                        //Opciones de proyecci?n
157
                        boolean compareProj = Configuration.getValue("general_ask_projection", Boolean.valueOf(false)).booleanValue();
158
                        if(compareProj) {
159
                                compareProjections(lyrRaster);
160
                        } else {
161
                                actionList.add(new Integer(defaultActionLayer));
162
                        }
163

    
164
                        lyrsRaster.add(lyrRaster);
165
                } catch (LoadLayerException e) {
166
                        RasterToolsUtil.messageBoxError("error_carga_capa", this, e);
167
                }
168

    
169
                return super.post(file);
170
        }
171

    
172

    
173
        /*
174
         * (non-Javadoc)
175
         * @see org.gvsig.raster.gui.wizards.IFileOpen#execute(java.io.File[])
176
         */
177
        public Envelope createLayer(File file, MapControl mapControl,
178
                        FileFilter driverName, IProjection proj) {
179
                this.mapControl = mapControl;
180
                FLyrRasterSE lyr = null;
181
                String layerName = file.getName();
182
                int nLayer = -1;
183

    
184
                // Si hay capas en la lista la buscamos all?
185
                if (lyrsRaster.size() != 0) {
186
                        for (int i = 0; i < lyrsRaster.size(); i++) {
187
                                if (((FLyrRasterSE) lyrsRaster.get(i)).getName().equals(layerName)) {
188
                                        lyr = (FLyrRasterSE) lyrsRaster.get(i);
189
                                        lyr.setProjection(proj);
190
                                        nLayer = i;
191
                                }
192
                        }
193
                }
194

    
195
                // Si no hay capa la cargamos
196
                if (lyr == null) {
197
                        try {
198
                                lyr = FLyrRasterSE.createLayer(layerName, file, proj);
199
                                layerActions(defaultActionLayer, lyr);
200
                        } catch (LoadLayerException e) {
201
                                RasterToolsUtil.messageBoxError("error_carga_capa", this, e);
202
                        }
203
                }
204

    
205
                if (lyr != null) {
206
                        boolean actionsAdded = false;
207
                        if ((nLayer >= 0) && (nLayer < actionList.size())) {
208
                                Object obj = actionList.get(nLayer);
209
                                if (obj != null && obj instanceof Integer) {
210
                                        actionsAdded = true;
211
                                        layerActions(((Integer) obj).intValue(), lyr);
212
                                }
213
                        }
214
                        if (!actionsAdded) {
215
                                layerActions(defaultActionLayer, lyr);
216
                        }
217
                        return lyr.getFullEnvelope();
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) {
230
                IProjection viewProj = getMapControl().getProjection();
231
                IProjection lyrProj = lyr.readProjection();
232
                if (lyrProj == null) {
233
                        lyr.setProjection(viewProj);
234
                        actionList.add(new Integer(defaultActionLayer));
235
                        return;
236
                }
237
                if(viewProj == null) {
238
                        getMapControl().setProjection(lyrProj);
239
                        actionList.add(new Integer(defaultActionLayer));
240
                        return;
241
                }
242

    
243
                /*
244
                 * Si las proyecciones de vista y raster son distintas se lanza el dialogo de selecci?n de
245
                 * opciones. Este dialogo solo se lanza en caso de que el checkbox de aplicar a todos los
246
                 * ficheros no haya sido marcado. En este caso para el resto de ficheros de esa selecci?n
247
                 * se har? la misma acci?n que se hizo para el primero.
248
                 */
249
                if (!viewProj.getAbrev().endsWith(lyrProj.getAbrev())) {
250
                        boolean showDialog = false;
251
                        if (!RasterProjectionActionsPanel.selectAllFiles) {
252
                                showDialog = true;
253
                        }
254

    
255
                        if (showDialog) {
256
                                dialog = new RasterProjectionActionsDialog(lyr);
257
                        } else {
258
                                if (defaultActionLayer == FileOpenRaster.REPROJECT && !lyr.isReproyectable()) {
259
                                        dialog = new RasterProjectionActionsDialog(lyr);
260
                                }
261
                        }
262
                        int select = defaultActionLayer;
263
                        if (dialog != null) {
264
                                select = dialog.getRasterProjectionActionsPanel().getSelection();
265
                        }
266

    
267
                        actionList.add(new Integer(select));
268
                        return;
269
                }
270
                actionList.add(new Integer(defaultActionLayer));
271
        }
272

    
273
        /**
274
         * Acciones posibles cuando la proyecci?n de la capa es distinta de la de
275
         * la vista.
276
         * @param action Valor de la acci?n. Est? representado en RasterProjectionActionsPanel
277
         */
278
        private void layerActions(int action, FLyrRasterSE lyr) {
279
                // Cambia la proyecci?n de la vista y carga la capa
280
                if (action == CHANGE_VIEW_PROJECTION) {
281
                        if (lyr != null) {
282
                                getMapControl().setProjection(lyr.readProjection());
283
                                lyr.setVisible(true);
284
                                getMapControl().getMapContext().getLayers().addLayer(lyr);
285
                        }
286
                }
287

    
288
                // Ignora la proyecci?n de la capa y la carga
289
                if (action == IGNORE) {
290
                        if (lyr != null) {
291
                                lyr.setVisible(true);
292
                                getMapControl().getMapContext().getLayers().addLayer(lyr);
293
                        }
294
                }
295

    
296
                // Reproyectando
297
                if (action == REPROJECT) {
298
                        LayerReprojectPanel reprojectPanel = new LayerReprojectPanel(lyr, Boolean.FALSE);
299
                        RasterToolsUtil.addWindow(reprojectPanel);
300
                }
301

    
302
                // No carga
303
                if (action == NOTLOAD) {
304
                }
305
        }
306

    
307
        /**
308
         * Comprueba si un fichero VRT esta en correcto estado, en caso contrario
309
         * lanza una excepcion indicando el tipo de error en la apertura.
310
         *
311
         * @param file
312
         * @throws FileOpenVRTException
313
         */
314
        private void checkFileVRT(File file) throws FileOpenVRTException {
315
                KXmlParser parser = new KXmlParser();
316

    
317
                FileReader fileReader = null;
318
                try {
319
                        fileReader = new FileReader(file);
320
                        parser.setInput(fileReader);
321

    
322
                        parser.nextTag();
323

    
324
                        parser.require(XmlPullParser.START_TAG, null, "VRTDataset");
325

    
326
                        while (parser.nextTag () != XmlPullParser.END_TAG) {
327
                                parser.require(XmlPullParser.START_TAG, null, "VRTRasterBand");
328

    
329
                                String name;
330
                                while (parser.nextTag() != XmlPullParser.END_TAG) {
331
                                        parser.require(XmlPullParser.START_TAG, null, null);
332
                                        boolean relativePath = false;
333
                                        for (int i=0; i<parser.getAttributeCount(); i++) {
334
                                                if (parser.getAttributeName(i).equals("relativetoVRT") &&
335
                                                                parser.getAttributeValue(i).equals("1")) {
336
                                                        relativePath = true;
337
                                                }
338
                                        }
339
                                        name = parser.getName();
340
                                        String nameFile = parser.nextText();
341
                                        if (name.equals("SourceFilename")) {
342
                                                if (relativePath) {
343
                                                        nameFile = file.getParent() + File.separator + nameFile;
344
                                                }
345
                                                File tryFile = new File(nameFile);
346
                                                if (!tryFile.exists()) {
347
                                                        throw new FileOpenVRTException(PluginServices.getText(this, "no_existe_fichero") + " " + nameFile);
348
                                                }
349
                                        }
350
                                        parser.require(XmlPullParser.END_TAG, null, name);
351
                                }
352

    
353
                                parser.require(XmlPullParser.END_TAG, null, "VRTRasterBand");
354
                        }
355
                        parser.require(XmlPullParser.END_TAG, null, "VRTDataset");
356
                        parser.next();
357
                        parser.require(XmlPullParser.END_DOCUMENT, null, null);
358
                } catch (XmlPullParserException e) {
359
                        throw new FileOpenVRTException(PluginServices.getText(this, "el_fichero")+ " " + file.getName().toString() + " " + PluginServices.getText(this, "esta_formato_desconocido"));
360
                } catch (IOException e) {
361
                        throw new FileOpenVRTException(PluginServices.getText(this, "no_puede_abrir_fichero") + " " + file.getName().toString());
362
                } finally {
363
                        if (fileReader != null) {
364
                                try {
365
                                        fileReader.close();
366
                                } catch (IOException e) {
367
                                }
368
                        }
369
                }
370
        }
371

    
372
        /**
373
         * Obtiene el mapControl. La llamada createLayer recibe el MapControl por par?metro pero
374
         * ni pre() ni post() pueden tener acceso al MapControl a no ser que lo busquen ellos.
375
         * @return MapControl
376
         */
377
        public MapControl getMapControl() {
378
                if (mapControl != null) {
379
                        return mapControl;
380
                }
381

    
382
                IWindow activeWindow = PluginServices.getMDIManager().getActiveWindow();
383
                if ((activeWindow != null) && (activeWindow instanceof DefaultViewPanel)) {
384
                        return ((DefaultViewPanel) activeWindow).getMapControl();
385
                }
386

    
387
                IWindow[] w = PluginServices.getMDIManager().getAllWindows();
388
                // Obtiene la primera vista activa
389
                for (int i = 0; i < w.length; i++) {
390
                        if (w[i] instanceof AbstractViewPanel && w[i].equals(PluginServices.getMDIManager().getActiveWindow())) {
391
                                return ((AbstractViewPanel) w[i]).getMapControl();
392
                        }
393
                }
394

    
395
                // Si no hay ninguna activa obtiene la primera vista aunque no est? activa
396
                for (int i = 0; i < w.length; i++) {
397
                        if (w[i] instanceof AbstractViewPanel) {
398
                                return ((AbstractViewPanel) w[i]).getMapControl();
399
                        }
400
                }
401

    
402
                return null;
403
        }
404

    
405
        public void pre() {}
406

    
407
}