Statistics
| Revision:

gvsig-raster / org.gvsig.raster.tools / trunk / org.gvsig.raster.tools / org.gvsig.raster.tools.app / org.gvsig.raster.tools.app.basic / src / main / java / org / gvsig / raster / tools / app / basic / RasterToolsUtil.java @ 1174

History | View | Annotate | Download (21.4 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
* 
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
* 
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
* 
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
19
* MA  02110-1301, USA.
20
* 
21
*/
22
package org.gvsig.raster.tools.app.basic;
23

    
24
import java.awt.Component;
25
import java.awt.Dimension;
26
import java.awt.Point;
27
import java.io.File;
28
import java.util.ArrayList;
29

    
30
import javax.swing.ImageIcon;
31
import javax.swing.JOptionPane;
32

    
33
import org.gvsig.andami.IconThemeHelper;
34
import org.gvsig.andami.PluginServices;
35
import org.gvsig.andami.ui.mdiManager.IWindow;
36
import org.gvsig.app.project.Project;
37
import org.gvsig.app.project.ProjectManager;
38
import org.gvsig.app.project.documents.view.gui.AbstractViewPanel;
39
import org.gvsig.fmap.dal.DALLocator;
40
import org.gvsig.fmap.dal.DataManager;
41
import org.gvsig.fmap.dal.DataStore;
42
import org.gvsig.fmap.dal.coverage.RasterLocator;
43
import org.gvsig.fmap.dal.coverage.datastruct.Param;
44
import org.gvsig.fmap.dal.coverage.datastruct.Params;
45
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
46
import org.gvsig.fmap.dal.coverage.util.ProviderServices;
47
import org.gvsig.fmap.dal.exception.InitializeException;
48
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
49
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
50
import org.gvsig.fmap.mapcontext.MapContextLocator;
51
import org.gvsig.fmap.mapcontext.MapContextManager;
52
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
53
import org.gvsig.fmap.mapcontext.layers.FLayer;
54
import org.gvsig.fmap.mapcontext.layers.FLayers;
55
import org.gvsig.gui.beans.propertiespanel.PropertiesComponent;
56
import org.gvsig.gui.beans.propertiespanel.PropertyStruct;
57
import org.gvsig.raster.fmap.layers.DefaultFLyrRaster;
58
import org.gvsig.raster.util.RasterNotLoadException;
59
import org.slf4j.LoggerFactory;
60

    
61
/**
62
 * Herramientas de uso general y que son dependientes de gvSIG, FMap o de
63
 * libUIComponents. En caso de no serlo existe una clase independiente de
64
 * cualquier proyecto dentro de libRaster para este tipo de funciones.
65
 *
66
 * @version 31/05/2007
67
 * @author Nacho Brodin (nachobrodin@gmail.com)
68
 */
69
public class RasterToolsUtil {
70

    
71
        /**
72
         * Obtiene la lista de capas del TOC y devuelve las raster. Si hay capas agrupadas lo tiene en cuenta y mira
73
         * dentro de la agrupaci?n.
74
         * @param srcLyrs FLayers de la vista
75
         * @param destLyrs Lista de capas 
76
         * @return ArrayList con la lista de capas raster agrupadas o no. El orden en que aparecen
77
         * en la lista es de abajo a arriba las que aparecen en el TOC.
78
         */
79
        public static ArrayList<FLayer> getRasterLayerList(FLayers srcLyrs, ArrayList<FLayer> destLyrs) {
80
                if(destLyrs == null)
81
                        destLyrs = new ArrayList<FLayer>();
82
                for (int i = 0; i < srcLyrs.getLayersCount(); i++) {
83
                        if(srcLyrs.getLayer(i) instanceof DefaultFLyrRaster)
84
                                destLyrs.add(srcLyrs.getLayer(i));
85
                        if(srcLyrs.getLayer(i) instanceof FLayers)
86
                                destLyrs = getLayerList((FLayers)srcLyrs.getLayer(i), destLyrs);
87
                }
88
                return destLyrs;
89
        }
90
        
91
        /**
92
         * Obtiene la lista de capas del TOC y devuelve las raster. Si hay capas agrupadas lo tiene en cuenta y mira
93
         * dentro de la agrupaci?n.
94
         * @param srcLyrs FLayers de la vista
95
         * @param destLyrs Lista de capas 
96
         * @return ArrayList con la lista de capas raster agrupadas o no. El orden en que aparecen
97
         * en la lista es de abajo a arriba las que aparecen en el TOC.
98
         */
99
        public static ArrayList<FLayer> getLayerList(FLayers srcLyrs, ArrayList<FLayer> destLyrs) {
100
                if(srcLyrs == null)
101
                        return null;
102
                if(destLyrs == null)
103
                        destLyrs = new ArrayList<FLayer>();
104
                for (int i = 0; i < srcLyrs.getLayersCount(); i++) {
105
                        if(srcLyrs.getLayer(i) instanceof FLayers)
106
                                destLyrs = getLayerList((FLayers)srcLyrs.getLayer(i), destLyrs);
107
                        else 
108
                                destLyrs.add(srcLyrs.getLayer(i));
109
                }
110
                return destLyrs;
111
        }
112
        
113
        /**
114
         * Obtiene el nombre de la vista donde est? cargada la capa que se pasa por par?metro
115
         * @param layer Capa cargada en una vista
116
         * @return Nombre de la vista donde est? cargada la capa.
117
         */
118
        public static String getView(FLayer layer) {
119
//                Project p = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
120
                Project p = ProjectManager.getInstance().getCurrentProject();
121
                return p.getViewName(layer);        
122
        }
123
        
124
        /**
125
         * Devuelve la traducci?n de un texto. En caso de no existir la traducci?n al idioma seleccionado
126
         * devolver? la cadena de entrada.
127
         * @param parent Ventana padre que contiene el objeto con la traducci?n
128
         * @param text Texto a traducir
129
         * @return Texto traducido o cadena de entrada en caso de no encontrar una traducci?n
130
         */
131
        public static String getText(Object parent, String text) {
132
                return PluginServices.getText(parent, text);
133
        }
134
        
135
        /**
136
         * Obtiene un icono definido por la etiqueta que se especifica en el 
137
         * par?metro
138
         * @param ico Etiqueta del icono
139
         * @return Icono
140
         */
141
        public static ImageIcon getIcon(String ico) {
142
                return IconThemeHelper.getImageIcon(ico);        
143
        }
144
        
145
        /**
146
         * A?ade una ventana al gestor de ventanas
147
         * @param window
148
         */
149
        public static void addWindow(IWindow window) {
150
                PluginServices.getMDIManager().addWindow(window);
151
        }
152
        
153
        /**
154
         * Elimina una ventana al gestor de ventanas
155
         * @param window
156
         */
157
        public static void closeWindow(IWindow window) {
158
                PluginServices.getMDIManager().closeWindow(window);
159
        }
160
        
161
        /**
162
         * Selecciona los controles del panel de propiedades a partir de los par?mtros
163
         * obtenidos del driver. Este m?todo realiza una transformaci?n entre Params
164
         * obtenido del driver de escritura y los par?metros del panel de propiedades.
165
         * @param panel Panel de propiedades
166
         * @param params Par?metros del driver
167
         * @param notTakeIntoAccount Nombre de par?metros que no hay que tener en cuenta. Si es null se tienen en cuenta todos.
168
         */
169
        public static void loadPropertiesFromWriterParams(PropertiesComponent pComp, Params params, String[] notTakeIntoAccount) {
170
                for (int i = 0; i < params.getNumParams(); i++) {
171
                        Param p = params.getParam(i);
172
                        String name = getText(null, p.getId());
173
                        String key = p.getId();
174

    
175
                        //Miramos si el par?metro coincide con  alguno en la lista de parametros que no hay que
176
                        //tener en cuenta. Si es as? no lo a?adimos
177
                        if(notTakeIntoAccount != null && notTakeIntoAccount.length > 0) {
178
                                boolean jump = false;
179
                                for (int j = 0; j < notTakeIntoAccount.length; j++) {
180
                                        if (key.equals(notTakeIntoAccount[j]))
181
                                                jump = true;
182
                                }
183
                                if(jump)
184
                                        continue;
185
                        }
186

    
187
                        Object[] types = null;
188
                        int selectedValue = 0;
189

    
190
                        switch (p.getType()) {
191
                                case Params.CHECK:
192
                                        pComp.addValue(name, key, p.getDefaultValue(), types);
193
                                        break;
194
                                case Params.CHOICE:
195
                                        ArrayList<String> list = new ArrayList<String>();
196
                                        for (int j = 0; j < p.getList().length; j++) {
197
                                                list.add(p.getList()[j]);
198
                                                if (p.getDefaultValue() instanceof Integer)
199
                                                        if (((Integer) p.getDefaultValue()).intValue() == j)
200
                                                                selectedValue = j;
201
                                        }
202
                                        types = new Object[] { new Integer(PropertiesComponent.TYPE_COMBO), list };
203
                                        pComp.addValue(name, key, new Integer(selectedValue), types);
204
                                        break;
205
                                case Params.SLIDER:
206
                                        types = new Object[] { new Integer(PropertiesComponent.TYPE_SLIDER), new Integer(p.getList()[0]), new Integer(p.getList()[1]) };
207
                                        pComp.addValue(name, key, p.getDefaultValue(), types);
208
                                        break;
209
                                default:
210
                                        pComp.addValue(getText(null, ((Param)params.getParam(i)).getId()), params.getParam(i).getId(), params.getParam(i).getDefaultValue(), null);
211
                                        break;
212
                        }
213
                }
214
        }
215

    
216
        /**
217
         * Carga los par?metros del escritor WriterParams con los valores obtenidos
218
         * de la ventana de propiedades.
219
         */
220
        @SuppressWarnings("unchecked")
221
        public static void loadWriterParamsFromPropertiesPanel(PropertiesComponent pComp, Params params) {
222
                ArrayList<PropertyStruct> values = pComp.getValues();
223
                for (int iParam = 0; iParam < params.getNumParams(); iParam++) {
224
                        Param p = params.getParam(iParam);
225
                        for (int iValue = 0; iValue < values.size(); iValue++) {
226
                                PropertyStruct prop = values.get(iValue);
227
                                if (p.getId().compareTo(prop.getKey()) == 0) {
228
                                        switch (p.getType()) {
229
                                                case Params.CHECK:
230
                                                        p.setDefaultValue((Boolean) prop.getNewValue());
231
                                                        break;
232
                                                case Params.CHOICE:
233
                                                        p.setDefaultValue(((Integer) prop.getNewValue()));//p.list[((Integer) prop.getNewValue()).intValue()];
234
                                                        break;
235
                                                case Params.SLIDER:
236
                                                        try {
237
                                                                p.setDefaultValue((Integer)prop.getNewValue());
238
                                                        } catch (NumberFormatException e) {}
239
                                        }
240
                                        break;
241
                                }
242
                        }
243
                }
244
        }
245

    
246
        /**
247
         * Funci?n que devuelve true si se tiene permiso de escritura en la ruta
248
         * indicada en el par?metro path y false si no los tiene.
249
         * @param path Ruta a comprobar los permisosv
250
         * @param pluginObject si es distinto de null se obtiene un mensaje de
251
         *          advertencia y sirve como par?metro para getText de la traducci?n.
252
         *          Si es null no se mostrar? ventana de advertencia
253
         * @return true si se tiene permiso de escritura en la ruta indicada en el
254
         *         par?metro path y false si no los tiene.
255
         */
256
        public static boolean canWrite(String path, Object pluginObject) {
257
                File f = new File(path);
258
                if(f.exists() && f.canWrite())
259
                        return true;
260
                else {
261
                        if(pluginObject != null)
262
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
263
                                                PluginServices.getText(pluginObject, "error_escritura"));
264
                        return false;
265
                }
266
        }
267

    
268
        /**
269
         * Muestra un dialogo con un texto y un bot?n Si o No.
270
         * @param msg Mensaje a mostrar en el dialogo.
271
         * @param parentWindow Ventana desde la que se lanza el dialogo
272
         * @return El bot?n seleccionado por el usuario. true si ha seleccionado "si"
273
         *         y false si ha seleccionado "no"
274
         */
275
        public static boolean messageBoxYesOrNot(String msg, Object parentWindow){
276
                String string1 = PluginServices.getText(parentWindow, "yes");
277
                String string2 = PluginServices.getText(parentWindow, "no");
278
                Object[] options = {string1, string2};
279
                int n = JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
280
                                        "<html>" + PluginServices.getText(parentWindow, msg).replaceAll("\n", "<br>") + "</html>",
281
                                        PluginServices.getText(parentWindow, "confirmacion"),
282
                                        JOptionPane.YES_NO_OPTION,
283
                                        JOptionPane.QUESTION_MESSAGE,
284
                                        null,
285
                                        options,
286
                                        string1);
287
                if (n == JOptionPane.YES_OPTION)
288
                        return true;
289
                else
290
                        return false;
291
        }
