Statistics
| Revision:

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

History | View | Annotate | Download (15.8 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.project.Project;
43
import com.iver.cit.gvsig.project.documents.view.gui.View;
44
/**
45
 * Herramientas de uso general y que son dependientes de gvSIG, FMap o de
46
 * libUIComponents. En caso de no serlo existe una clase independiente de
47
 * cualquier proyecto dentro de libRaster para este tipo de funciones.
48
 *
49
 * @version 31/05/2007
50
 * @author Nacho Brodin (nachobrodin@gmail.com)
51
 */
52
public class RasterToolsUtil {
53

    
54
        /**
55
         * Obtiene el nombre de la vista donde est? cargada la capa que se pasa por par?metro
56
         * @param layer Capa cargada en una vista
57
         * @return Nombre de la vista donde est? cargada la capa.
58
         */
59
        public static String getView(FLayer layer) {
60
                Project p = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
61
                return p.getView(layer);        
62
        }
63
        
64
        /**
65
         * Devuelve la traducci?n de un texto. En caso de no existir la traducci?n al idioma seleccionado
66
         * devolver? la cadena de entrada.
67
         * @param parent Ventana padre que contiene el objeto con la traducci?n
68
         * @param text Texto a traducir
69
         * @return Texto traducido o cadena de entrada en caso de no encontrar una traducci?n
70
         */
71
        public static String getText(Object parent, String text) {
72
                return PluginServices.getText(parent, text);
73
        }
74
        
75
        /**
76
         * Obtiene un icono definido por la etiqueta que se especifica en el 
77
         * par?metro
78
         * @param ico Etiqueta del icono
79
         * @return Icono
80
         */
81
        public static ImageIcon getIcon(String ico) {
82
                return PluginServices.getIconTheme().get(ico);        
83
        }
84
        
85
        /**
86
         * A?ade una ventana al gestor de ventanas
87
         * @param window
88
         */
89
        public static void addWindow(IWindow window) {
90
                PluginServices.getMDIManager().addWindow(window);
91
        }
92
        
93
        /**
94
         * Elimina una ventana al gestor de ventanas
95
         * @param window
96
         */
97
        public static void closeWindow(IWindow window) {
98
                PluginServices.getMDIManager().closeWindow(window);
99
        }
100
        
101
        /**
102
         * Selecciona los controles del panel de propiedades a partir de los par?mtros
103
         * obtenidos del driver. Este m?todo realiza una transformaci?n entre Params
104
         * obtenido del driver de escritura y los par?metros del panel de propiedades.
105
         * @param panel Panel de propiedades
106
         * @param params Par?metros del driver
107
         * @param notTakeIntoAccount Nombre de par?metros que no hay que tener en cuenta. Si es null se tienen en cuenta todos.
108
         */
109
        public static void loadPropertiesFromWriterParams(PropertiesComponent pComp, Params params, String[] notTakeIntoAccount) {
110
                for (int i = 0; i < params.getNumParams(); i++) {
111
                        Param p = params.getParam(i);
112
                        String name = getText(null, p.id);
113
                        String key = p.id;
114

    
115
                        //Miramos si el par?metro coincide con  alguno en la lista de parametros que no hay que
116
                        //tener en cuenta. Si es as? no lo a?adimos
117
                        if(notTakeIntoAccount != null && notTakeIntoAccount.length > 0) {
118
                                boolean jump = false;
119
                                for (int j = 0; j < notTakeIntoAccount.length; j++) {
120
                                        if (key.equals(notTakeIntoAccount[j]))
121
                                                jump = true;
122
                                }
123
                                if(jump)
124
                                        continue;
125
                        }
126

    
127
                        Object[] types = null;
128
                        int selectedValue = 0;
129

    
130
                        switch (p.type) {
131
                                case Params.CHECK:
132
                                        pComp.addValue(name, key, p.defaultValue, types);
133
                                        break;
134
                                case Params.CHOICE:
135
                                        ArrayList list = new ArrayList();
136
                                        for (int j = 0; j < p.list.length; j++) {
137
                                                list.add(p.list[j]);
138
                                                if (p.defaultValue instanceof Integer)
139
                                                        if (((Integer) p.defaultValue).intValue() == j)
140
                                                                selectedValue = j;
141
                                        }
142
                                        types = new Object[] { new Integer(PropertiesComponent.TYPE_COMBO), list };
143
                                        pComp.addValue(name, key, new Integer(selectedValue), types);
144
                                        break;
145
                                case Params.SLIDER:
146
                                        types = new Object[] { new Integer(PropertiesComponent.TYPE_SLIDER), new Integer(p.list[0]), new Integer(p.list[1]) };
147
                                        pComp.addValue(name, key, p.defaultValue, types);
148
                                        break;
149
                                default:
150
                                        pComp.addValue(getText(null, params.getParam(i).id), params.getParam(i).id, params.getParam(i).defaultValue, null);
151
                                        break;
152
                        }
153
                }
154
        }
155

    
156
        /**
157
         * Carga los par?metros del escritor WriterParams con los valores obtenidos
158
         * de la ventana de propiedades.
159
         */
160
        public static void loadWriterParamsFromPropertiesPanel(PropertiesComponent pComp, Params params) {
161
                ArrayList values = pComp.getValues();
162
                for (int iParam = 0; iParam < params.getNumParams(); iParam++) {
163
                        Param p = (Param) params.getParam(iParam);
164
                        for (int iValue = 0; iValue < values.size(); iValue++) {
165
                                PropertyStruct prop = ((PropertyStruct) values.get(iValue));
166
                                if (p.id.compareTo(prop.getKey()) == 0) {
167
                                        switch (p.type) {
168
                                                case Params.CHECK:
169
                                                        p.defaultValue = (Boolean) prop.getNewValue();
170
                                                        break;
171
                                                case Params.CHOICE:
172
                                                        p.defaultValue = ((Integer) prop.getNewValue());//p.list[((Integer) prop.getNewValue()).intValue()];
173
                                                        break;
174
                                                case Params.SLIDER:
175
                                                        try {
176
                                                                p.defaultValue = (Integer)prop.getNewValue();
177
                                                        } catch (NumberFormatException e) {}
178
                                        }
179
                                        break;
180
                                }
181
                        }
182
                }
183
        }
184

    
185
        /**
186
         * Funci?n que devuelve true si se tiene permiso de escritura en la ruta
187
         * indicada en el par?metro path y false si no los tiene.
188
         * @param path Ruta a comprobar los permisosv
189
         * @param pluginObject si es distinto de null se obtiene un mensaje de
190
         *          advertencia y sirve como par?metro para getText de la traducci?n.
191
         *          Si es null no se mostrar? ventana de advertencia
192
         * @return true si se tiene permiso de escritura en la ruta indicada en el
193
         *         par?metro path y false si no los tiene.
194
         */
195
        public static boolean canWrite(String path, Object pluginObject) {
196
                File f = new File(path);
197
                if(f.exists() && f.canWrite())
198
                        return true;
199
                else {
200
                        if(pluginObject != null)
201
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
202
                                                PluginServices.getText(pluginObject, "error_escritura"));
203
                        return false;
204
                }
205
        }
206

    
207
        /**
208
         * Muestra un dialogo con un texto y un bot?n Si o No.
209
         * @param msg Mensaje a mostrar en el dialogo.
210
         * @param parentWindow Ventana desde la que se lanza el dialogo
211
         * @return El bot?n seleccionado por el usuario. true si ha seleccionado "si"
212
         *         y false si ha seleccionado "no"
213
         */
214
        public static boolean messageBoxYesOrNot(String msg, Object parentWindow){
215
                String string1 = PluginServices.getText(parentWindow, "yes");
216
                String string2 = PluginServices.getText(parentWindow, "no");
217
                Object[] options = {string1, string2};
218
                int n = JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
219
                                        "<html>" + PluginServices.getText(parentWindow, msg).replaceAll("\n", "<br>") + "</html>",
220
                                        PluginServices.getText(parentWindow, "confirmacion"),
221
                                        JOptionPane.YES_NO_OPTION,
222
                                        JOptionPane.QUESTION_MESSAGE,
223
                                        null,
224
                                        options,
225
                                        string1);
226
                if (n == JOptionPane.YES_OPTION)
227
                        return true;
228
                else
229
                        return false;
230
        }
