Statistics
| Revision:

root / trunk / extensions / extRasterTools-SE / src / org / gvsig / raster / util / RasterToolsUtil.java @ 22826

History | View | Annotate | Download (19.3 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2007 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.util;
20

    
21
import java.awt.Component;
22
import java.awt.Dimension;
23
import java.awt.Point;
24
import java.io.File;
25
import java.util.ArrayList;
26

    
27
import javax.swing.ImageIcon;
28
import javax.swing.JOptionPane;
29

    
30
import org.apache.log4j.Logger;
31
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
32
import org.gvsig.gui.beans.propertiespanel.PropertiesComponent;
33
import org.gvsig.gui.beans.propertiespanel.PropertyStruct;
34
import org.gvsig.raster.dataset.Params;
35
import org.gvsig.raster.dataset.Params.Param;
36

    
37
import com.iver.andami.PluginServices;
38
import com.iver.andami.ui.mdiManager.IWindow;
39
import com.iver.cit.gvsig.ProjectExtension;
40
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
41
import com.iver.cit.gvsig.fmap.layers.FLayer;
42
import com.iver.cit.gvsig.fmap.layers.FLayers;
43
import com.iver.cit.gvsig.project.Project;
44
import com.iver.cit.gvsig.project.documents.view.gui.View;
45
/**
46
 * Herramientas de uso general y que son dependientes de gvSIG, FMap o de
47
 * libUIComponents. En caso de no serlo existe una clase independiente de
48
 * cualquier proyecto dentro de libRaster para este tipo de funciones.
49
 *
50
 * @version 31/05/2007
51
 * @author Nacho Brodin (nachobrodin@gmail.com)
52
 */
53
public class RasterToolsUtil {
54

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

    
156
                        //Miramos si el par?metro coincide con  alguno en la lista de parametros que no hay que
157
                        //tener en cuenta. Si es as? no lo a?adimos
158
                        if(notTakeIntoAccount != null && notTakeIntoAccount.length > 0) {
159
                                boolean jump = false;
160
                                for (int j = 0; j < notTakeIntoAccount.length; j++) {
161
                                        if (key.equals(notTakeIntoAccount[j]))
162
                                                jump = true;
163
                                }
164
                                if(jump)
165
                                        continue;
166
                        }
167

    
168
                        Object[] types = null;
169
                        int selectedValue = 0;
170

    
171
                        switch (p.type) {
172
                                case Params.CHECK:
173
                                        pComp.addValue(name, key, p.defaultValue, types);
174
                                        break;
175
                                case Params.CHOICE:
176
                                        ArrayList list = new ArrayList();
177
                                        for (int j = 0; j < p.list.length; j++) {
178
                                                list.add(p.list[j]);
179
                                                if (p.defaultValue instanceof Integer)
180
                                                        if (((Integer) p.defaultValue).intValue() == j)
181
                                                                selectedValue = j;
182
                                        }
183
                                        types = new Object[] { new Integer(PropertiesComponent.TYPE_COMBO), list };
184
                                        pComp.addValue(name, key, new Integer(selectedValue), types);
185
                                        break;
186
                                case Params.SLIDER:
187
                                        types = new Object[] { new Integer(PropertiesComponent.TYPE_SLIDER), new Integer(p.list[0]), new Integer(p.list[1]) };
188
                                        pComp.addValue(name, key, p.defaultValue, types);
189
                                        break;
190
                                default:
191
                                        pComp.addValue(getText(null, params.getParam(i).id), params.getParam(i).id, params.getParam(i).defaultValue, null);
192
                                        break;
193
                        }
194
                }
195
        }
196

    
197
        /**
198
         * Carga los par?metros del escritor WriterParams con los valores obtenidos
199
         * de la ventana de propiedades.
200
         */
201
        public static void loadWriterParamsFromPropertiesPanel(PropertiesComponent pComp, Params params) {
202
                ArrayList values = pComp.getValues();
203
                for (int iParam = 0; iParam < params.getNumParams(); iParam++) {
204
                        Param p = (Param) params.getParam(iParam);
205
                        for (int iValue = 0; iValue < values.size(); iValue++) {
206
                                PropertyStruct prop = ((PropertyStruct) values.get(iValue));
207
                                if (p.id.compareTo(prop.getKey()) == 0) {
208
                                        switch (p.type) {
209
                                                case Params.CHECK:
210
                                                        p.defaultValue = (Boolean) prop.getNewValue();
211
                                                        break;
212
                                                case Params.CHOICE:
213
                                                        p.defaultValue = ((Integer) prop.getNewValue());//p.list[((Integer) prop.getNewValue()).intValue()];
214
                                                        break;
215
                                                case Params.SLIDER:
216
                                                        try {
217
                                                                p.defaultValue = (Integer)prop.getNewValue();
218
                                                        } catch (NumberFormatException e) {}
219
                                        }
220
                                        break;
221
                                }
222
                        }
223
                }
224
        }