292

    
293
        /**
294
         * Shows a error dialog with a text and a accept button 
295
         * @param msg Message to show in the dialog
296
         * @param parentWindow Parent window
297
         */
298
        public static void messageBoxError(String msg, Object parentWindow){
299
                String string = PluginServices.getText(parentWindow, "accept");
300
                Object[] options = {string};
301
                JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
302
                                        "<html>" + PluginServices.getText(parentWindow, msg).replaceAll("\n", "<br>") + "</html>",
303
                                        PluginServices.getText(parentWindow, "confirmacion"),
304
                                        JOptionPane.OK_OPTION,
305
                                        JOptionPane.ERROR_MESSAGE,
306
                                        null,
307
                                        options,
308
                                        string);
309
        }
310

    
311
        /**
312
         * Muestra un dialogo de informaci?n con un texto y un bot?n de aceptar.
313
         * @param msg Mensaje a mostrar en el dialogo. Identificador de la cadena a traducir
314
         * @param parentWindow Ventana desde la que se lanza el dialogo
315
         */
316
        public static void messageBoxInfo(String msg, Object parentWindow){
317
                String string = PluginServices.getText(parentWindow, "accept");
318
                Object[] options = {string};
319
                JOptionPane.showOptionDialog((Component)/*PluginServices.getMainFrame()*/parentWindow,
320
                                        "<html>" + PluginServices.getText(parentWindow, msg).replaceAll("\n", "<br>") + "</html>",
321
                                        PluginServices.getText(parentWindow, "confirmacion"),
322
                                        JOptionPane.OK_OPTION,
323
                                        JOptionPane.INFORMATION_MESSAGE,
324
                                        null,
325
                                        options,
326
                                        string);
327
        }