231

    
232
        /**
233
         * Muestra un dialogo de error con un texto y un bot?n de aceptar.
234
         * @param msg Mensaje a mostrar en el dialogo.
235
         * @param parentWindow Ventana desde la que se lanza el dialogo
236
         */
237
        public static void messageBoxError(String msg, Object parentWindow){
238
                String string = PluginServices.getText(parentWindow, "accept");
239
                Object[] options = {string};
240
                JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
241
                                        "<html>" + PluginServices.getText(parentWindow, msg).replaceAll("\n", "<br>") + "</html>",
242
                                        PluginServices.getText(parentWindow, "confirmacion"),
243
                                        JOptionPane.OK_OPTION,
244
                                        JOptionPane.ERROR_MESSAGE,
245
                                        null,
246
                                        options,
247
                                        string);
248
        }
249

    
250
        /**
251
         * Muestra un dialogo de informaci?n con un texto y un bot?n de aceptar.
252
         * @param msg Mensaje a mostrar en el dialogo. Identificador de la cadena a traducir
253
         * @param parentWindow Ventana desde la que se lanza el dialogo
254
         */
255
        public static void messageBoxInfo(String msg, Object parentWindow){
256
                String string = PluginServices.getText(parentWindow, "accept");
257
                Object[] options = {string};
258
                JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
259
                                        "<html>" + PluginServices.getText(parentWindow, msg).replaceAll("\n", "<br>") + "</html>",
260
                                        PluginServices.getText(parentWindow, "confirmacion"),
261
                                        JOptionPane.OK_OPTION,
262
                                        JOptionPane.INFORMATION_MESSAGE,
263
                                        null,
264
                                        options,
265
                                        string);