225

    
226
        /**
227
         * Funci?n que devuelve true si se tiene permiso de escritura en la ruta
228
         * indicada en el par?metro path y false si no los tiene.
229
         * @param path Ruta a comprobar los permisosv
230
         * @param pluginObject si es distinto de null se obtiene un mensaje de
231
         *          advertencia y sirve como par?metro para getText de la traducci?n.
232
         *          Si es null no se mostrar? ventana de advertencia
233
         * @return true si se tiene permiso de escritura en la ruta indicada en el
234
         *         par?metro path y false si no los tiene.
235
         */
236
        public static boolean canWrite(String path, Object pluginObject) {
237
                File f = new File(path);
238
                if(f.exists() && f.canWrite())
239
                        return true;
240
                else {
241
                        if(pluginObject != null)
242
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
243
                                                PluginServices.getText(pluginObject, "error_escritura"));
244
                        return false;
245
                }
246
        }
247

    
248
        /**
249
         * Muestra un dialogo con un texto y un bot?n Si o No.
250
         * @param msg Mensaje a mostrar en el dialogo.
251
         * @param parentWindow Ventana desde la que se lanza el dialogo
252
         * @return El bot?n seleccionado por el usuario. true si ha seleccionado "si"
253
         *         y false si ha seleccionado "no"
254
         */
255
        public static boolean messageBoxYesOrNot(String msg, Object parentWindow){
256
                String string1 = PluginServices.getText(parentWindow, "yes");
257
                String string2 = PluginServices.getText(parentWindow, "no");
258
                Object[] options = {string1, string2};
259
                int n = JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
260
                                        "<html>" + PluginServices.getText(parentWindow, msg).replaceAll("\n", "<br>") + "</html>",
261
                                        PluginServices.getText(parentWindow, "confirmacion"),
262
                                        JOptionPane.YES_NO_OPTION,
263
                                        JOptionPane.QUESTION_MESSAGE,
264
                                        null,
265
                                        options,
266
                                        string1);
267
                if (n == JOptionPane.YES_OPTION)
268
                        return true;
269
                else
270
                        return false;
271
        }
272

    
273
        /**
274
         * Muestra un dialogo de error con un texto y un bot?n de aceptar.
275
         * @param msg Mensaje a mostrar en el dialogo.
276
         * @param parentWindow Ventana desde la que se lanza el dialogo
277
         */
278
        public static void messageBoxError(String msg, Object parentWindow){
279
                String string = PluginServices.getText(parentWindow, "accept");
280
                Object[] options = {string};
281
                JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
282
                                        "<html>" + PluginServices.getText(parentWindow, msg).replaceAll("\n", "<br>") + "</html>",
283
                                        PluginServices.getText(parentWindow, "confirmacion"),
284
                                        JOptionPane.OK_OPTION,
285
                                        JOptionPane.ERROR_MESSAGE,
286
                                        null,
287
                                        options,
288
                                        string);
289
        }
290

    
291
        /**
292
         * Muestra un dialogo de informaci?n con un texto y un bot?n de aceptar.
293
         * @param msg Mensaje a mostrar en el dialogo. Identificador de la cadena a traducir
294
         * @param parentWindow Ventana desde la que se lanza el dialogo
295
         */
296
        public static void messageBoxInfo(String msg, Object parentWindow){
297
                String string = PluginServices.getText(parentWindow, "accept");
298
                Object[] options = {string};
299
                JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
300
                                        "<html>" + PluginServices.getText(parentWindow, msg).replaceAll("\n", "<br>") + "</html>",
301
                                        PluginServices.getText(parentWindow, "confirmacion"),
302
                                        JOptionPane.OK_OPTION,
303
                                        JOptionPane.INFORMATION_MESSAGE,
304
                                        null,
305
                                        options,
306
                                        string);
307
        }
308

    
309
        /**
310
         * Registra un mensaje de error en el log de gvSIG
311
         * @param msg Mensaje a guardar en el log
312
         * @param parent Objeto que hizo disparar el mensaje
313
         * @param exception Excepcion que ha sido recogida
314
         */
315
        public static void debug(String msg, Object parent, Exception exception) {
316
                if(parent != null)
317
                        Logger.getLogger(parent.getClass().getName()).debug(PluginServices.getText(parent, msg), exception);
318
        }
319

    
320
        /**
321
         * Muestra un dialogo de error con un texto y un bot?n de aceptar. El error es
322
         * registrado en el log de gvSIG con la excepcion que se le pase por parametro
323
         * @param msg Mensaje a mostrar en el dialogo.
324
         * @param parentWindow Ventana desde la que se lanza el dialogo
325
         * @param exception Excepcion que ha sido recogida
326
         */