328

    
329
        /**
330
         * Registra un mensaje de error en el log de gvSIG
331
         * @param msg Mensaje a guardar en el log
332
         * @param parent Objeto que hizo disparar el mensaje
333
         * @param exception Excepcion que ha sido recogida
334
         */
335
        public static void debug(String msg, Object parent, Exception exception) {
336
                if(parent != null)
337
                    LoggerFactory
338
            .getLogger(parent.getClass()).debug(PluginServices.getText(parent, msg), exception);
339
        }
340

    
341
        /**
342
         * Muestra un dialogo de error con un texto y un bot?n de aceptar. El error es
343
         * registrado en el log de gvSIG con la excepcion que se le pase por parametro
344
         * @param msg Mensaje a mostrar en el dialogo.
345
         * @param parentWindow Ventana desde la que se lanza el dialogo
346
         * @param exception Excepcion que ha sido recogida
347
         */
348
        public static void messageBoxError(String msg, Object parentWindow, Exception exception) {
349
                debug(msg, parentWindow, exception);
350
                messageBoxError(msg, parentWindow);
351
        }
352
        
353
        /**
354
         * Muestra un dialogo de error con un texto y un bot?n de aceptar. Se le pasa como ?ltimo par?metros
355
         * una lista de excepciones que ser?n guardadas en el log
356
         * @param msg Mensaje a mostrar en el dialogo.
357
         * @param parentWindow Ventana desde la que se lanza el dialogo
358
         * @param exception Excepcion que ha sido recogida
359
         */
