Statistics
| Revision:

gvsig-raster / org.gvsig.raster / trunk / org.gvsig.raster / org.gvsig.raster.app / org.gvsig.raster.app.common / src / main / java / org / gvsig / raster / mainplugin / RasterMainPluginUtils.java @ 2861

History | View | Annotate | Download (15.9 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.mainplugin;
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.JOptionPane;
31

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

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

    
69
        /**
70
         * Obtiene la lista de capas del TOC y devuelve las raster. Si hay capas agrupadas lo tiene en cuenta y mira
71
         * dentro de la agrupaci?n.
72
         * @param srcLyrs FLayers de la vista
73
         * @param destLyrs Lista de capas 
74
         * @return ArrayList con la lista de capas raster agrupadas o no. El orden en que aparecen
75
         * en la lista es de abajo a arriba las que aparecen en el TOC.
76
         */
77
        public static ArrayList<FLayer> getRasterLayerList(FLayers srcLyrs, ArrayList<FLayer> destLyrs) {
78
                if(destLyrs == null)
79
                        destLyrs = new ArrayList<FLayer>();
80
                for (int i = 0; i < srcLyrs.getLayersCount(); i++) {
81
                        if(srcLyrs.getLayer(i) instanceof DefaultFLyrRaster)
82
                                destLyrs.add(srcLyrs.getLayer(i));
83
                        if(srcLyrs.getLayer(i) instanceof FLayers)
84
                                destLyrs = getLayerList((FLayers)srcLyrs.getLayer(i), destLyrs);
85
                }
86
                return destLyrs;
87
        }
88
        
89
        /**
90
         * Obtiene la lista de capas del TOC y devuelve las raster. Si hay capas agrupadas lo tiene en cuenta y mira
91
         * dentro de la agrupaci?n.
92
         * @param srcLyrs FLayers de la vista
93
         * @param destLyrs Lista de capas 
94
         * @return ArrayList con la lista de capas raster agrupadas o no. El orden en que aparecen
95
         * en la lista es de abajo a arriba las que aparecen en el TOC.
96
         */
97
        public static ArrayList<FLayer> getLayerList(FLayers srcLyrs, ArrayList<FLayer> destLyrs) {
98
                if(srcLyrs == null)
99
                        return null;
100
                if(destLyrs == null)
101
                        destLyrs = new ArrayList<FLayer>();
102
                for (int i = 0; i < srcLyrs.getLayersCount(); i++) {
103
                        if(srcLyrs.getLayer(i) instanceof FLayers)
104
                                destLyrs = getLayerList((FLayers)srcLyrs.getLayer(i), destLyrs);
105
                        else 
106
                                destLyrs.add(srcLyrs.getLayer(i));
107
                }
108
                return destLyrs;
109
        }
110
        
111
        /**
112
         * Obtiene el nombre de la vista donde est? cargada la capa que se pasa por par?metro
113
         * @param layer Capa cargada en una vista
114
         * @return Nombre de la vista donde est? cargada la capa.
115
         */
116
        public static String getView(FLayer layer) {
117
//                Project p = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
118
                Project p = ProjectManager.getInstance().getCurrentProject();
119
                return p.getViewName(layer);        
120
        }
121
        
122
        /**
123
         * A?ade una ventana al gestor de ventanas
124
         * @param window
125
         */
126
        public static void addWindow(IWindow window) {
127
                PluginServices.getMDIManager().addWindow(window);
128
        }
129
        
130
        /**
131
         * Elimina una ventana al gestor de ventanas
132
         * @param window
133
         */
134
        public static void closeWindow(IWindow window) {
135
                PluginServices.getMDIManager().closeWindow(window);
136
        }
137
        
138
        /**
139
         * Selecciona los controles del panel de propiedades a partir de los par?mtros
140
         * obtenidos del driver. Este m?todo realiza una transformaci?n entre Params
141
         * obtenido del driver de escritura y los par?metros del panel de propiedades.
142
         * @param panel Panel de propiedades
143
         * @param params Par?metros del driver
144
         * @param notTakeIntoAccount Nombre de par?metros que no hay que tener en cuenta. Si es null se tienen en cuenta todos.
145
         */
146
        public static void loadPropertiesFromWriterParams(PropertiesComponent pComp, Params params, String[] notTakeIntoAccount) {
147
                for (int i = 0; i < params.getNumParams(); i++) {
148
                        Param p = params.getParam(i);
149
                        String name = Messages.getText(p.getId());
150
                        String key = p.getId();
151

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

    
164
                        Object[] types = null;
165
                        int selectedValue = 0;
166

    
167
                        switch (p.getType()) {
168
                                case Params.CHECK:
169
                                        pComp.addValue(name, key, p.getDefaultValue(), types);
170
                                        break;
171
                                case Params.CHOICE:
172
                                        ArrayList<String> list = new ArrayList<String>();
173
                                        for (int j = 0; j < p.getList().length; j++) {
174
                                                list.add(p.getList()[j]);
175
                                                if (p.getDefaultValue() instanceof Integer)
176
                                                        if (((Integer) p.getDefaultValue()).intValue() == j)
177
                                                                selectedValue = j;
178
                                        }
179
                                        types = new Object[] { new Integer(PropertiesComponent.TYPE_COMBO), list };
180
                                        pComp.addValue(name, key, new Integer(selectedValue), types);
181
                                        break;
182
                                case Params.SLIDER:
183
                                        types = new Object[] { new Integer(PropertiesComponent.TYPE_SLIDER), new Integer(p.getList()[0]), new Integer(p.getList()[1]) };
184
                                        pComp.addValue(name, key, p.getDefaultValue(), types);
185
                                        break;
186
                                default:
187
                                        pComp.addValue(Messages.getText(((Param)params.getParam(i)).getId()), params.getParam(i).getId(), params.getParam(i).getDefaultValue(), null);
188
                                        break;
189
                        }
190
                }
191
        }
192

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

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

    
245
        /**
246
         * Carga una capa raster en una vista de gvSIG.
247
         * @param viewName Nombre de la vista donde ha de cargarse. Si vale null se cargar? en la
248
         * primera vista que encuentre que est? activa. Si no hay ninguna saltar? una excepci?n.
249
         * @param fileName Nombre del fichero a cargar. No debe ser nulo nunca.
250
         * @param layerName Nombre de la capa. Si es null se asignar? el nombre del
251
         * fichero sin extensi?n.
252
         * @throws RasterNotLoadException Excepci?n que se lanza cuando no se ha podido cargar la capa
253
         * por alg?n motivo.
254
         */
255
        @SuppressWarnings("deprecation")
256
        public static FLayer loadLayer(String viewName, String fileName, String layerName) throws RasterNotLoadException {
257
                if(fileName ==  null)
258
                        return null;
259

    
260
                //Seleccionamos la vista de gvSIG
261
                AbstractViewPanel theView = null;
262
                try {
263
                        IWindow[] allViews = PluginServices.getMDIManager().getAllWindows();
264
                        if(viewName != null) {
265
                                for (int i = 0; i < allViews.length; i++) {
266
                                        if (allViews[i] instanceof AbstractViewPanel
267
                                                && (((AbstractViewPanel) allViews[i]).getDocument().getName().equals(viewName) ||
268
                                                        PluginServices.getMDIManager().getWindowInfo((AbstractViewPanel) allViews[i]).getTitle().equals(viewName)))
269
                                                theView = (AbstractViewPanel) allViews[i];
270
                                }
271
                        } else {
272
                                IWindow activeWindow = PluginServices.getMDIManager().getActiveWindow();
273
                                for (int i = 0; i < allViews.length; i++) {
274
                                        if (allViews[i] instanceof AbstractViewPanel && ((AbstractViewPanel)allViews[i]) == activeWindow) //En la primera vista activa
275
                                                theView = (AbstractViewPanel) allViews[i];
276
                                }
277
                                if(theView == null) {
278
                                        for (int i = 0; i < allViews.length; i++) {
279
                                                if (allViews[i] instanceof AbstractViewPanel) //En la primera vista
280
                                                        theView = (AbstractViewPanel) allViews[i];
281
                                        }
282
                                }
283
                        }
284

    
285
                        if (theView == null)
286
                                throw new RasterNotLoadException("Imposible cargar la capa.");
287
                } catch (ClassCastException ex) {
288
                        throw new RasterNotLoadException("No se puede hacer un casting de esa IWindow a View.");
289
                }
290

    
291
                theView.getMapControl().getMapContext().beginAtomicEvent();
292

    
293
                DefaultFLyrRaster lyr = null;
294
                try {
295
                        ProviderServices provServ = RasterLocator.getManager().getProviderServices();
296
                        RasterDataParameters storeParameters = provServ.createNotTiledParameters(fileName);
297
                        storeParameters.setSRS(theView.getProjection());
298
                        
299
                        MapContextManager mcm = MapContextLocator.getMapContextManager();
300
                        DataManager dataManager = DALLocator.getDataManager();
301
                        DataStore dataStore = null;
302
                        try {
303
                                dataStore = dataManager.createStore(storeParameters);
304
                        } catch (ValidateDataParametersException e) {
305
                                throw new RasterNotLoadException("Error al cargar la capa.");
306
                        } catch (InitializeException e) {
307
                                throw new RasterNotLoadException("Error al cargar la capa.");
308
                        } catch (ProviderNotRegisteredException e) {
309
                                throw new RasterNotLoadException("Error al cargar la capa.");
310
                        }
311
                        
312
                        lyr = new DefaultFLyrRaster();
313
                        
314
                        if(layerName == null) {
315
                                int endIndex = fileName.lastIndexOf(".");
316
                                if (endIndex < 0)
317
                                        endIndex = fileName.length();
318
                                
319
                                layerName = fileName.substring(fileName.lastIndexOf(File.separator) + 1, endIndex);
320
                        }
321
                        
322
                        lyr = (DefaultFLyrRaster) mcm.createLayer(layerName, dataStore);
323

    
324
                } catch (LoadLayerException e) {
325
                        throw new RasterNotLoadException("Error al cargar la capa.");
326
                } catch (InitializeException e) {
327
                        throw new RasterNotLoadException("Error creating parameters.");
328
                } catch (ProviderNotRegisteredException e) {
329
                        throw new RasterNotLoadException("Error creating parameters.");
330
                }
331
                theView.getMapControl().getMapContext().getLayers().addLayer(lyr);
332
                theView.getMapControl().getMapContext().invalidate();
333
                theView.getMapControl().getMapContext().endAtomicEvent();
334
                return lyr;
335
        }
336
        
337
        /**
338
         * Carga una capa raster en una vista de gvSIG.
339
         * @param viewName Nombre de la vista donde ha de cargarse. Si vale null se cargar? en la
340
         * primera vista que encuentre que est? activa. Si no hay ninguna saltar? una excepci?n.
341
         * @param fileName Nombre del fichero a cargar. No debe ser nulo nunca.
342
         * @param layerName Nombre de la capa. Si es null se asignar? el nombre del
343
         * fichero sin extensi?n.
344
         * @throws RasterNotLoadException Excepci?n que se lanza cuando no se ha podido cargar la capa
345
         * por alg?n motivo.
346
         */
347
        public static FLayer loadLayer(String viewName, FLayer lyr) throws RasterNotLoadException {
348
                if(lyr ==  null)
349
                        return null;
350

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

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

    
381
                theView.getMapControl().getMapContext().beginAtomicEvent();
382
                theView.getMapControl().getMapContext().getLayers().addLayer(lyr);
383
                theView.getMapControl().getMapContext().invalidate();
384
                theView.getMapControl().getMapContext().endAtomicEvent();
385
                return lyr;
386
        }
387
        
388
        /**
389
         * Calculo de las coordenadas de una ventana IWindow para que quede centrada sobre el 
390
         * MainFrame. Estas coordenadas solo valen para un IWindow ya que andami mete las ventanas
391
         * con coordenadas relativas a su ventanta principal.
392
         * @param widthWindow Ancho de la ventana a a?adir
393
         * @param heightWindow Alto de la ventana a a?adir
394
         * @return Array con el ancho y el alto 
395
         */
396
        public static Point iwindowPosition(int widthWindow, int heightWindow) {
397
                int posWindowX = 0;
398
                int posWindowY = 0;
399
                Dimension dim = null;
400
                Point pos = null;
401
                if(PluginServices.getMainFrame() instanceof Component) {
402
                        dim = ((Component)PluginServices.getMainFrame()).getSize();
403
                        pos = ((Component)PluginServices.getMainFrame()).getLocation();
404
                        if(dim != null && pos != null) {
405
                                posWindowX = ((dim.width >> 1) - (widthWindow >> 1));
406
                                posWindowY = ((dim.height >> 1) - (heightWindow >> 1) - 70);
407
                                return new Point(posWindowX, posWindowY);
408
                        }
409
                }
410
                return null;
411
        }
412
}