266
        }
267

    
268
        /**
269
         * Registra un mensaje de error en el log de gvSIG
270
         * @param msg Mensaje a guardar en el log
271
         * @param parentWindow Objeto que hizo disparar el mensaje
272
         * @param exception Excepcion que ha sido recogida
273
         */
274
        public static void debug(String msg, Object parentWindow, Exception exception) {
275
                if(parentWindow != null)
276
                        Logger.getLogger(parentWindow.getClass().getName()).debug(PluginServices.getText(parentWindow, msg), exception);
277
        }
278

    
279
        /**
280
         * Muestra un dialogo de error con un texto y un bot?n de aceptar. El error es
281
         * registrado en el log de gvSIG con la excepcion que se le pase por parametro
282
         * @param msg Mensaje a mostrar en el dialogo.
283
         * @param parentWindow Ventana desde la que se lanza el dialogo
284
         * @param exception Excepcion que ha sido recogida
285
         */
286
        public static void messageBoxError(String msg, Object parentWindow, Exception exception) {
287
                debug(msg, parentWindow, exception);
288
                messageBoxError(msg, parentWindow);
289
        }
290
        
291
        /**
292
         * Muestra un dialogo de error con un texto y un bot?n de aceptar. Se le pasa como ?ltimo par?metros
293
         * una lista de excepciones que ser?n guardadas en el log
294
         * @param msg Mensaje a mostrar en el dialogo.
295
         * @param parentWindow Ventana desde la que se lanza el dialogo
296
         * @param exception Excepcion que ha sido recogida
297
         */
298
        public static void messageBoxError(String msg, Object parentWindow, ArrayList exception) {
299
                for (int i = 0; i < exception.size(); i++) {
300
                        if(exception.get(i) instanceof Exception)
301
                                debug(msg, parentWindow, (Exception)exception.get(i));
302
                }
303
                messageBoxError(msg, parentWindow);
304
        }
305

    
306
        /**
307
         * Muestra un dialogo de informaci?n con un texto y un bot?n de aceptar. El
308
         * mensaje informativo es registrado en el log de gvSIG con la excepcion que
309
         * se le pase por parametro.
310
         * @param msg Mensaje a mostrar en el dialogo. Identificador de la cadena a
311
         *          traducir
312
         * @param parentWindow Ventana desde la que se lanza el dialogo
313
         * @param exception Excepcion que ha sido recogida
314
         */
315
        public static void messageBoxInfo(String msg, Object parentWindow, Exception exception) {
316
                debug(msg, parentWindow, exception);
317
                messageBoxInfo(msg, parentWindow);
318
        }
319

    
320
        /**
321
         * Muestra un dialogo con un texto y un bot?n Si o No. El mensaje es
322
         * registrado en el log de gvSIG con la excepcion que se le pase por
323
         * parametro.
324
         * @param msg Mensaje a mostrar en el dialogo.
325
         * @param parentWindow Ventana desde la que se lanza el dialogo
326
         * @return El bot?n seleccionado por el usuario. true si ha seleccionado "si"
327
         *         y false si ha seleccionado "no"
328
         */
329
        public static boolean messageBoxYesOrNot(String msg, Object parentWindow, Exception exception) {
330
                debug(msg, parentWindow, exception);
331
                return messageBoxYesOrNot(msg, parentWindow);
332
        }