360
        public static void messageBoxError(String msg, Object parentWindow, ArrayList<Exception> exception) {
361
                for (int i = 0; i < exception.size(); i++) 
362
                        debug(msg, parentWindow, exception.get(i));
363
                messageBoxError(msg, parentWindow);
364
        }
365

    
366
        /**
367
         * Muestra un dialogo de informaci?n con un texto y un bot?n de aceptar. El
368
         * mensaje informativo es registrado en el log de gvSIG con la excepcion que
369
         * se le pase por parametro.
370
         * @param msg Mensaje a mostrar en el dialogo. Identificador de la cadena a
371
         *          traducir
372
         * @param parentWindow Ventana desde la que se lanza el dialogo
373
         * @param exception Excepcion que ha sido recogida
374
         */
375
        public static void messageBoxInfo(String msg, Object parentWindow, Exception exception) {
376
                debug(msg, parentWindow, exception);
377
                messageBoxInfo(msg, parentWindow);
378
        }
379

    
380
        /**
381
         * Muestra un dialogo con un texto y un bot?n Si o No. El mensaje es
382
         * registrado en el log de gvSIG con la excepcion que se le pase por
383
         * parametro.
384
         * @param msg Mensaje a mostrar en el dialogo.
385
         * @param parentWindow Ventana desde la que se lanza el dialogo
386
         * @return El bot?n seleccionado por el usuario. true si ha seleccionado "si"
387
         *         y false si ha seleccionado "no"
388
         */
