Statistics
| Revision:

svn-gvsig-desktop / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / AddLayer.java @ 10661

History | View | Annotate | Download (14.2 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 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
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig;
42

    
43
import java.awt.Component;
44
import java.awt.geom.Rectangle2D;
45
import java.io.File;
46
import java.lang.reflect.InvocationTargetException;
47
import java.util.ArrayList;
48
import java.util.List;
49

    
50
import javax.swing.JOptionPane;
51

    
52
import org.cresques.cts.ICoordTrans;
53
import org.cresques.cts.IProjection;
54

    
55
import com.hardcode.driverManager.Driver;
56
import com.hardcode.driverManager.DriverLoadException;
57
import com.hardcode.driverManager.DriverManager;
58
import com.hardcode.driverManager.WriterManager;
59
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
60
import com.iver.andami.PluginServices;
61
import com.iver.andami.plugins.Extension;
62
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
63
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
64
import com.iver.cit.gvsig.fmap.DriverIOExceptionType;
65
import com.iver.cit.gvsig.fmap.DriverNotLoadedExceptionType;
66
import com.iver.cit.gvsig.fmap.GenericDriverExceptionType;
67
import com.iver.cit.gvsig.fmap.MapControl;
68
import com.iver.cit.gvsig.fmap.ViewPort;
69
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
70
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
71
import com.iver.cit.gvsig.fmap.layers.CancelationException;
72
import com.iver.cit.gvsig.fmap.layers.FLayer;
73
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
74
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
75
import com.iver.cit.gvsig.gui.WizardPanel;
76
import com.iver.cit.gvsig.project.documents.ProjectDocument;
77
import com.iver.cit.gvsig.project.documents.gui.FOpenDialog;
78
import com.iver.cit.gvsig.project.documents.gui.FileOpenDialog;
79
import com.iver.cit.gvsig.project.documents.view.gui.BaseView;
80
import com.iver.cit.gvsig.project.documents.view.gui.IView;
81

    
82

    
83
/**
84
 * Extensi?n que abre un di?logo para seleccionar la capa o capas que se quieren
85
 * a?adir a la vista.
86
 *
87
 * @author Fernando Gonz?lez Cort?s
88
 */
89
public class AddLayer extends Extension {
90
        public FOpenDialog fopen = null;
91

    
92
        private static ArrayList wizardStack = null;
93

    
94
        static {
95
                AddLayer.wizardStack = new ArrayList();
96
        }
97

    
98
        public static void addWizard(Class wpClass) {
99
                AddLayer.wizardStack.add(wpClass);
100
        }
101

    
102
        public static WizardPanel getInstance(int i)
103
                        throws IllegalArgumentException, SecurityException,
104
                        InstantiationException, IllegalAccessException,
105
                        InvocationTargetException, NoSuchMethodException {
106
                Class wpClass = (Class) AddLayer.wizardStack.get(i);
107
                Class[] args = {};
108
                Object[] params = {};
109
                WizardPanel wp = (WizardPanel) wpClass.getConstructor(args)
110
                                .newInstance(params);
111

    
112
                wp.initWizard();
113

    
114
                return wp;
115
        }
116

    
117
        /**
118
         * @see com.iver.mdiApp.plugins.IExtension#isVisible()
119
         */
120
        public boolean isVisible() {
121
                com.iver.andami.ui.mdiManager.IWindow window = PluginServices.getMDIManager()
122
                                                                                                                         .getActiveWindow();
123

    
124
                if (window == null) {
125
                        return false;
126
                }
127

    
128
                // Any view derived from BaseView should have AddLayer available
129

    
130
                IView view;
131
                try {
132
                        view = (IView)window;
133
                }
134
                catch (ClassCastException e) {
135
                    return false;
136
                }
137

    
138
                if (view == null)
139
                        return false;
140

    
141
                BaseView baseView = (BaseView)view;
142
                return (baseView != null);
143
        }
144

    
145
        /**
146
         * @see com.iver.andami.plugins.IExtension#postInitialize()
147
         */
148
        public void postInitialize() {
149
                LayerFactory.initialize();
150
                DriverManager dm=LayerFactory.getDM();
151
                PluginServices.addLoaders(dm.getDriverClassLoaders());
152
                WriterManager wm=LayerFactory.getWM();
153
                PluginServices.addLoaders(wm.getWriterClassLoaders());
154
        }
155

    
156
        private void checkProjection(FLayer lyr, ViewPort viewPort) {
157
                if (lyr instanceof FLyrVect) {
158
                        FLyrVect lyrVect = (FLyrVect) lyr;
159
                        IProjection proj = lyr.getProjection();
160
                        // Comprobar que la projecci?n es la misma que la vista
161
                        if (proj == null) {
162
                                // SUPONEMOS que la capa est? en la proyecci?n que
163
                                // estamos pidiendo (que ya es mucho suponer, ya).
164
                                lyrVect.setProjection(viewPort.getProjection());
165
                                return;
166
                        }
167
                        if (proj != viewPort.getProjection()) {
168
                                int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(), PluginServices
169
                                                .getText(this, "reproyectar_aviso"), PluginServices
170
                                                .getText(this, "reproyectar_pregunta"),
171
                                                JOptionPane.YES_NO_OPTION);
172

    
173
                                if (option != JOptionPane.OK_OPTION) {
174
                                        return;
175
                                } else {
176
                                        ICoordTrans ct = proj.getCT(viewPort.getProjection());
177
                                        lyrVect.setCoordTrans(ct);
178
                                        System.err.println("coordTrans = " + proj.getAbrev() + " "
179
                                                        + viewPort.getProjection().getAbrev());
180
                                }
181
                        }
182
                }
183

    
184
        }
185

    
186
        /**
187
         * @see com.iver.andami.plugins.IExtension#execute(java.lang.String)
188
         */
189
        public void execute(String actionCommand) {
190
                // Project project = ((ProjectExtension)
191
                // PluginServices.getExtension(ProjectExtension.class)).getProject();
192
                BaseView theView = (BaseView) PluginServices.getMDIManager().getActiveWindow();
193
                MapControl mapControl=theView.getMapControl();
194
                this.addLayers(mapControl);
195
                mapControl.getMapContext().callLegendChanged();
196
                ((ProjectDocument)theView.getModel()).setModified(true);
197
        }
198

    
199
        /**
200
         * @see com.iver.andami.plugins.IExtension#isEnabled()
201
         */
202
        public boolean isEnabled() {
203
                return true;
204
        }
205

    
206
        /**
207
         * Creates FOpenDialog, and adds file tab, and additional registered tabs
208
         *
209
         * @return FOpenDialog
210
         */
211
        private FOpenDialog createFOpenDialog() {
212
                fopen = new FOpenDialog();
213
                FileOpenDialog fileDlg = new FileOpenDialog(new Class[] {
214
                                VectorialFileDriver.class, RasterDriver.class });
215
                // first, file wizard tab
216
                fopen.addTab(PluginServices.getText(this, "Fichero"), fileDlg);
217

    
218
                // after that, all registerez tabs (wizardpanels implementations)
219
                for (int i = 0; i < wizardStack.size(); i++) {
220
                        WizardPanel wp;
221
                        try {
222
                                wp = AddLayer.getInstance(i);
223
                                fopen.addWizardTab(wp.getTabName(), wp);
224
                        } catch (IllegalArgumentException e) {
225
                                e.printStackTrace();
226
                        } catch (SecurityException e) {
227
                                e.printStackTrace();
228
                        } catch (InstantiationException e) {
229
                                e.printStackTrace();
230
                        } catch (IllegalAccessException e) {
231
                                e.printStackTrace();
232
                        } catch (InvocationTargetException e) {
233
                                e.printStackTrace();
234
                        } catch (NoSuchMethodException e) {
235
                                e.printStackTrace();
236
                        }
237
                }// for
238
                return fopen;
239
        }
240

    
241
        /**
242
         * Adds to mapcontrol all the file based layers selected by user in
243
         * fileOpenDialog  instance.
244
         *
245
         * @param mapControl
246
         *            MapControl where we want to add the selected layers
247
         *
248
         * @param fileDlg
249
         *            FileOpenDialog where user selected file based layers
250
         *
251
         * @return boolean flag to report sucess of the operation
252
         */
253
        private boolean loadFileLayers(MapControl mapControl, FileOpenDialog fileDlg) {
254

    
255
                if (fileDlg.getFiles() == null) {
256
                        return false;
257
                }
258

    
259
                FLayer lyr = null;
260
                IProjection proj = FOpenDialog.getLastProjection();
261
                File[] files = fileDlg.getFiles();
262
                String[] driverNames = fileDlg.getDriverNames();
263
                Driver[] drivers = new Driver[driverNames.length];
264

    
265
                //all catched errors will be saved here, to show user at the end
266
                //of the method
267
                ArrayList errors = new ArrayList();
268

    
269

    
270
                // try to load the drivers referenced by the file dialog
271
                for (int i = 0; i < drivers.length; i++) {
272
                        try {
273
                                drivers[i] = LayerFactory.getDM().getDriver(driverNames[i]);
274
                        } catch (DriverLoadException e) {
275
//                                DriverNotLoadedExceptionType type = new DriverNotLoadedExceptionType();
276
//                                type.setDriverName(driverNames[i]);
277
//                                DriverException exception = new DriverException(e, type);
278
                                errors.add(e);
279
//                                NotificationManager.addError("No se pudo cargar el driver", e);
280
                        }
281
                }
282

    
283

    
284
                // Envelope de cada fichero seleccionado por el usuario
285
                Rectangle2D[] rects = new Rectangle2D[files.length];
286
                boolean first = false;
287

    
288
                // A?adir capas al mapControl se trata como una transaccion
289
                mapControl.getMapContext().beginAtomicEvent();
290

    
291
                for (int iFile = 0; iFile < files.length; iFile++) {
292
                        File fich = files[iFile];
293
                        String layerName = fich.getName();
294
                        try {
295
// FJP: Comento esto (if (fileDlg.accept(fich))) para resolver
296
// el bug 75. ?Esto estaba antes
297
// o lo apuesto alguien por algo en concreto?.
298
// if (fileDlg.accept(fich))
299

    
300
                                if (drivers[iFile] instanceof VectorialFileDriver) {
301
                                        lyr = LayerFactory.createLayer(layerName,
302
                                                        (VectorialFileDriver) drivers[iFile], fich, proj);
303
                                } else if (drivers[iFile] instanceof RasterDriver) {
304
                                        lyr = LayerFactory.createLayer(layerName,
305
                                                        (RasterDriver) drivers[iFile], fich, proj);
306
                                }
307

    
308
                                if (lyr != null) {
309
                                        //lyr.setVisible(true);
310
                                        if (mapControl.getMapContext().getViewPort().getExtent() == null) {
311
                                                first = true;
312
                                        }
313
                                        checkProjection(lyr, mapControl.getViewPort());
314
                                        mapControl.getMapContext().getLayers().addLayer(lyr);
315

    
316
        //esto ya se hace en layerfactory ?lo dejamos? (azabala)
317
        /*
318
        if (lyr instanceof FLyrVect) {
319
                FLyrVect lyrVect = (FLyrVect) lyr;
320
                if (drivers[iFile] instanceof WithDefaultLegend) {
321
                        WithDefaultLegend aux = (WithDefaultLegend) drivers[iFile];
322
                        lyrVect.setLegend((VectorialLegend) aux
323
                                        .getDefaultLegend());
324
                } else {
325
                        lyrVect.setLegend(LegendFactory
326
                                        .createSingleSymbolLegend(lyrVect
327
                                                        .getShapeType()));
328
                }
329
        }// if
330
        */
331
                                        rects[iFile] = lyr.getFullExtent();
332

    
333
                                        // TODO: Poner una variable y dibujar solo cuando
334
                                        // todas las capas hayan sido cargadas.
335

    
336
                                        // TODO Se deber? de redibujar mediante la captura de los
337
                                        // eventos, por
338
                                        // eso se comenta la parte anterior
339
                                        // theView.getMapControl().drawMap();
340
                                        // theView.getTOC().refresh();
341

    
342
                                }// if
343

    
344
//                        } catch (DriverException e) {
345
//                                //This exception is produced in the layer.getFullExtent() call
346
//                                DriverIOExceptionType type =
347
//                                        new DriverIOExceptionType();
348
//                                type.setFile(fich);
349
//                                DriverException newException = new DriverException(e, type);
350
//                                lyr.addError(newException);
351
//                                lyr.setAvailable(false);
352
////                                NotificationManager.addError("Error al crear la capa", e);
353
//
354
//                                errors.add(newException);
355
//
356
//                        } catch (Exception e) {
357
////azabala: usamos el notificationManager?? a mi no me gusta demasiado
358
////NotificationManager.addError("Error al crear la capa", e);
359
//                                //we catch any possible error
360
//                                GenericDriverExceptionType type = new GenericDriverExceptionType();
361
//                                DriverException exception = new DriverException(e, type);
362
//                                lyr.addError(exception);
363
//                                lyr.setAvailable(false);
364
//
365
//                                errors.add(exception);
366
//                        }
367
                        } catch (LoadLayerException e) {
368
                                errors.add(e);
369
                        } catch (ReadDriverException e) {
370
                                errors.add(e);
371
                        } catch (ExpansionFileReadException e) {
372
                                errors.add(e);
373
                        }
374
                }// for
375

    
376

    
377

    
378
                //now, if it is the first time, we put the extent of the mapcontrol
379
                //to the global extent of all the loaded layers.
380
                if (rects.length > 1) {
381
                        Rectangle2D rect = new Rectangle2D.Double();
382
                        rect.setRect(rects[0]);
383

    
384
                        //first is true only if the extent of the mapcontrol was null
385
                        if (first) {
386
                                for (int i = 0; i < rects.length; i++) {
387
                                        if (rects[i] != null) {
388
                                                rect.add(rects[i]);
389
                                        }
390
                                }//for
391
                                mapControl.getMapContext().getViewPort().setExtent(rect);
392
                        }// if first
393
                }// if
394
                mapControl.getMapContext().endAtomicEvent();
395

    
396
                return true;
397
        }
398

    
399

    
400
        /**
401
         * Adds to mapcontrol all layers selected by user in the specified WizardPanel.
402
         *
403
         * @param mapControl
404
         *         MapControl on which we want to load user selected layers.
405
         * @param wizardPanel
406
         *         WizardPanel where user selected the layers to load
407
         * @return
408
         */
409
        private boolean loadGenericWizardPanelLayers(MapControl mapControl, WizardPanel wp) {
410
                FLayer lyr = null;
411
                wp.setMapCtrl(mapControl);
412
                wp.execute();
413
                lyr = wp.getLayer();
414

    
415
                if((lyr != null) && !(lyr.isOk())){
416
                        //if the layer is not okay (it has errors) process them
417
                        processErrorsOfLayer(lyr, mapControl);
418
                }
419

    
420
                if (lyr != null) {
421
                        lyr.setVisible(true);
422
                        mapControl.getMapContext().beginAtomicEvent();
423
                        checkProjection(lyr, mapControl.getViewPort());
424
                        try {
425
                                mapControl.getMapContext().getLayers().addLayer(lyr);
426
                        } catch (CancelationException e) {
427
                                // TODO Auto-generated catch block
428
                                e.printStackTrace();
429
                        }
430
                        mapControl.getMapContext().endAtomicEvent();
431
                        return true;
432
                }
433
                return false;
434
        }
435

    
436
        /**
437
         * This method process the errors found in a layer
438
         * @param lyr
439
         * @param mapControl
440
         */
441

    
442
        private void processErrorsOfLayer(FLayer lyr, MapControl mapControl){
443
                List errors = lyr.getErrors();
444
//                wp.callError(null);
445
                mapControl.getMapContext().callNewErrorEvent(null);
446
        }
447
        /**
448
         * Abre dialogo para a?adir capas y las a?ade en mapControl
449
         *
450
         * Devuelve true si se han a?adido capas.
451
         */
452
        public boolean addLayers(MapControl mapControl) {
453

    
454

    
455

    
456
                // create and show the modal fopen dialog
457
                fopen = createFOpenDialog();
458
                PluginServices.getMDIManager().addWindow(fopen);
459

    
460
                if (fopen.isAccepted()) {
461
                        if (fopen.getSelectedTab() instanceof FileOpenDialog) {
462
                                FileOpenDialog fileDlg = (FileOpenDialog) fopen
463
                                                .getSelectedTab();
464
                                return loadFileLayers(mapControl, fileDlg);
465

    
466
                        } else if (fopen.getSelectedTab() instanceof WizardPanel) {
467
                                WizardPanel wp = (WizardPanel) fopen.getSelectedTab();
468
                                return loadGenericWizardPanelLayers(mapControl, wp);
469
                        } else {
470
                                JOptionPane.showMessageDialog((Component) PluginServices
471
                                                .getMainFrame(), "Ninguna capa seleccionada");
472
                        }
473
                }
474
                return false;
475
        }
476

    
477
        public void initialize() {
478
                // TODO Auto-generated method stub
479

    
480
        }
481
}