Statistics
| Revision:

root / trunk / extensions / extgvSIGPiloto-Raster / src / com / iver / cit / gvsig / project / documents / view / gui / dialogs / CutRasterDialog.java @ 9045

History | View | Annotate | Download (13.2 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 */
19
package com.iver.cit.gvsig.project.documents.view.gui.dialogs;
20

    
21
import java.awt.Dimension;
22
import java.awt.GridBagConstraints;
23
import java.awt.event.ActionEvent;
24
import java.awt.event.ActionListener;
25
import java.awt.event.ComponentEvent;
26
import java.awt.event.ComponentListener;
27
import java.io.File;
28
import java.io.FileNotFoundException;
29
import java.io.IOException;
30
import java.util.ArrayList;
31

    
32
import javax.swing.JFileChooser;
33
import javax.swing.JPanel;
34

    
35
import org.apache.log4j.Logger;
36
import org.cresques.io.data.CutRasterProcess;
37
import org.cresques.io.data.Grid;
38
import org.cresques.io.data.ICutRaster;
39
import org.cresques.io.data.IQueryableRaster;
40
import org.cresques.ui.raster.CutRasterPanel;
41
import org.gvsig.gui.beans.table.models.CheckBoxModel;
42

    
43
import com.hardcode.driverManager.Driver;
44
import com.iver.andami.PluginServices;
45
import com.iver.andami.Utilities;
46
import com.iver.andami.messages.NotificationManager;
47
import com.iver.andami.ui.mdiManager.IWindow;
48
import com.iver.andami.ui.mdiManager.WindowInfo;
49
import com.iver.cit.gvsig.fmap.DriverException;
50
import com.iver.cit.gvsig.fmap.MapControl;
51
import com.iver.cit.gvsig.fmap.drivers.RasterDriver;
52
import com.iver.cit.gvsig.fmap.layers.FLayer;
53
import com.iver.cit.gvsig.fmap.layers.FLyrRaster;
54
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
55
import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior;
56
import com.iver.cit.gvsig.fmap.tools.Behavior.MouseMovementBehavior;
57
import com.iver.cit.gvsig.fmap.tools.Behavior.RectangleBehavior;
58
import com.iver.cit.gvsig.project.documents.view.toolListeners.CutRasterListener;
59
import com.iver.cit.gvsig.project.documents.view.toolListeners.StatusBarListener;
60

    
61
public class CutRasterDialog extends JPanel implements IWindow, ActionListener,
62
                ComponentListener, ICutRaster {
63
                
64
        private static Logger logger = Logger.getLogger(CutRasterDialog.class.getName());
65
        
66
        private int                                                 width = 0, height = 0;
67
        /**
68
         * Panel de recortado de imagen que est? en la libreria raster
69
         */
70
        private CutRasterPanel                                cutPanel = null;
71
        /**
72
         * Capa raster cargada en la vista que es la fuente de datos
73
         */
74
        private FLyrRaster                                        fLayer = null;
75
        /**
76
         * Ancho y alto en pixeles de la imagen a recortar
77
         */
78
        private int                                                 widthPx = 0, heightPx = 0;
79
        /**
80
         * clase que realiza el proceso de recortado y extracci?n de bandas
81
         */
82
        private CutRasterProcess                        process = null;
83
        /**
84
         * Grid del raster fuente de datos
85
         */
86
        private Grid                                                 grid = null;
87
        /**
88
         * Valores iniciales de ancho y alto en pixeles de la ventana.
89
         */
90
        private double                                                 initWidth, initHeight;
91
        /**
92
         * Recuerda la ?ltima ruta seleccionada por el usuario
93
         */
94
        private static String                                lastPath = "./";
95
        /**
96
         * Lista de ficheros creados. Si se ha creado una imagen por banda solo 
97
         * tendr? un elemento, sino tendr? uno por banda.
98
         */
99
        private String[]                                        fileNames = null;
100

    
101
        /**
102
         * Constructor
103
         * @param width Ancho
104
         * @param height Alto
105
         */
106
        public CutRasterDialog(FLyrRaster layer, int width, int height){
107
                this.width = width;
108
                this.height = height;
109
                this.fLayer = layer;
110
        
111
                ArrayList attr = ((FLyrRaster)layer).getSource().getAttributes();
112
                   for (int i=0; i<attr.size(); i++) {
113
                        Object[] a = (Object []) attr.get(i);
114
                        if(a[0].toString().equals("Width"))
115
                                widthPx = ((Integer)a[1]).intValue();
116
                        if(a[0].toString().equals("Height"))
117
                                heightPx = ((Integer)a[1]).intValue();
118
                }
119
                
120
                GridBagConstraints gridBagConstraints = new GridBagConstraints();
121
                gridBagConstraints.gridx = 0;
122
                gridBagConstraints.gridy = 0;
123
                this.setPreferredSize(new Dimension(width, height));
124
                
125
                this.add(getPCut(), gridBagConstraints);
126
                this.addComponentListener(this);
127
                
128
                getPCut().getBSave().addActionListener(this);
129
                getPCut().getBAccept().addActionListener(this);
130
                getPCut().getBCancel().addActionListener(this);
131
        
132
        }
133
        
134
        /**
135
         * Obtiene el panel de recorte
136
         * @return TailImagePanel
137
         */
138
        public CutRasterPanel getPCut(){
139
                if(cutPanel == null){
140
                        try {
141
                                cutPanel = new CutRasterPanel(fLayer.getFullExtent(), widthPx, heightPx, this);
142
                        } catch (DriverException e) {
143
                                NotificationManager.addError("No se ha podido obtener el extent de la capa al crear el panel de recorte", e);
144
                                return null;
145
                        }
146
                        cutPanel.setComponentSize(this.width - 10, this.height - 40);
147
                        cutPanel.addComponentListener(this);
148
                }
149
                return cutPanel;
150
        }
151
        
152
        /**
153
         * Asigna el valor inicial en ancho y alto de la ventana en pixeles .
154
         * @param w Ancho en pixeles
155
         * @param h Alto en pixeles
156
         */
157
        public void setInitValuesToSize(double w, double h){
158
                initWidth = w;
159
                initHeight = h;
160
        }
161
                
162
        /**
163
         * @see com.iver.mdiApp.ui.MDIManager.View#getViewInfo()
164
         */
165
        public WindowInfo getWindowInfo() {
166
                WindowInfo m_viewinfo=new WindowInfo(WindowInfo.MODELESSDIALOG /*| ViewInfo.RESIZABLE*/);
167
            m_viewinfo.setTitle(PluginServices.getText(this, "recorte"));
168
            m_viewinfo.setWidth(width);
169
            m_viewinfo.setHeight(height - 36);
170
                return m_viewinfo;
171
        }
172

    
173
        
174
        /**
175
         * Al pulsar Cancelar o Aceptar la ventana se cierra.
176
         */
177
        public void actionPerformed(ActionEvent e) {                
178
                
179
                //Bot?n de Aceptar o Aplicar
180
                if(e.getSource() == cutPanel.getBAccept())
181
                        accept();
182
                
183
                //Bot?n de Cerrar
184
                if(e.getSource() == cutPanel.getBCancel()){
185
                        try{
186
                                PluginServices.getMDIManager().closeWindow(CutRasterDialog.this);
187
                        }catch(ArrayIndexOutOfBoundsException ex){
188
                                //Si la ventana no se puede eliminar no hacemos nada
189
                        }
190
                }
191
                
192
                //Bot?n de Salvar
193
                if(e.getSource() == cutPanel.getBSave())
194
                        saveRaster();
195
                                
196
                fLayer.getMapContext().invalidate();
197
        }
198

    
199
        /**
200
         * Acciones realizadas cuando se acepta en el dialogo. Se obtendr?n los datos de recorte desde el dialogo,
201
         * crearemos el objeto TailRasterProcess que gestiona el recortado, ajustamos el tama?o del grid
202
         * de salida y procesamos.
203
         */
204
        private void accept(){
205
                grid = fLayer.getGrid();
206
                
207
                //Obtenemos las coordenadas del recorte
208
                String[] sValues = cutPanel.getCoordPixel();
209
                int[] dValues = new int[sValues.length];
210
                try{
211
                        for(int i = 0; i < sValues.length; i ++)
212
                                dValues[i] = (int)Math.round(Double.valueOf(sValues[i]).doubleValue());
213
                }catch(NumberFormatException exc){
214
                        //Los valores de las cajas son incorrectos. Terminamos la funci?n
215
                        return ;
216
                }
217
                                        
218
                //Seleccionamos las bandas que se usaran en el recorte a partir de la tabla
219
                int countBands = 0;
220
                int rowCount = ((CheckBoxModel)getPCut().getTSelection().getModel()).getRowCount();
221
                for(int iRow = 0; iRow < rowCount; iRow++)
222
                        if((((Boolean)((CheckBoxModel)getPCut().getTSelection().getModel()).getValueAt(iRow, 0))).booleanValue())
223
                                countBands++;
224
                
225
                int[] drawableBands = new int[countBands];
226
                int i = 0;
227
                for(int iRow = 0; iRow < rowCount; iRow++){
228
                        if((((Boolean)((CheckBoxModel)getPCut().getTSelection().getModel()).getValueAt(iRow, 0))).booleanValue()){
229
                                drawableBands[i ++] = iRow;
230
                        }
231
                }
232
                                
233
                //Usamos el directorio de temporales de andami
234
                String tmpImgs = Utilities.createTempDirectory();
235
                
236
                process = new CutRasterProcess(        dValues,
237
                                                                                        drawableBands, 
238
                                                                                        grid, 
239
                                                                                        tmpImgs + File.separator + "cutLayer", cutPanel.getCbOneLyrPerBand().isSelected(),
240
                                                                                        (int)initWidth,
241
                                                                                        (int)initHeight,
242
                                                                                        this);
243
                
244
                //Remuestreamos por si se ha variado el tama?o del raster de salida
245
                grid.setAdjustedWindow((int)cutPanel.getWidthText(), (int)cutPanel.getHeightText(), IQueryableRaster.INTERPOLATION_NearestNeighbour, null);
246
                
247
                fileNames = process.createWriters(grid.getRasterBuf(), (int)cutPanel.getWidthText(), (int)cutPanel.getHeightText());
248
                process.start();
249
                getPCut().getBSave().setEnabled(true);
250
        
251
        }
252
        
253
        /**
254
         * Acciones realizadas cuando se salva los recortes de raster. Aparecer? un dialogo para introducir
255
         * la ruta y salvaremos el raster completo con el nombre proporcionado o si se ha salvado por bandas
256
         * se guardar? un fichero por cada una con el nombre proporcionado m?s _Bn.
257
         */
258
        private void saveRaster(){
259
                JFileChooser chooser = new JFileChooser(lastPath);
260
                chooser.setDialogTitle(PluginServices.getText(this, "seleccionar_directorio"));
261
                
262
                int returnVal = chooser.showOpenDialog(this);
263
                if(returnVal == JFileChooser.APPROVE_OPTION){
264
                         String fName = chooser.getSelectedFile().toString();
265

    
266
                         if(fileNames == null || fileNames.length == 0)
267
                                 return;
268
                         
269
                         try {
270
                                 if(fileNames.length == 1){
271
                                         if(!fName.endsWith(".tif"))
272
                                                 fName += ".tif";
273
                                         File oldFile = new File(fileNames[0]);
274
                                        org.cresques.util.Utilities.copyFile(fileNames[0], fName);
275
                                 }else{
276
                                         if(fName.endsWith(".tif"))
277
                                                 fName = fName.substring(0, fName.indexOf("."));
278
                                         for(int iFile = 0; iFile < fileNames.length; iFile ++){
279
                                                 File oldFile = new File(fileNames[iFile]);
280
                                                 org.cresques.util.Utilities.copyFile(fileNames[iFile], fName + "_B" + iFile + ".tif");
281
                                         }
282
                                 }
283
                         } catch (FileNotFoundException e1) {
284
                                logger.error(PluginServices.getText(this,"file_not_found "), e1);
285
                        } catch (IOException e1) {
286
                                logger.error(PluginServices.getText(this,"io_exception"), e1);
287
                        }                                         
288
                                 
289
                         lastPath = chooser.getCurrentDirectory().getAbsolutePath();
290
                }
291
                         
292
        }
293
        
294
        public void componentHidden(ComponentEvent e) {
295
                // TODO Auto-generated method stub
296
                
297
        }
298

    
299
        public void componentMoved(ComponentEvent e) {
300
                // TODO Auto-generated method stub
301
                
302
        }
303

    
304
        public void componentResized(ComponentEvent e) {
305
                PluginServices.getMDIManager().getWindowInfo(PluginServices.getMDIManager().getActiveWindow()).setWidth(cutPanel.getWidth()+10);
306
                PluginServices.getMDIManager().getWindowInfo(PluginServices.getMDIManager().getActiveWindow()).setHeight(cutPanel.getHeight()+40);
307
        }
308

    
309
        public void componentShown(ComponentEvent e) {
310
                
311
        }
312

    
313
        /**
314
         * Obtiene la capa raster
315
         * @return capa raster
316
         */
317
        public FLyrRaster getFLayer() {
318
                return fLayer;
319
        }
320

    
321
        /**
322
         * Acciones que se realizan al finalizar de crear los recortes de imagen.
323
         * Este m?todo es llamado por el thread TailRasterProcess al finalizar.
324
         */
325
        public void cutFinalize(String[] fileNames) {
326
                //seleccionamos la vista de gvSIG
327
                com.iver.cit.gvsig.project.documents.view.gui.View theView = null;
328
                try{
329
                        IWindow[] allViews = PluginServices.getMDIManager().getAllWindows();
330
                        for(int i = 0; i < allViews.length; i++){
331
                                if(allViews[i] instanceof com.iver.cit.gvsig.project.documents.view.gui.View)
332
                                        theView = (com.iver.cit.gvsig.project.documents.view.gui.View) allViews[i];                                        
333
                        }
334
                        
335
                }catch(ClassCastException ex){
336
                        logger.error(PluginServices.getText(this,"cant_get_view "), ex);
337
                        return;
338
                }
339
                
340
                //Cargamos las capas
341
                for(int iFName = 0; iFName < fileNames.length; iFName ++){
342
                        theView.getMapControl().getMapContext().beginAtomicEvent();
343
                        try {
344
                                Driver driver = LayerFactory.getDM().getDriver("gvSIG Image Driver");
345
                                FLayer lyr = LayerFactory.createLayer(fileNames[iFName].substring(fileNames[iFName].lastIndexOf(File.separator) + 1, fileNames[iFName].indexOf(".")), 
346
                                                (RasterDriver)driver, 
347
                                                new File(fileNames[iFName]),
348
                                                theView.getMapControl().getProjection());
349
                                theView.getMapControl().getMapContext().getLayers().addLayer(lyr);
350
                        }catch (DriverException e) {
351
                                //Intentamos cargar el siguiente 
352
                                continue;
353
                        }
354
                        theView.getMapControl().getMapContext().endAtomicEvent();
355
                }
356
                theView.getMapControl().getMapContext().invalidate();
357
                grid.free();
358
                
359
                /*try{
360
                        PluginServices.getMDIManager().closeView(this);
361
                }catch(ArrayIndexOutOfBoundsException ex){
362
                        //Si la ventana no se puede eliminar no hacemos nada
363
                }*/
364
        }
365

    
366
        /**
367
         * Acciones que se realizan para seleccionar la tool CutRaster
368
         */
369
        public void selectToolButton() {
370
                //seleccionamos la vista de gvSIG
371
                com.iver.cit.gvsig.project.documents.view.gui.View theView = null;
372
                try{
373
                        IWindow[] allViews = PluginServices.getMDIManager().getAllWindows();
374
                        for(int i = 0; i < allViews.length; i++){
375
                                if(allViews[i] instanceof com.iver.cit.gvsig.project.documents.view.gui.View)
376
                                        theView = (com.iver.cit.gvsig.project.documents.view.gui.View) allViews[i];                                        
377
                        }
378
                        
379
                }catch(ClassCastException ex){
380
                        logger.error(PluginServices.getText(this,"cant_get_view "), ex);
381
                        return;
382
                }
383
            MapControl m_MapControl = theView.getMapControl();
384
            
385
                //Listener de eventos de movimiento que pone las coordenadas del rat?n en la barra de estado
386
        StatusBarListener sbl = new StatusBarListener(m_MapControl);
387
        
388
        //Cortar Raster
389
        CutRasterListener crl = new CutRasterListener(m_MapControl, this);
390
        m_MapControl.addMapTool("cutRaster", new Behavior[]{
391
                                        new RectangleBehavior(crl), new MouseMovementBehavior(sbl)});
392
        
393
        m_MapControl.setTool("cutRaster");
394
        }
395

    
396
}