389
        public static boolean messageBoxYesOrNot(String msg, Object parentWindow, Exception exception) {
390
                debug(msg, parentWindow, exception);
391
                return messageBoxYesOrNot(msg, parentWindow);
392
        }
393

    
394
        /**
395
         * Carga una capa raster en una vista de gvSIG.
396
         * @param viewName Nombre de la vista donde ha de cargarse. Si vale null se cargar? en la
397
         * primera vista que encuentre que est? activa. Si no hay ninguna saltar? una excepci?n.
398
         * @param fileName Nombre del fichero a cargar. No debe ser nulo nunca.
399
         * @param layerName Nombre de la capa. Si es null se asignar? el nombre del
400
         * fichero sin extensi?n.
401
         * @throws RasterNotLoadException Excepci?n que se lanza cuando no se ha podido cargar la capa
402
         * por alg?n motivo.
403
         */
404
        @SuppressWarnings("deprecation")
405
        public static FLayer loadLayer(String viewName, String fileName, String layerName) throws RasterNotLoadException {
406
                if(fileName ==  null)
407
                        return null;
408

    
409
                //Seleccionamos la vista de gvSIG
410
                AbstractViewPanel theView = null;
411
                try {
412
                        IWindow[] allViews = PluginServices.getMDIManager().getAllWindows();
413
                        if(viewName != null) {
414
                                for (int i = 0; i < allViews.length; i++) {
415
                                        if (allViews[i] instanceof AbstractViewPanel
416
                                                && PluginServices.getMDIManager().getWindowInfo((AbstractViewPanel) allViews[i]).getTitle().equals(viewName))
417
                                                theView = (AbstractViewPanel) allViews[i];
418
                                }
419
                        } else {
420
                                IWindow activeWindow = PluginServices.getMDIManager().getActiveWindow();
421
                                for (int i = 0; i < allViews.length; i++) {
422
                                        if (allViews[i] instanceof AbstractViewPanel && ((AbstractViewPanel)allViews[i]) == activeWindow) //En la primera vista activa
423
                                                theView = (AbstractViewPanel) allViews[i];
424
                                }
425
                                if(theView == null) {
426
                                        for (int i = 0; i < allViews.length; i++) {
427
                                                if (allViews[i] instanceof AbstractViewPanel) //En la primera vista
428
                                                        theView = (AbstractViewPanel) allViews[i];
429
                                        }
430
                                }
431
                        }
432

    
433
                        if (theView == null)
434
                                throw new RasterNotLoadException("Imposible cargar la capa.");
435
                } catch (ClassCastException ex) {
436
                        throw new RasterNotLoadException("No se puede hacer un casting de esa IWindow a View.");
437
                }
438

    
439
                theView.getMapControl().getMapContext().beginAtomicEvent();
440

    
441
                DefaultFLyrRaster lyr = null;
442
                try {
443
                        ProviderServices provServ = RasterLocator.getManager().getProviderServices();
444
                        RasterDataParameters storeParameters = provServ.createNotTiledParameters(fileName);
445
                        storeParameters.setSRS(theView.getProjection());
446
                        
447
                        MapContextManager mcm = MapContextLocator.getMapContextManager();
448
                        DataManager dataManager = DALLocator.getDataManager();
449
                        DataStore dataStore = null;
450
                        try {
451
                                dataStore = dataManager.createStore(storeParameters);
452
                        } catch (ValidateDataParametersException e) {
453
                                throw new RasterNotLoadException("Error al cargar la capa.");
454
                        } catch (InitializeException e) {
455
                                throw new RasterNotLoadException("Error al cargar la capa.");
456
                        } catch (ProviderNotRegisteredException e) {
457
                                throw new RasterNotLoadException("Error al cargar la capa.");
458
                        }
459
                        
460
                        lyr = new DefaultFLyrRaster();
461
                        
462
                        if(layerName == null) {
463
                                int endIndex = fileName.lastIndexOf(".");
464
                                if (endIndex < 0)
465
                                        endIndex = fileName.length();
466
                                
467
                                layerName = fileName.substring(fileName.lastIndexOf(File.separator) + 1, endIndex);
468
                        }
469
                        
470
                        lyr = (DefaultFLyrRaster) mcm.createLayer(layerName, dataStore);
471

    
472
                } catch (LoadLayerException e) {
473
                        throw new RasterNotLoadException("Error al cargar la capa.");
474
                } catch (InitializeException e) {
475
                        throw new RasterNotLoadException("Error creating parameters.");
476
                } catch (ProviderNotRegisteredException e) {
477
                        throw new RasterNotLoadException("Error creating parameters.");
478
                }
479
                theView.getMapControl().getMapContext().getLayers().addLayer(lyr);
480
                theView.getMapControl().getMapContext().invalidate();
481
                theView.getMapControl().getMapContext().endAtomicEvent();
482
                return lyr;
483
        }
