Statistics
| Revision:

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

History | View | Annotate | Download (13.4 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.iver.andami.PluginServices;
58
import com.iver.andami.plugins.Extension;
59
import com.iver.cit.gvsig.fmap.DriverException;
60
import com.iver.cit.gvsig.fmap.DriverIOExceptionType;
61
import com.iver.cit.gvsig.fmap.DriverNotLoadedExceptionType;
62
import com.iver.cit.gvsig.fmap.GenericDriverExceptionType;
63
import com.iver.cit.gvsig.fmap.MapControl;
64
import com.iver.cit.gvsig.fmap.ViewPort;
65
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
66
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
67
import com.iver.cit.gvsig.fmap.layers.FLayer;
68
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
69
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
70
import com.iver.cit.gvsig.gui.WizardPanel;
71
import com.iver.cit.gvsig.project.documents.ProjectDocument;
72
import com.iver.cit.gvsig.project.documents.gui.FOpenDialog;
73
import com.iver.cit.gvsig.project.documents.gui.FileOpenDialog;
74
import com.iver.cit.gvsig.project.documents.view.gui.BaseView;
75
import com.iver.cit.gvsig.project.documents.view.gui.IView;
76

    
77

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

    
87
        private static ArrayList wizardStack = null;
88

    
89
        static {
90
                AddLayer.wizardStack = new ArrayList();
91
        }
92

    
93
        public static void addWizard(Class wpClass) {
94
                AddLayer.wizardStack.add(wpClass);
95
        }
96

    
97
        public static WizardPanel getInstance(int i)
98
                        throws IllegalArgumentException, SecurityException,
99
                        InstantiationException, IllegalAccessException,
100
                        InvocationTargetException, NoSuchMethodException {
101
                Class wpClass = (Class) AddLayer.wizardStack.get(i);
102
                Class[] args = {};
103
                Object[] params = {};
104
                WizardPanel wp = (WizardPanel) wpClass.getConstructor(args)
105
                                .newInstance(params);
106

    
107
                wp.initWizard();
108

    
109
                return wp;
110
        }
111

    
112
        /**
113
         * @see com.iver.mdiApp.plugins.IExtension#isVisible()
114
         */
115
        public boolean isVisible() {
116
                com.iver.andami.ui.mdiManager.IWindow window = PluginServices.getMDIManager()
117
                                                                                                                         .getActiveWindow();
118

    
119
                if (window == null) {
120
                        return false;
121
                }
122

    
123
                // Any view derived from BaseView should have AddLayer available
124

    
125
                IView view;
126
                try {
127
                        view = (IView)window;
128
                }
129
                catch (ClassCastException e) {
130
                    return false;
131
                }
132

    
133
                if (view == null)
134
                        return false;
135

    
136
                BaseView baseView = (BaseView)view;
137
                return (baseView != null);
138
        }
139

    
140
        /**
141
         * @see com.iver.andami.plugins.IExtension#initialize()
142
         */
143
        public void initialize() {
144
        }
145

    
146
        private void checkProjection(FLayer lyr, ViewPort viewPort) {
147
                if (lyr instanceof FLyrVect) {
148
                        FLyrVect lyrVect = (FLyrVect) lyr;
149
                        IProjection proj = lyr.getProjection();
150
                        // Comprobar que la projecci?n es la misma que la vista
151
                        if (proj == null) {
152
                                // SUPONEMOS que la capa est? en la proyecci?n que
153
                                // estamos pidiendo (que ya es mucho suponer, ya).
154
                                lyrVect.setProjection(viewPort.getProjection());
155
                                return;
156
                        }
157
                        if (proj != viewPort.getProjection()) {
158
                                int option = JOptionPane.showConfirmDialog((Component)PluginServices.getMainFrame(), PluginServices
159
                                                .getText(this, "reproyectar_aviso"), PluginServices
160
                                                .getText(this, "reproyectar_pregunta"),
161
                                                JOptionPane.YES_NO_OPTION);
162

    
163
                                if (option != JOptionPane.OK_OPTION) {
164
                                        return;
165
                                } else {
166
                                        ICoordTrans ct = proj.getCT(viewPort.getProjection());
167
                                        lyrVect.setCoordTrans(ct);
168
                                        System.err.println("coordTrans = " + proj.getAbrev() + " "
169
                                                        + viewPort.getProjection().getAbrev());
170
                                }
171
                        }
172
                }
173

    
174
        }
175

    
176
        /**
177
         * @see com.iver.andami.plugins.IExtension#execute(java.lang.String)
178
         */
179
        public void execute(String actionCommand) {
180
                // Project project = ((ProjectExtension)
181
                // PluginServices.getExtension(ProjectExtension.class)).getProject();
182
                BaseView theView = (BaseView) PluginServices.getMDIManager().getActiveWindow();
183
                MapControl mapControl=theView.getMapControl();
184
                this.addLayers(mapControl);
185
                mapControl.getMapContext().callLegendChanged();
186
                ((ProjectDocument)theView.getModel()).setModified(true);
187
        }
188

    
189
        /**
190
         * @see com.iver.andami.plugins.IExtension#isEnabled()
191
         */
192
        public boolean isEnabled() {
193
                return true;
194
        }
195

    
196
        /**
197
         * Creates FOpenDialog, and adds file tab, and additional registered tabs
198
         *
199
         * @return FOpenDialog
200
         */
201
        private FOpenDialog createFOpenDialog() {
202
                fopen = new FOpenDialog();
203
                FileOpenDialog fileDlg = new FileOpenDialog(new Class[] {
204
                                VectorialFileDriver.class, RasterDriver.class });
205
                // first, file wizard tab
206
                fopen.addTab(PluginServices.getText(this, "Fichero"), fileDlg);
207

    
208
                // after that, all registerez tabs (wizardpanels implementations)
209
                for (int i = 0; i < wizardStack.size(); i++) {
210
                        WizardPanel wp;
211
                        try {
212
                                wp = AddLayer.getInstance(i);
213
                                fopen.addWizardTab(wp.getTabName(), wp);
214
                        } catch (IllegalArgumentException e) {
215
                                e.printStackTrace();
216
                        } catch (SecurityException e) {
217
                                e.printStackTrace();
218
                        } catch (InstantiationException e) {
219
                                e.printStackTrace();
220
                        } catch (IllegalAccessException e) {
221
                                e.printStackTrace();
222
                        } catch (InvocationTargetException e) {
223
                                e.printStackTrace();
224
                        } catch (NoSuchMethodException e) {
225
                                e.printStackTrace();
226
                        }
227
                }// for
228
                return fopen;
229
        }
230

    
231
        /**
232
         * Adds to mapcontrol all the file based layers selected by user in
233
         * fileOpenDialog  instance.
234
         *
235
         * @param mapControl
236
         *            MapControl where we want to add the selected layers
237
         *
238
         * @param fileDlg
239
         *            FileOpenDialog where user selected file based layers
240
         *
241
         * @return boolean flag to report sucess of the operation
242
         */
243
        private boolean loadFileLayers(MapControl mapControl, FileOpenDialog fileDlg) {
244

    
245
                if (fileDlg.getFiles() == null) {
246
                        return false;
247
                }
248

    
249
                FLayer lyr = null;
250
                IProjection proj = FOpenDialog.getLastProjection();
251
                File[] files = fileDlg.getFiles();
252
                String[] driverNames = fileDlg.getDriverNames();
253
                Driver[] drivers = new Driver[driverNames.length];
254

    
255
                //all catched errors will be saved here, to show user at the end
256
                //of the method
257
                ArrayList errors = new ArrayList();
258

    
259

    
260
                // try to load the drivers referenced by the file dialog
261
                for (int i = 0; i < drivers.length; i++) {
262
                        try {
263
                                drivers[i] = LayerFactory.getDM().getDriver(driverNames[i]);
264
                        } catch (DriverLoadException e) {
265
                                DriverNotLoadedExceptionType type = new DriverNotLoadedExceptionType();
266
                                type.setDriverName(driverNames[i]);
267
                                DriverException exception = new DriverException(e, type);
268
                                errors.add(exception);
269
//                                NotificationManager.addError("No se pudo cargar el driver", e);
270
                        }
271
                }
272

    
273

    
274
                // Envelope de cada fichero seleccionado por el usuario
275
                Rectangle2D[] rects = new Rectangle2D[files.length];
276
                boolean first = false;
277

    
278
                // A?adir capas al mapControl se trata como una transaccion
279
                mapControl.getMapContext().beginAtomicEvent();
280

    
281
                for (int iFile = 0; iFile < files.length; iFile++) {
282
                        File fich = files[iFile];
283
                        String layerName = fich.getName();
284
                        try {
285
// FJP: Comento esto (if (fileDlg.accept(fich))) para resolver
286
// el bug 75. ?Esto estaba antes
287
// o lo apuesto alguien por algo en concreto?.
288
// if (fileDlg.accept(fich))
289

    
290
                                if (drivers[iFile] instanceof VectorialFileDriver) {
291
                                        lyr = LayerFactory.createLayer(layerName,
292
                                                        (VectorialFileDriver) drivers[iFile], fich, proj);
293
                                } else if (drivers[iFile] instanceof RasterDriver) {
294
                                        lyr = LayerFactory.createLayer(layerName,
295
                                                        (RasterDriver) drivers[iFile], fich, proj);
296
                                }
297

    
298
                                if (lyr != null) {
299
                                        lyr.setVisible(true);
300
                                        if (mapControl.getMapContext().getViewPort().getExtent() == null) {
301
                                                first = true;
302
                                        }
303
                                        checkProjection(lyr, mapControl.getViewPort());
304
                                        mapControl.getMapContext().getLayers().addLayer(lyr);
305

    
306
        //esto ya se hace en layerfactory ?lo dejamos? (azabala)
307
        /*
308
        if (lyr instanceof FLyrVect) {
309
                FLyrVect lyrVect = (FLyrVect) lyr;
310
                if (drivers[iFile] instanceof WithDefaultLegend) {
311
                        WithDefaultLegend aux = (WithDefaultLegend) drivers[iFile];
312
                        lyrVect.setLegend((VectorialLegend) aux
313
                                        .getDefaultLegend());
314
                } else {
315
                        lyrVect.setLegend(LegendFactory
316
                                        .createSingleSymbolLegend(lyrVect
317
                                                        .getShapeType()));
318
                }
319
        }// if
320
        */
321
                                        rects[iFile] = lyr.getFullExtent();
322

    
323
                                        // TODO: Poner una variable y dibujar solo cuando
324
                                        // todas las capas hayan sido cargadas.
325

    
326
                                        // TODO Se deber? de redibujar mediante la captura de los
327
                                        // eventos, por
328
                                        // eso se comenta la parte anterior
329
                                        // theView.getMapControl().drawMap();
330
                                        // theView.getTOC().refresh();
331

    
332
                                }// if
333

    
334
                        } catch (DriverException e) {
335
                                //This exception is produced in the layer.getFullExtent() call
336
                                DriverIOExceptionType type =
337
                                        new DriverIOExceptionType();
338
                                type.setFile(fich);
339
                                DriverException newException = new DriverException(e, type);
340
                                lyr.addError(newException);
341
                                lyr.setAvailable(false);
342
//                                NotificationManager.addError("Error al crear la capa", e);
343

    
344
                                errors.add(newException);
345

    
346
                        }
347

    
348

    
349
        /* si no seteamos la leyenda, pq ya se hace en el factory, esto quitarlo (azabala)
350
                        catch (FieldNotFoundException e) {
351
                                // Esta no puede saltar
352
                        }
353
        */
354

    
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
                }// for
368

    
369

    
370

    
371
                //now, if it is the first time, we put the extent of the mapcontrol
372
                //to the global extent of all the loaded layers.
373
                if (rects.length > 1) {
374
                        Rectangle2D rect = new Rectangle2D.Double();
375
                        rect.setRect(rects[0]);
376

    
377
                        //first is true only if the extent of the mapcontrol was null
378
                        if (first) {
379
                                for (int i = 0; i < rects.length; i++) {
380
                                        if (rects[i] != null) {
381
                                                rect.add(rects[i]);
382
                                        }
383
                                }//for
384
                                mapControl.getMapContext().getViewPort().setExtent(rect);
385
                        }// if first
386
                }// if
387
                mapControl.getMapContext().endAtomicEvent();
388

    
389
                return true;
390
        }
391

    
392

    
393
        /**
394
         * Adds to mapcontrol all layers selected by user in the specified WizardPanel.
395
         *
396
         * @param mapControl
397
         *         MapControl on which we want to load user selected layers.
398
         * @param wizardPanel
399
         *         WizardPanel where user selected the layers to load
400
         * @return
401
         */
402
        private boolean loadGenericWizardPanelLayers(MapControl mapControl, WizardPanel wp) {
403
                FLayer lyr = null;
404
                wp.setMapCtrl(mapControl);
405
                wp.execute();
406
                lyr = wp.getLayer();
407

    
408
                if((lyr != null) && !(lyr.isOk())){
409
                        //if the layer is not okay (it has errors) process them
410
                        processErrorsOfLayer(lyr, mapControl);
411
                }
412

    
413
                if (lyr != null) {
414
                        lyr.setVisible(true);
415
                        mapControl.getMapContext().beginAtomicEvent();
416
                        checkProjection(lyr, mapControl.getViewPort());
417
                        mapControl.getMapContext().getLayers().addLayer(lyr);
418
                        mapControl.getMapContext().endAtomicEvent();
419
                        return true;
420
                }
421
                return false;
422
        }
423

    
424
        /**
425
         * This method process the errors found in a layer
426
         * @param lyr
427
         * @param mapControl
428
         */
429

    
430
        private void processErrorsOfLayer(FLayer lyr, MapControl mapControl){
431
                List errors = lyr.getErrors();
432
//                wp.callError(null);
433
                mapControl.getMapContext().callNewErrorEvent(null);
434
        }
435
        /**
436
         * Abre dialogo para a?adir capas y las a?ade en mapControl
437
         *
438
         * Devuelve true si se han a?adido capas.
439
         */
440
        public boolean addLayers(MapControl mapControl) {
441

    
442

    
443

    
444
                // create and show the modal fopen dialog
445
                fopen = createFOpenDialog();
446
                PluginServices.getMDIManager().addWindow(fopen);
447

    
448
                if (fopen.isAccepted()) {
449
                        if (fopen.getSelectedTab() instanceof FileOpenDialog) {
450
                                FileOpenDialog fileDlg = (FileOpenDialog) fopen
451
                                                .getSelectedTab();
452
                                return loadFileLayers(mapControl, fileDlg);
453

    
454
                        } else if (fopen.getSelectedTab() instanceof WizardPanel) {
455
                                WizardPanel wp = (WizardPanel) fopen.getSelectedTab();
456
                                return loadGenericWizardPanelLayers(mapControl, wp);
457
                        } else {
458
                                JOptionPane.showMessageDialog((Component) PluginServices
459
                                                .getMainFrame(), "Ninguna capa seleccionada");
460
                        }
461
                }
462
                return false;
463
        }
464
}