333

    
334
        /**
335
         * Carga una capa raster en una vista de gvSIG.
336
         * @param viewName Nombre de la vista donde ha de cargarse. Si vale null se cargar? en la
337
         * primera vista que encuentre que est? activa. Si no hay ninguna saltar? una excepci?n.
338
         * @param fileName Nombre del fichero a cargar. No debe ser nulo nunca.
339
         * @param layerName Nombre de la capa. Si es null se asignar? el nombre del
340
         * fichero sin extensi?n.
341
         * @throws RasterNotLoadException Excepci?n que se lanza cuando no se ha podido cargar la capa
342
         * por alg?n motivo.
343
         */
344
        public static FLayer loadLayer(String viewName, String fileName, String layerName) throws RasterNotLoadException {
345
                if(fileName ==  null)
346
                        return null;
347

    
348
                //Seleccionamos la vista de gvSIG
349
                View theView = null;
350
                try {
351
                        IWindow[] allViews = PluginServices.getMDIManager().getAllWindows();
352
                        if(viewName != null) {
353
                                for (int i = 0; i < allViews.length; i++) {
354
                                        if (allViews[i] instanceof View
355
                                                && PluginServices.getMDIManager().getWindowInfo((View) allViews[i]).getTitle().equals(viewName))
356
                                                theView = (View) allViews[i];
357
                                }
358
                        } else {
359
                                IWindow activeWindow = PluginServices.getMDIManager().getActiveWindow();
360
                                for (int i = 0; i < allViews.length; i++) {
361
                                        if (allViews[i] instanceof View && ((View)allViews[i]) == activeWindow) //En la primera vista activa
362
                                                theView = (View) allViews[i];
363
                                }
364
                                if(theView == null) {
365
                                        for (int i = 0; i < allViews.length; i++) {
366
                                                if (allViews[i] instanceof View) //En la primera vista
367
                                                        theView = (View) allViews[i];
368
                                        }
369
                                }
370
                        }
371

    
372
                        if (theView == null)
373
                                throw new RasterNotLoadException("Imposible cargar la capa.");
374
                } catch (ClassCastException ex) {
375
                        throw new RasterNotLoadException("No se puede hacer un casting de esa IWindow a View.");
376
                }
377

    
378
                theView.getMapControl().getMapContext().beginAtomicEvent();
379

    
380
                FLayer lyr = null;
381
                try {
382
                        if(layerName == null) {
383
                                int endIndex = fileName.lastIndexOf(".");
384
                                if (endIndex < 0)
385
                                        endIndex = fileName.length();
386
                                lyr = FLyrRasterSE.createLayer(
387
                                                fileName.substring(fileName.lastIndexOf(File.separator) + 1, endIndex),
388
                                                new File(fileName),
389
                                                theView.getMapControl().getProjection());
390
                        } else {
391
                                lyr = FLyrRasterSE.createLayer(
392
                                                layerName,
393
                                                new File(fileName),
394
                                                theView.getMapControl().getProjection());
395
                        }
396

    
397
                } catch (LoadLayerException e) {
398
                        throw new RasterNotLoadException("Error al cargar la capa.");
399
                }
400
                theView.getMapControl().getMapContext().getLayers().addLayer(lyr);
401
                theView.getMapControl().getMapContext().invalidate();
402
                theView.getMapControl().getMapContext().endAtomicEvent();
403
                return lyr;
404
        }
405
        
406
        /**
407
         * Calculo de las coordenadas de una ventana IWindow para que quede centrada sobre el 
408
         * MainFrame. Estas coordenadas solo valen para un IWindow ya que andami mete las ventanas
409
         * con coordenadas relativas a su ventanta principal.
410
         * @param widthWindow Ancho de la ventana a a?adir
411
         * @param heightWindow Alto de la ventana a a?adir
412
         * @return Array con el ancho y el alto 
413
         */
414
        public static Point iwindowPosition(int widthWindow, int heightWindow) {
415
                int posWindowX = 0;
416
                int posWindowY = 0;
417
                Dimension dim = null;
418
                Point pos = null;
419
                if(PluginServices.getMainFrame() instanceof Component) {
420
                        dim = ((Component)PluginServices.getMainFrame()).getSize();
421
                        pos = ((Component)PluginServices.getMainFrame()).getLocation();
422
                        if(dim != null && pos != null) {
423
                                posWindowX = ((dim.width >> 1) - (widthWindow >> 1));
424
                                posWindowY = ((dim.height >> 1) - (heightWindow >> 1) - 70);
425
                                return new Point(posWindowX, posWindowY);
426
                        }
427
                }
428
                return null;
429
        }
430
}