327
        public static void messageBoxError(String msg, Object parentWindow, Exception exception) {
328
                debug(msg, parentWindow, exception);
329
                messageBoxError(msg, parentWindow);
330
        }
331
        
332
        /**
333
         * Muestra un dialogo de error con un texto y un bot?n de aceptar. Se le pasa como ?ltimo par?metros
334
         * una lista de excepciones que ser?n guardadas en el log
335
         * @param msg Mensaje a mostrar en el dialogo.
336
         * @param parentWindow Ventana desde la que se lanza el dialogo
337
         * @param exception Excepcion que ha sido recogida
338
         */
339
        public static void messageBoxError(String msg, Object parentWindow, ArrayList exception) {
340
                for (int i = 0; i < exception.size(); i++) {
341
                        if(exception.get(i) instanceof Exception)
342
                                debug(msg, parentWindow, (Exception)exception.get(i));
343
                }
344
                messageBoxError(msg, parentWindow);
345
        }
346

    
347
        /**
348
         * Muestra un dialogo de informaci?n con un texto y un bot?n de aceptar. El
349
         * mensaje informativo es registrado en el log de gvSIG con la excepcion que
350
         * se le pase por parametro.
351
         * @param msg Mensaje a mostrar en el dialogo. Identificador de la cadena a
352
         *          traducir
353
         * @param parentWindow Ventana desde la que se lanza el dialogo
354
         * @param exception Excepcion que ha sido recogida
355
         */
356
        public static void messageBoxInfo(String msg, Object parentWindow, Exception exception) {
357
                debug(msg, parentWindow, exception);
358
                messageBoxInfo(msg, parentWindow);
359
        }
360

    
361
        /**
362
         * Muestra un dialogo con un texto y un bot?n Si o No. El mensaje es
363
         * registrado en el log de gvSIG con la excepcion que se le pase por
364
         * parametro.
365
         * @param msg Mensaje a mostrar en el dialogo.
366
         * @param parentWindow Ventana desde la que se lanza el dialogo
367
         * @return El bot?n seleccionado por el usuario. true si ha seleccionado "si"
368
         *         y false si ha seleccionado "no"
369
         */
370
        public static boolean messageBoxYesOrNot(String msg, Object parentWindow, Exception exception) {
371
                debug(msg, parentWindow, exception);
372
                return messageBoxYesOrNot(msg, parentWindow);
373
        }
374

    
375
        /**
376
         * Carga una capa raster en una vista de gvSIG.
377
         * @param viewName Nombre de la vista donde ha de cargarse. Si vale null se cargar? en la
378
         * primera vista que encuentre que est? activa. Si no hay ninguna saltar? una excepci?n.
379
         * @param fileName Nombre del fichero a cargar. No debe ser nulo nunca.
380
         * @param layerName Nombre de la capa. Si es null se asignar? el nombre del
381
         * fichero sin extensi?n.
382
         * @throws RasterNotLoadException Excepci?n que se lanza cuando no se ha podido cargar la capa
383
         * por alg?n motivo.
384
         */
385
        public static FLayer loadLayer(String viewName, String fileName, String layerName) throws RasterNotLoadException {
386
                if(fileName ==  null)
387
                        return null;
388

    
389
                //Seleccionamos la vista de gvSIG
390
                View theView = null;
391
                try {
392
                        IWindow[] allViews = PluginServices.getMDIManager().getAllWindows();
393
                        if(viewName != null) {
394
                                for (int i = 0; i < allViews.length; i++) {
395
                                        if (allViews[i] instanceof View
396
                                                && PluginServices.getMDIManager().getWindowInfo((View) allViews[i]).getTitle().equals(viewName))
397
                                                theView = (View) allViews[i];
398
                                }
399
                        } else {
400
                                IWindow activeWindow = PluginServices.getMDIManager().getActiveWindow();
401
                                for (int i = 0; i < allViews.length; i++) {
402
                                        if (allViews[i] instanceof View && ((View)allViews[i]) == activeWindow) //En la primera vista activa
403
                                                theView = (View) allViews[i];
404
                                }
405
                                if(theView == null) {
406
                                        for (int i = 0; i < allViews.length; i++) {
407
                                                if (allViews[i] instanceof View) //En la primera vista
408
                                                        theView = (View) allViews[i];
409
                                        }
410
                                }
411
                        }
412

    
413
                        if (theView == null)
414
                                throw new RasterNotLoadException("Imposible cargar la capa.");
415
                } catch (ClassCastException ex) {
416
                        throw new RasterNotLoadException("No se puede hacer un casting de esa IWindow a View.");
417
                }
418

    
419
                theView.getMapControl().getMapContext().beginAtomicEvent();
420

    
421
                FLayer lyr = null;
422
                try {
423
                        if(layerName == null) {
424
                                int endIndex = fileName.lastIndexOf(".");
425
                                if (endIndex < 0)
426
                                        endIndex = fileName.length();
427
                                lyr = FLyrRasterSE.createLayer(
428
                                                fileName.substring(fileName.lastIndexOf(File.separator) + 1, endIndex),
429
                                                new File(fileName),
430
                                                theView.getMapControl().getProjection());
431
                        } else {
432
                                lyr = FLyrRasterSE.createLayer(
433
                                                layerName,
434
                                                new File(fileName),
435
                                                theView.getMapControl().getProjection());
436
                        }
437

    
438
                } catch (LoadLayerException e) {
439
                        throw new RasterNotLoadException("Error al cargar la capa.");
440
                }
441
                theView.getMapControl().getMapContext().getLayers().addLayer(lyr);
442
                theView.getMapControl().getMapContext().invalidate();
443
                theView.getMapControl().getMapContext().endAtomicEvent();
444
                return lyr;
445
        }