484
        
485
        /**
486
         * Carga una capa raster en una vista de gvSIG.
487
         * @param viewName Nombre de la vista donde ha de cargarse. Si vale null se cargar? en la
488
         * primera vista que encuentre que est? activa. Si no hay ninguna saltar? una excepci?n.
489
         * @param fileName Nombre del fichero a cargar. No debe ser nulo nunca.
490
         * @param layerName Nombre de la capa. Si es null se asignar? el nombre del
491
         * fichero sin extensi?n.
492
         * @throws RasterNotLoadException Excepci?n que se lanza cuando no se ha podido cargar la capa
493
         * por alg?n motivo.
494
         */
495
        public static FLayer loadLayer(String viewName, FLayer lyr) throws RasterNotLoadException {
496
                if(lyr ==  null)
497
                        return null;
498

    
499
                //Seleccionamos la vista de gvSIG
500
                AbstractViewPanel theView = null;
501
                try {
502
                        IWindow[] allViews = PluginServices.getMDIManager().getAllWindows();
503
                        if(viewName != null) {
504
                                for (int i = 0; i < allViews.length; i++) {
505
                                        if (allViews[i] instanceof AbstractViewPanel
506
                                                && PluginServices.getMDIManager().getWindowInfo((AbstractViewPanel) allViews[i]).getTitle().equals(viewName))
507
                                                theView = (AbstractViewPanel) allViews[i];
508
                                }
509
                        } else {
510
                                IWindow activeWindow = PluginServices.getMDIManager().getActiveWindow();
511
                                for (int i = 0; i < allViews.length; i++) {
512
                                        if (allViews[i] instanceof AbstractViewPanel && ((AbstractViewPanel)allViews[i]) == activeWindow) //En la primera vista activa
513
                                                theView = (AbstractViewPanel) allViews[i];
514
                                }
515
                                if(theView == null) {
516
                                        for (int i = 0; i < allViews.length; i++) {
517
                                                if (allViews[i] instanceof AbstractViewPanel) //En la primera vista
518
                                                        theView = (AbstractViewPanel) allViews[i];
519
                                        }
520
                                }
521
                        }
522

    
523
                        if (theView == null)
524
                                throw new RasterNotLoadException("Imposible cargar la capa.");
525
                } catch (ClassCastException ex) {
526
                        throw new RasterNotLoadException("No se puede hacer un casting de esa IWindow a View.");
527
                }
528

    
529
                theView.getMapControl().getMapContext().beginAtomicEvent();
530
                theView.getMapControl().getMapContext().getLayers().addLayer(lyr);
531
                theView.getMapControl().getMapContext().invalidate();
532
                theView.getMapControl().getMapContext().endAtomicEvent();
533
                return lyr;
534
        }
535
        
536
        /**
537
         * Calculo de las coordenadas de una ventana IWindow para que quede centrada sobre el 
538
         * MainFrame. Estas coordenadas solo valen para un IWindow ya que andami mete las ventanas
539
         * con coordenadas relativas a su ventanta principal.
540
         * @param widthWindow Ancho de la ventana a a?adir
541
         * @param heightWindow Alto de la ventana a a?adir
542
         * @return Array con el ancho y el alto 
543
         */
544
        public static Point iwindowPosition(int widthWindow, int heightWindow) {
545
                int posWindowX = 0;
546
                int posWindowY = 0;
547
                Dimension dim = null;
548
                Point pos = null;
549
                if(PluginServices.getMainFrame() instanceof Component) {
550
                        dim = ((Component)PluginServices.getMainFrame()).getSize();
551
                        pos = ((Component)PluginServices.getMainFrame()).getLocation();
552
                        if(dim != null && pos != null) {
553
                                posWindowX = ((dim.width >> 1) - (widthWindow >> 1));
554
                                posWindowY = ((dim.height >> 1) - (heightWindow >> 1) - 70);
555
                                return new Point(posWindowX, posWindowY);
556
                        }
557
                }
558
                return null;
559
        }
560
}