446
        
447
        /**
448
         * Carga una capa raster en una vista de gvSIG.
449
         * @param viewName Nombre de la vista donde ha de cargarse. Si vale null se cargar? en la
450
         * primera vista que encuentre que est? activa. Si no hay ninguna saltar? una excepci?n.
451
         * @param fileName Nombre del fichero a cargar. No debe ser nulo nunca.
452
         * @param layerName Nombre de la capa. Si es null se asignar? el nombre del
453
         * fichero sin extensi?n.
454
         * @throws RasterNotLoadException Excepci?n que se lanza cuando no se ha podido cargar la capa
455
         * por alg?n motivo.
456
         */
457
        public static FLayer loadLayer(String viewName, FLayer lyr) throws RasterNotLoadException {
458
                if(lyr ==  null)
459
                        return null;
460

    
461
                //Seleccionamos la vista de gvSIG
462
                View theView = null;
463
                try {
464
                        IWindow[] allViews = PluginServices.getMDIManager().getAllWindows();
465
                        if(viewName != null) {
466
                                for (int i = 0; i < allViews.length; i++) {
467
                                        if (allViews[i] instanceof View
468
                                                && PluginServices.getMDIManager().getWindowInfo((View) allViews[i]).getTitle().equals(viewName))
469
                                                theView = (View) allViews[i];
470
                                }
471
                        } else {
472
                                IWindow activeWindow = PluginServices.getMDIManager().getActiveWindow();
473
                                for (int i = 0; i < allViews.length; i++) {
474
                                        if (allViews[i] instanceof View && ((View)allViews[i]) == activeWindow) //En la primera vista activa
475
                                                theView = (View) allViews[i];
476
                                }
477
                                if(theView == null) {
478
                                        for (int i = 0; i < allViews.length; i++) {
479
                                                if (allViews[i] instanceof View) //En la primera vista
480
                                                        theView = (View) allViews[i];
481
                                        }
482
                                }
483
                        }
484

    
485
                        if (theView == null)
486
                                throw new RasterNotLoadException("Imposible cargar la capa.");
487
                } catch (ClassCastException ex) {
488
                        throw new RasterNotLoadException("No se puede hacer un casting de esa IWindow a View.");
489
                }
490

    
491
                theView.getMapControl().getMapContext().beginAtomicEvent();
492
                theView.getMapControl().getMapContext().getLayers().addLayer(lyr);
493
                theView.getMapControl().getMapContext().invalidate();
494
                theView.getMapControl().getMapContext().endAtomicEvent();
495
                return lyr;
496
        }
497
        
498
        /**
499
         * Calculo de las coordenadas de una ventana IWindow para que quede centrada sobre el 
500
         * MainFrame. Estas coordenadas solo valen para un IWindow ya que andami mete las ventanas
501
         * con coordenadas relativas a su ventanta principal.
502
         * @param widthWindow Ancho de la ventana a a?adir
503
         * @param heightWindow Alto de la ventana a a?adir
504
         * @return Array con el ancho y el alto 
505
         */
506
        public static Point iwindowPosition(int widthWindow, int heightWindow) {
507
                int posWindowX = 0;
508
                int posWindowY = 0;
509
                Dimension dim = null;
510
                Point pos = null;
511
                if(PluginServices.getMainFrame() instanceof Component) {
512
                        dim = ((Component)PluginServices.getMainFrame()).getSize();
513
                        pos = ((Component)PluginServices.getMainFrame()).getLocation();
514
                        if(dim != null && pos != null) {
515
                                posWindowX = ((dim.width >> 1) - (widthWindow >> 1));
516
                                posWindowY = ((dim.height >> 1) - (heightWindow >> 1) - 70);
517
                                return new Point(posWindowX, posWindowY);
518
                        }
519
                }
520
                return null;
521
        }
522
}