Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRasterTools-SE / src / org / gvsig / rastertools / clipping / ui / listener / ClippingPanelListener.java @ 30938

History | View | Annotate | Download (33.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.rastertools.clipping.ui.listener;
20

    
21
import java.awt.Component;
22
import java.awt.Cursor;
23
import java.awt.Dimension;
24
import java.awt.event.ActionEvent;
25
import java.awt.event.ActionListener;
26
import java.awt.geom.AffineTransform;
27
import java.awt.geom.NoninvertibleTransformException;
28
import java.awt.geom.Point2D;
29
import java.awt.geom.Rectangle2D;
30
import java.io.File;
31
import java.util.ArrayList;
32
import java.util.EventObject;
33

    
34
import javax.swing.JOptionPane;
35

    
36
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
37
import org.gvsig.gui.beans.buttonspanel.ButtonsPanel;
38
import org.gvsig.gui.beans.buttonspanel.ButtonsPanelEvent;
39
import org.gvsig.gui.beans.buttonspanel.ButtonsPanelListener;
40
import org.gvsig.gui.beans.coordinatespanel.CoordinatesEvent;
41
import org.gvsig.gui.beans.coordinatespanel.CoordinatesListener;
42
import org.gvsig.gui.beans.coordinatespanel.CoordinatesPanel;
43
import org.gvsig.gui.beans.datainput.DataInputContainerListener;
44
import org.gvsig.gui.beans.table.models.CheckBoxModel;
45
import org.gvsig.raster.IProcessActions;
46
import org.gvsig.raster.RasterLibrary;
47
import org.gvsig.raster.RasterProcess;
48
import org.gvsig.raster.buffer.WriterBufferServer;
49
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
50
import org.gvsig.raster.datastruct.Extent;
51
import org.gvsig.raster.grid.roi.ROI;
52
import org.gvsig.raster.hierarchy.IRasterGeoOperations;
53
import org.gvsig.raster.hierarchy.IRasterOperations;
54
import org.gvsig.raster.util.RasterToolsUtil;
55
import org.gvsig.raster.util.process.ClippingProcess;
56
import org.gvsig.rastertools.clipping.ClippingData;
57
import org.gvsig.rastertools.clipping.panels.ClippingCoordinatesPanel;
58
import org.gvsig.rastertools.clipping.panels.ClippingOptionsPanel;
59
import org.gvsig.rastertools.clipping.panels.ClippingResolutionPanel;
60
import org.gvsig.rastertools.clipping.panels.ClippingSelectionPanel;
61
import org.gvsig.rastertools.clipping.ui.ClippingPanel;
62
import org.gvsig.rastertools.saveraster.ui.info.EndInfoDialog;
63

    
64
import com.iver.andami.PluginServices;
65
import com.iver.andami.Utilities;
66
import com.iver.andami.ui.mdiManager.IWindow;
67
import com.iver.cit.gvsig.fmap.MapControl;
68
import com.iver.cit.gvsig.fmap.tools.BehaviorException;
69
import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior;
70
import com.iver.cit.gvsig.fmap.tools.Behavior.MouseMovementBehavior;
71
import com.iver.cit.gvsig.fmap.tools.Behavior.RectangleBehavior;
72
import com.iver.cit.gvsig.fmap.tools.Events.RectangleEvent;
73
import com.iver.cit.gvsig.fmap.tools.Listeners.RectangleListener;
74
import com.iver.cit.gvsig.project.documents.view.gui.BaseView;
75
import com.iver.cit.gvsig.project.documents.view.gui.View;
76
import com.iver.cit.gvsig.project.documents.view.toolListeners.StatusBarListener;
77
/**
78
 * <code>ClippingPanelListener</code> es una clase donde se recoger?n y
79
 * tratar?n todos los eventos del panel de recorte
80
 *
81
 * @version 19/04/2007
82
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
83
 */
84
public class ClippingPanelListener implements ActionListener, RectangleListener, ButtonsPanelListener, CoordinatesListener, DataInputContainerListener, IProcessActions {
85
        private Dimension             dim                     = new Dimension();
86
        private AffineTransform       at                      = null;
87
        private ClippingPanel         clippingPanel           = null;
88
        private ClippingData          data                    = null;
89
        private boolean               enableValueChangedEvent = true;
90

    
91
        private FLyrRasterSE          fLayer                  = null;
92
        private MapControl            mapControl              = null;
93

    
94
        /**
95
         * Herramienta seleccionada en el momento de la apertura del dialogo
96
         */
97
        private String                 lastTool                = null;
98

    
99
        private String                 viewName                = null;
100
        
101
        private static ClippingData    lastDataSaved           = null;
102
        
103
        /**
104
         * Crea un nuevo <code>ClippingPanelListener</code> con el
105
         * <code>ClippingPanelListener</code> asociado
106
         * @param panel
107
         */
108
        public ClippingPanelListener(ClippingPanel clippingPanel) {
109
                this.clippingPanel = clippingPanel;
110
        }
111
        
112
        /**
113
         * Asigna el modelo de datos
114
         * @param data
115
         */
116
        public void setData(ClippingData data) {
117
                this.data = data;
118
        }
119

    
120
        /**
121
         * Asigna la matriz de transformaci?n entre puntos en coordenadas del raster y
122
         * puntos en coordenadas reales.
123
         * @param AffineTransform
124
         */
125
        private void setAffineTransform(AffineTransform at) {
126
                this.at = at;
127
        }
128

    
129
        /**
130
         * Asigna la dimensi?n del raster
131
         * @param dim
132
         */
133
        public void setDimension(Dimension dim) {
134
                this.dim = dim;
135
        }
136

    
137
        /**
138
         * M?todo que se invoca cuando se disparan los eventos de los botones de
139
         * extensi?n completa o de seleccion de extensi?n con el rat?n
140
         */
141
        @SuppressWarnings("unchecked")
142
        public void actionPerformed(ActionEvent e) {
143
                // Bot?n de selecci?n del extent completo
144
                // Modificamos las coordenadas reales y recalculamos las coordenadas pixel
145
                if (e.getSource() == getResolutionPanel().getButtonRestore()) {
146
                        getClippingPanel().restoreStatus(data);
147
                }
148
                
149
                //Load parameters
150
                if (e.getSource() == getCoordinatesPanel().getButtonBarContainer().getButton(0)) {
151
                        if(lastDataSaved != null) {
152
                                data = (ClippingData)lastDataSaved.clone();
153
                                data.addObserver(getClippingPanel());
154
                                data.updateObservers();
155
                                getClippingPanel().getButtonsPanel().getButton(ButtonsPanel.BUTTON_APPLY).setEnabled(true);
156
                                getClippingPanel().getButtonsPanel().getButton(ButtonsPanel.BUTTON_ACCEPT).setEnabled(true);
157
                        } else 
158
                                RasterToolsUtil.messageBoxError(RasterToolsUtil.getText(this, "no_data_saved"), null);
159
                }
160
                
161
                //Save parameters
162
                if (e.getSource() == getCoordinatesPanel().getButtonBarContainer().getButton(1)) {
163
                        lastDataSaved = (ClippingData)data.clone();
164
                }
165
                
166
                //Bot?n de selecci?n del ?rea m?xima asociada a los ROIs
167
                if (e.getSource() == getCoordinatesPanel().getButtonBarContainer().getButton(2)) {
168
                        ArrayList roiList = getFLayer().getRois();
169
                        if(roiList != null && roiList.size() > 0) {
170
                                Extent ext = ROI.getROIsMaximunExtent(roiList);
171
                                assignROISExtent(ext, getFLayer());
172
                        } else
173
                                assignFullExtent();
174
                        return;
175
                }
176

    
177
                // Bot?n de selecci?n del extent completo
178
                // Modificamos las coordenadas reales y recalculamos las coordenadas pixel
179
                if (e.getSource() == getCoordinatesPanel().getButtonBarContainer().getButton(3)) {
180
                        assignFullExtent();
181
                        return;
182
                }
183

    
184
                // Bot?n de selecci?n de la herramienta de seleccionar desde la vista
185
                if (e.getSource() == getCoordinatesPanel().getButtonBarContainer().getButton(4)) {
186
                        selectToolButton();
187
                        return;
188
                }
189
                
190
        }
191
        
192
        /**
193
         * Asigna el extent completo a los cuadros de texto donde se introducen las coordenadas
194
         * reales y p?xel. 
195
         */
196
        private void assignROISExtent(Extent ext, FLyrRasterSE layer) {
197
                AffineTransform at = layer.getAffineTransform();
198
                Point2D ulWc = new Point2D.Double(ext.minX(), ext.maxY());
199
                Point2D lrWc = new Point2D.Double(ext.maxX(), ext.minY());
200
                Point2D llWc = new Point2D.Double(ext.minX(), ext.minY());
201
                Point2D urWc = new Point2D.Double(ext.maxX(), ext.maxY());
202
                
203
                ulWc = getFLayer().adjustWorldRequest(ulWc);
204
                lrWc = getFLayer().adjustWorldRequest(lrWc);
205
                llWc = getFLayer().adjustWorldRequest(llWc);
206
                urWc = getFLayer().adjustWorldRequest(urWc);
207
                
208
                Point2D ulPx = new Point2D.Double();
209
                Point2D lrPx = new Point2D.Double();
210
                Point2D llPx = new Point2D.Double();
211
                Point2D urPx = new Point2D.Double();
212
                
213
                try {
214
                        at.inverseTransform(ulWc, ulPx);
215
                        at.inverseTransform(lrWc, lrPx);
216
                        at.inverseTransform(ulWc, llPx);
217
                        at.inverseTransform(lrWc, urPx);
218
                } catch (NoninvertibleTransformException e) {
219
                        JOptionPane.showMessageDialog((Component) PluginServices.getMainFrame(), PluginServices.getText(this, "coordenadas_erroneas"));
220
                        return;
221
                }
222

    
223
                data.setCoorPixel(ulPx, lrPx, llPx, urPx);
224
                data.setCoorReal(ulWc, lrWc, llWc, urWc);
225
                data.setAffineTransform(at);
226
                data.initSize();
227
                getClippingPanel().saveStatus(data);
228
                
229
                getClippingPanel().getButtonsPanel().getButton(ButtonsPanel.BUTTON_APPLY).setEnabled(true);
230
                getClippingPanel().getButtonsPanel().getButton(ButtonsPanel.BUTTON_ACCEPT).setEnabled(true);
231
        }
232
        
233
        /**
234
         * Asigna el extent completo a los cuadros de texto donde se introducen las coordenadas
235
         * reales y p?xel. 
236
         */
237
        private void assignFullExtent() {
238
                Point2D ulPx = new Point2D.Double(0, 0);
239
                Point2D lrPx = new Point2D.Double(dim.width, dim.height);
240
                Point2D urPx = new Point2D.Double(dim.width, 0);
241
                Point2D llPx = new Point2D.Double(0, dim.height);
242

    
243
                //Convertimos nuevamente a coordenadas reales
244
                Point2D ulWc = new Point2D.Double();
245
                Point2D lrWc = new Point2D.Double();
246
                Point2D urWc = new Point2D.Double();
247
                Point2D llWc = new Point2D.Double();
248
                at.transform(ulPx, ulWc);
249
                at.transform(lrPx, lrWc);
250
                at.transform(urPx, urWc);
251
                at.transform(llPx, llWc);
252

    
253
                ulPx = new Point2D.Double(0, 0);
254
                lrPx = new Point2D.Double(dim.width - 1, dim.height - 1);
255
                urPx = new Point2D.Double(dim.width - 1, 0);
256
                llPx = new Point2D.Double(0, dim.height - 1);
257
                
258
                data.setCoorPixel(ulPx, lrPx, llPx, urPx);
259
                data.setCoorReal(ulWc, lrWc, llWc, urWc);
260
                data.setAffineTransform(at);
261
                data.initSize();
262

    
263
                getClippingPanel().saveStatus(data);
264
                getClippingPanel().getButtonsPanel().getButton(ButtonsPanel.BUTTON_APPLY).setEnabled(true);
265
                getClippingPanel().getButtonsPanel().getButton(ButtonsPanel.BUTTON_ACCEPT).setEnabled(true);
266
        }
267
                
268
        /**
269
         * Al producirse un evento de perdida de foco o pulsaci?n de "enter" en un campo de texto de coordenadas
270
         * hay que asignar el nuevo valor introducido.
271
         * @param obj
272
         */
273
        private void eventJTextField(CoordinatesEvent e) {
274
                try {
275
                        if (e.getSource() == getCoordinatesPanel().getPixelCoordinates()) {
276
                                if (e.getName().equals("11")) {
277
                                        data.setUlxPx(Double.valueOf(getCoordinatesPanel().getPixelCoordinates().getValue11()).doubleValue());
278
                                        data.setLlxPx(Double.valueOf(getCoordinatesPanel().getPixelCoordinates().getValue11()).doubleValue());
279
                                }
280
                                if (e.getName().equals("12")) {
281
                                        data.setUlyPx(Double.valueOf(getCoordinatesPanel().getPixelCoordinates().getValue12()).doubleValue());
282
                                        data.setUryPx(Double.valueOf(getCoordinatesPanel().getPixelCoordinates().getValue12()).doubleValue());
283
                                }
284
                                if (e.getName().equals("21")) {
285
                                        data.setLrxPx(Double.valueOf(getCoordinatesPanel().getPixelCoordinates().getValue21()).doubleValue());
286
                                        data.setUrxPx(Double.valueOf(getCoordinatesPanel().getPixelCoordinates().getValue21()).doubleValue());
287
                                }
288
                                if (e.getName().equals("22")) {
289
                                        data.setLryPx(Double.valueOf(getCoordinatesPanel().getPixelCoordinates().getValue22()).doubleValue());
290
                                        data.setLlyPx(Double.valueOf(getCoordinatesPanel().getPixelCoordinates().getValue22()).doubleValue());
291
                                }
292
                                data.updateObservers();
293
                        }
294

    
295
                        if (e.getSource() == getCoordinatesPanel().getRealCoordinates()) {
296
                                if (e.getName().equals("11")) {
297
                                        data.setUlxWc(Double.valueOf(getCoordinatesPanel().getRealCoordinates().getValue11()).doubleValue());
298
                                        data.setLlxWc(Double.valueOf(getCoordinatesPanel().getRealCoordinates().getValue11()).doubleValue());
299
                                }
300
                                if (e.getName().equals("12")) {
301
                                        data.setUlyWc(Double.valueOf(getCoordinatesPanel().getRealCoordinates().getValue12()).doubleValue());
302
                                        data.setUryWc(Double.valueOf(getCoordinatesPanel().getRealCoordinates().getValue12()).doubleValue());
303
                                }
304
                                if (e.getName().equals("21")) {
305
                                        data.setLrxWc(Double.valueOf(getCoordinatesPanel().getRealCoordinates().getValue21()).doubleValue());
306
                                        data.setUrxWc(Double.valueOf(getCoordinatesPanel().getRealCoordinates().getValue21()).doubleValue());
307
                                }
308
                                if (e.getName().equals("22")) {
309
                                        data.setLryWc(Double.valueOf(getCoordinatesPanel().getRealCoordinates().getValue22()).doubleValue());
310
                                        data.setLlyWc(Double.valueOf(getCoordinatesPanel().getRealCoordinates().getValue22()).doubleValue());
311
                                }
312
                                data.updateObservers();
313
                        }
314
                } catch (NumberFormatException ex1) {
315
                        // No hay valores parseables a decimal en las cajas de texto. No hacemos nada
316
                }
317
        }
318

    
319
        /**
320
         * Recalcula el valor de los campos de coordenadas reales y pixel. Cuando modificamos alg?n campo
321
         * de las coordenadas reales se modifican los pixeles y viceversa.
322
         * @param modifyPx true si se ha modificado alg?n campo de coordenadas pixel y false si se ha modificado
323
         * alg?n campo de las coordenadas reales.
324
         */
325
        private void recalcCoordFields(boolean modifyPx, boolean modifyUL, boolean modifyX) {
326
                try {
327
                        getClippingPanel().getButtonsPanel().getButton(ButtonsPanel.BUTTON_APPLY).setEnabled(false);
328
                        getClippingPanel().getButtonsPanel().getButton(ButtonsPanel.BUTTON_ACCEPT).setEnabled(false);
329

    
330
                        if (modifyPx) {
331
                                Point2D ulPx = new Point2D.Double(data.getUlxPx(), data.getUlyPx());
332
                                Point2D lrPx = new Point2D.Double(data.getLrxPx(), data.getLryPx());
333
                                Point2D llPx = new Point2D.Double(data.getLlxPx(), data.getLlyPx());
334
                                Point2D urPx = new Point2D.Double(data.getUrxPx(), data.getUryPx());
335

    
336
                                //Comprobamos que las esquinas no esten cambiadas de sitio
337
                                //Mueve la ULX
338
                                if(modifyUL && modifyX) {
339
                                        if(ulPx.getX() > lrPx.getX()) {
340
                                                urPx.setLocation(dim.width, urPx.getY());
341
                                                lrPx.setLocation(dim.width, lrPx.getY());
342
                                        }
343
                                }
344
                                
345
                                //Mueve la LRX
346
                                if(!modifyUL && modifyX) {
347
                                        if(lrPx.getX() < ulPx.getX()) {
348
                                                ulPx.setLocation(0, ulPx.getY());
349
                                                llPx.setLocation(0, llPx.getY());
350
                                        }
351
                                }
352
                                
353
                                //Mueve la ULY
354
                                if(modifyUL && !modifyX) {
355
                                        if(ulPx.getY() > lrPx.getY()) {
356
                                                llPx.setLocation(llPx.getX(), dim.height);
357
                                                lrPx.setLocation(lrPx.getX(), dim.height);
358
                                        }
359
                                }
360

    
361
                                //Mueve la LRY
362
                                if(!modifyUL && !modifyX) {
363
                                        if(lrPx.getY() < ulPx.getY()) {
364
                                                ulPx.setLocation(ulPx.getX(), 0);
365
                                                urPx.setLocation(urPx.getX(), 0);
366
                                        }
367
                                }
368
                                                                
369
                                //Ajustamos la selecci?n al ?rea
370
                                ulPx = adjustPixelRequest(ulPx);
371
                                lrPx = adjustPixelRequest(lrPx);
372

    
373
                                Point2D ulWc = new Point2D.Double();
374
                                Point2D lrWc = new Point2D.Double();
375
                                Point2D llWc = new Point2D.Double();
376
                                Point2D urWc = new Point2D.Double();
377
                                
378
                                at.transform(ulPx, ulWc);
379
                                at.transform(lrPx, lrWc);
380
                                at.transform(llPx, llWc);
381
                                at.transform(urPx, urWc);
382

    
383
                                data.setCoorPixel(ulPx, lrPx, llPx, urPx);
384
                                data.setCoorReal(ulWc, lrWc, llWc, urWc);
385
                                data.setAffineTransform(at);
386
                                data.initSize();
387

    
388
                                getClippingPanel().saveStatus(data);
389
                                
390
                                getClippingPanel().getButtonsPanel().getButton(ButtonsPanel.BUTTON_APPLY).setEnabled(true);
391
                                getClippingPanel().getButtonsPanel().getButton(ButtonsPanel.BUTTON_ACCEPT).setEnabled(true);
392
                        } else {
393
                                Point2D ulWc = new Point2D.Double(data.getUlxWc(), data.getUlyWc());
394
                                Point2D lrWc = new Point2D.Double(data.getLrxWc(), data.getLryWc());
395
                                Point2D llWc = new Point2D.Double(data.getLlxWc(), data.getLlyWc());
396
                                Point2D urWc = new Point2D.Double(data.getUrxWc(), data.getUryWc());
397
                                
398
                                //Mueve la ULX
399
                                if(modifyUL && modifyX) {
400
                                        if(ulWc.getX() > lrWc.getX()) {
401
                                                urWc.setLocation(fLayer.getMaxX(), urWc.getY());
402
                                                lrWc.setLocation(fLayer.getMaxX(), lrWc.getY());
403
                                        }
404
                                }
405
                                
406
                                //Mueve la LRX
407
                                if(!modifyUL && modifyX) {
408
                                        if(lrWc.getX() < ulWc.getX()) {
409
                                                ulWc.setLocation(fLayer.getMinX(), ulWc.getY());
410
                                                llWc.setLocation(fLayer.getMinX(), llWc.getY());
411
                                        }
412
                                }
413
                                
414
                                //Mueve la ULY
415
                                if(modifyUL && !modifyX) {
416
                                        if(ulWc.getY() < lrWc.getY()) {
417
                                                llWc.setLocation(llWc.getX(), fLayer.getMinY());
418
                                                lrWc.setLocation(lrWc.getX(), fLayer.getMinY());
419
                                        }
420
                                }
421

    
422
                                //Mueve la LRY
423
                                if(!modifyUL && !modifyX) {
424
                                        if(lrWc.getY() > ulWc.getY()) {
425
                                                ulWc.setLocation(ulWc.getX(), fLayer.getMaxY());
426
                                                urWc.setLocation(urWc.getX(), fLayer.getMaxY());
427
                                        }
428
                                }
429
                                
430
                                //Ajustamos la selecci?n al ?rea
431
                                ulWc = getFLayer().adjustWorldRequest(ulWc);
432
                                lrWc = getFLayer().adjustWorldRequest(lrWc);
433
                                llWc = getFLayer().adjustWorldRequest(llWc);
434
                                urWc = getFLayer().adjustWorldRequest(urWc);
435
                                
436
                                Point2D ulPx = new Point2D.Double();
437
                                Point2D lrPx = new Point2D.Double();
438
                                Point2D llPx = new Point2D.Double();
439
                                Point2D urPx = new Point2D.Double();
440
                                
441
                                try {
442
                                        at.inverseTransform(ulWc, ulPx);
443
                                        at.inverseTransform(lrWc, lrPx);
444
                                        at.inverseTransform(llWc, llPx);
445
                                        at.inverseTransform(urWc, urPx);
446
                                } catch (NoninvertibleTransformException e) {
447
                                        JOptionPane.showMessageDialog((Component) PluginServices.getMainFrame(), PluginServices.getText(this, "coordenadas_erroneas"));
448
                                        return;
449
                                }
450

    
451
                                adjustPoints(ulPx, lrPx);
452
                                adjustPoints(llPx, urPx);
453
                                data.setCoorPixel(ulPx, lrPx, llPx, urPx);
454
                                data.setCoorReal(ulWc, lrWc, llWc, urWc);
455
                                data.setAffineTransform(at);
456
                                data.initSize();
457
                                getClippingPanel().saveStatus(data);
458
                                
459
                                getClippingPanel().getButtonsPanel().getButton(ButtonsPanel.BUTTON_APPLY).setEnabled(true);
460
                                getClippingPanel().getButtonsPanel().getButton(ButtonsPanel.BUTTON_ACCEPT).setEnabled(true);
461
                        }
462
                } catch (NumberFormatException ex) {
463
                        return;
464
                }
465

    
466
        }
467
        
468
        /**
469
         * Turns world coordinates into entire numbers to avoid rounds errors 
470
         * @param ul
471
         *        Upper left coordinate
472
         * @param lr
473
         *        Lower right coordinate
474
         */
475
        private void adjustPoints(Point2D ul, Point2D lr) {
476
                double a = (ul.getX() - (int)ul.getX());
477
                double b = (ul.getY() - (int)ul.getY());
478
                double c = (lr.getX() - (int)lr.getX());
479
                double d = (lr.getY() - (int)lr.getY());
480
                ul.setLocation(        (a > 0.95 || a < 0.05) ? Math.round(ul.getX()) : ul.getX(), 
481
                                                (b > 0.95 || b < 0.05) ? Math.round(ul.getY()) : ul.getY());
482
                lr.setLocation(        (c > 0.95 || c < 0.05) ? Math.round(lr.getX()) : lr.getX(), 
483
                                                (d > 0.95 || d < 0.05) ? Math.round(lr.getY()) : lr.getY());
484
        }
485

    
486
        /**
487
         * Ajusta las coordenadas especificadas en los par?metros al ?rea m?xima
488
         * del raster en p?xeles
489
         * @param req
490
         */
491
        private Point2D adjustPixelRequest(Point2D req) {
492
                req.setLocation(Math.max(0, req.getX()), Math.max(0, req.getY()));
493
                req.setLocation(Math.min(dim.width, req.getX()), Math.min(dim.height, req.getY()));
494
                return req;
495
        }
496
        
497
        /**
498
         * Invocaci?n de los eventos de la ventana de <code>DefaultButtonsPanel</code>
499
         */
500
        public void actionButtonPressed(ButtonsPanelEvent e) {
501
                // Bot?n de Aceptar
502
                if (e.getButton() == ButtonsPanel.BUTTON_ACCEPT) {
503
                        accept();
504
                        close();
505
                }
506

    
507
                // Bot?n de Aplicar
508
                if (e.getButton() == ButtonsPanel.BUTTON_APPLY) 
509
                        accept();
510

    
511
                // Bot?n de Cerrar
512
                if (e.getButton() == ButtonsPanel.BUTTON_CANCEL)
513
                        close();
514

    
515
                getFLayer().getMapContext().invalidate();
516
        }
517

    
518
        /**
519
         * Cerrar la ventana del recorte
520
         */
521
        private void close() {
522
                try {
523
                        if (getLastTool() != null)
524
                                getMapControl().setTool(getLastTool());
525
                        PluginServices.getMDIManager().closeWindow(getClippingPanel().getClippingDialog());
526
                } catch (ArrayIndexOutOfBoundsException ex) {
527
                        // Si la ventana no se puede eliminar no hacemos nada
528
                }
529
        }
530

    
531
        /**
532
         * Obtener el <code>ClippingPanel</code> asociado
533
         * @return ClippingPanel
534
         */
535
        private ClippingPanel getClippingPanel() {
536
                return clippingPanel;
537
        }
538

    
539
        private ClippingCoordinatesPanel getCoordinatesPanel() {
540
                return getClippingPanel().getCoordinatesPanel();
541
        }
542

    
543
        private ClippingResolutionPanel getResolutionPanel() {
544
                return getClippingPanel().getResolutionPanel();
545
        }
546

    
547
        private ClippingOptionsPanel getOptionsPanel() {
548
                return getClippingPanel().getOptionsPanel();
549
        }
550

    
551
        private ClippingSelectionPanel getSelectionPanel() {
552
                return getClippingPanel().getSelectionPanel();
553
        }
554

    
555
        /**
556
         * Acciones realizadas cuando se acepta en el dialogo. Se obtendr?n los datos
557
         * de recorte desde el dialogo, crearemos el objeto ClippingProcess que
558
         * gestiona el recortado, ajustamos el tama?o del grid de salida y procesamos.
559
         */
560
        private void accept() {
561
                // Controlamos las coordenadas del recorte que no se salgan de la imagen.
562
                // De ser as? mostramos un error
563
                CoordinatesPanel coordinatesReales = getCoordinatesPanel().getRealCoordinates();
564
                double ulx = 0;
565
                double lrx = 0;
566
                double lry = 0;
567
                double uly = 0;
568
                try {
569
                        ulx = Double.parseDouble(coordinatesReales.getValue11());
570
                        lry = Double.parseDouble(coordinatesReales.getValue22());
571
                        lrx = Double.parseDouble(coordinatesReales.getValue21());
572
                        uly = Double.parseDouble(coordinatesReales.getValue12());
573
                        Rectangle2D ext = getFLayer().getFullExtent();
574
                        if (((int) ulx) > ((int) ext.getMaxX()) || ((int) lrx) < ((int) ext.getMinX()) || ((int) uly) > ((int) ext.getMaxY()) || ((int) lry) < ((int) ext.getMinY())) {
575
                                RasterToolsUtil.messageBoxError(RasterToolsUtil.getText(this, "coordenadas_erroneas"), null);
576
                                return;
577
                        }
578
                } catch (NumberFormatException e) {
579
                        RasterToolsUtil.messageBoxError(RasterToolsUtil.getText(this, "coordenadas_erroneas"), null);
580
                        return;
581
                } 
582

    
583
                double[] wcValues = data.getWcCoordinatesToClip();
584

    
585
                // Seleccionamos las bandas que se usaran en el recorte a partir de la tabla
586
                int countBands = 0;
587
                int rowCount = ((CheckBoxModel) getSelectionPanel().getTableContainer().getModel()).getRowCount();
588
                for (int iRow = 0; iRow < rowCount; iRow++)
589
                        if ((((Boolean) ((CheckBoxModel) getSelectionPanel().getTableContainer().getModel()).getValueAt(iRow, 0))).booleanValue())
590
                                countBands++;
591

    
592
                int[] drawableBands = new int[countBands];
593
                int i = 0;
594
                for (int iRow = 0; iRow < rowCount; iRow++) {
595
                        if ((((Boolean) ((CheckBoxModel) getSelectionPanel().getTableContainer().getModel()).getValueAt(iRow, 0))).booleanValue()) {
596
                                int row = ((Integer) ((CheckBoxModel) getSelectionPanel().getTableContainer().getModel()).getValueAt(iRow, 2)).intValue();
597
                                drawableBands[i++] = row;
598
                        }
599
                }
600

    
601
                /**
602
                 * Donde se va a guardar el fichero
603
                 */
604
                String path;
605
                if (getOptionsPanel().getCbSaveFile().isSelected()) {
606
                        path = getOptionsPanel().getDirectoryTextField().getText();
607
                        File f = new File(path);
608
                        if(!f.exists() || !f.canWrite()) {
609
                                RasterToolsUtil.messageBoxError(RasterToolsUtil.getText(this, "path_not_valid"), null);
610
                                return;
611
                        }
612
                } else
613
                        path = Utilities.createTempDirectory();
614

    
615
                String file = getOptionsPanel().getFilenameTextField().getText();
616
                if (file.compareTo(RasterLibrary.getOnlyLayerName()) == 0)
617
                        RasterLibrary.usesOnlyLayerName();
618

    
619
                if (file == "")
620
                        file = "cutlayer";
621

    
622
                String filename = path + File.separator + file;
623

    
624
                if (new File(filename + ".tif").exists())
625
                        if (!RasterToolsUtil.messageBoxYesOrNot("raster_error_file_exists", getOptionsPanel()))
626
                                return;
627

    
628
                /**
629
                 * Preparacion para la generacion del proceso del recorte
630
                 */
631
                if (getFLayer() == null)
632
                        return;
633

    
634
                WriterBufferServer dataWriter1 = new WriterBufferServer();
635

    
636
                AffineTransform transf = calcAffineTransform(ulx, uly, lrx, lry, 
637
                                                                                                        Math.round(data.getPxWidth()), Math.round(data.getPxHeight()), at);
638

    
639
                int interpMethod = getResolutionPanel().getSelectedInterpolationMethod();
640

    
641
                // Creamos la interpretaci?n de color para el caso de que la salida tenga
642
                // m?s de una banda por fichero. Siempre creamos RED, GREEN y BLUE
643
                String[] ci = new String[drawableBands.length];
644
                for (int j = 0; j < ci.length; j++) {
645
                        switch (j) {
646
                                case 0:
647
                                        if (ci.length >= 3)
648
                                                ci[j] = DatasetColorInterpretation.RED_BAND;
649
                                        else
650
                                                ci[j] = DatasetColorInterpretation.GRAY_BAND;
651
                                        break;
652
                                case 1:
653
                                        if (ci.length >= 3)
654
                                                ci[j] = DatasetColorInterpretation.GREEN_BAND;
655
                                        else
656
                                                ci[j] = DatasetColorInterpretation.UNDEF_BAND;
657
                                        break;
658
                                case 2:
659
                                        ci[j] = DatasetColorInterpretation.BLUE_BAND;
660
                                        break;
661
                                default:
662
                                        ci[j] = DatasetColorInterpretation.UNDEF_BAND;
663
                                        break;
664
                        }
665
                }
666

    
667
                RasterProcess clippingProcess = new ClippingProcess();
668
                clippingProcess.setActions(this);
669
                clippingProcess.addParam("viewname", getViewName());
670
                //clippingProcess.addParam("pixelcoordinates", pxValues);
671
                clippingProcess.addParam("realcoordinates", wcValues);
672
                clippingProcess.addParam("filename", filename);
673
                clippingProcess.addParam("datawriter", dataWriter1);
674
                clippingProcess.addParam("layer", getFLayer());
675
                clippingProcess.addParam("drawablebands", drawableBands);
676
                clippingProcess.addParam("onelayerperband", new Boolean(getOptionsPanel().getCbOneLyrPerBand().isSelected()));
677
                clippingProcess.addParam("interpolationmethod", new Integer(interpMethod));
678
                clippingProcess.addParam("affinetransform", transf);
679
                clippingProcess.addParam("colorInterpretation", new DatasetColorInterpretation(ci));
680
                clippingProcess.addParam("resolution", new int[]{(int) Math.round(data.getPxWidth()),
681
                                                                                                                 (int) Math.round(data.getPxHeight())});
682
                clippingProcess.start();
683
        }
684

    
685
        /**
686
         * Calcula la matriz de transformaci?n que se usar? para el nuevo raster generado.
687
         * @param ulx Coordenada X real de la esquina superior izquierda
688
         * @param uly Coordenada Y real de la esquina superior izquierda
689
         * @param lrx Coordenada X real de la esquina inferior derecha
690
         * @param lry Coordenada Y real de la esquina inferior derecha
691
         * @param width Ancho en p?xeles del nuevo raster
692
         * @param height Alto en p?xeles del nuevo raster
693
         * @param trans Matriz de transformaci?n de la nueva capa
694
         * @return Matriz de transformaci?n para el nuevo raster
695
         */
696
        private AffineTransform calcAffineTransform(double ulx, double uly, double lrx, double lry, 
697
                                                                                                double width, double height, AffineTransform trans) {
698
                Point2D ul = new Point2D.Double(ulx, uly);
699
                Point2D lr = new Point2D.Double(lrx, lry);
700
                try {
701
                        trans.inverseTransform(ul, ul);
702
                        trans.inverseTransform(lr, lr);
703
                } catch (NoninvertibleTransformException e) {
704
                        JOptionPane.showMessageDialog(null, RasterToolsUtil.getText(this, "coordenadas_erroneas"));
705
                        return new AffineTransform();
706
                }
707
                double w = Math.abs(lr.getX() - ul.getX());
708

    
709
                Point2D ur = new Point2D.Double(ul.getX() + w, ul.getY());
710
                Point2D ll = new Point2D.Double(lr.getX() - w, lr.getY() );
711

    
712
                //Obtenemos la georreferenciaci?n de las cuatro esquinas del nuevo raster
713
                trans.transform(ul, ul);
714
                trans.transform(ur, ur);
715
                trans.transform(lr, lr);
716
                trans.transform(ll, ll);
717

    
718
                double pixelSizeX = (ur.getX() - ul.getX()) / width;
719
                double pixelSizeY = (ll.getY() - ul.getY()) / height;
720
                double rotX = trans.getShearX();
721
                double rotY = trans.getShearY();
722
                return new AffineTransform(pixelSizeX, rotY, rotX, pixelSizeY, ulx, uly);
723
        }
724

    
725
        /*
726
         * (non-Javadoc)
727
         * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#cancelDrawing()
728
         */
729
        public boolean cancelDrawing() {
730
                return false;
731
        }
732

    
733
        /*
734
         * (non-Javadoc)
735
         * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#getCursor()
736
         */
737
        public Cursor getCursor() {
738
                return null;
739
        }
740

    
741
        /*
742
         * (non-Javadoc)
743
         * @see org.gvsig.gui.beans.coordinatespanel.CoordinatesListener#actionValueChanged(org.gvsig.gui.beans.coordinatespanel.CoordinatesEvent)
744
         */
745
        public void actionValueChanged(CoordinatesEvent e) {
746
                if (e.getSource() == getCoordinatesPanel().getPixelCoordinates()) {
747
                        eventJTextField(e);
748
                        if (e.getName().equals("11"))
749
                                recalcCoordFields(true, true, true);
750
                        if (e.getName().equals("12"))
751
                                recalcCoordFields(true, true, false);
752
                        if (e.getName().equals("21"))
753
                                recalcCoordFields(true, false, true);
754
                        if (e.getName().equals("22"))
755
                                recalcCoordFields(true, false, false);
756
                }
757
                if (e.getSource() == getCoordinatesPanel().getRealCoordinates()) {
758
                        eventJTextField(e);
759
                        if (e.getName().equals("11"))
760
                                recalcCoordFields(false, true, true);
761
                        if (e.getName().equals("12"))
762
                                recalcCoordFields(false, true, false);
763
                        if (e.getName().equals("21"))
764
                                recalcCoordFields(false, false, true);
765
                        if (e.getName().equals("22"))
766
                                recalcCoordFields(false, false, false);
767
                }
768
        }
769

    
770
        /*
771
         * (non-Javadoc)
772
         * @see org.gvsig.gui.beans.datainput.DataInputContainerListener#actionValueChanged(java.util.EventObject)
773
         */
774
        public void actionValueChanged(EventObject e) {
775
                if(!enableValueChangedEvent)
776
                        return;
777

    
778
                enableValueChangedEvent = false; //Desactivamos el evento de cambio de valor de las cajas de texto para que no se bucle
779

    
780
                if (e.getSource() == getResolutionPanel().getCCellSize().getDataInputField()) {
781
                        // Cambiamos PS ==> wPx=wWC/PS & hPx=wPx/rel
782
                        double ps = 0;
783
                        try {
784
                                ps = Double.parseDouble(getResolutionPanel().getCCellSize().getValue());
785
                        } catch (NumberFormatException ex) {
786
                                return;
787
                        }
788
                        data.setPxWidth(data.getWcWidth() / ps);
789
                        data.setPxHeight(data.getWcHeight() / ps);
790
                        data.updateObservers();
791
                } else if (e.getSource() == getResolutionPanel().getCWidth().getDataInputField()) {
792
                        // Cambiamos wPx ==> hPx=wPx/rel & PS=wWC/wPx
793
                        double wPx = 0;
794
                        try {
795
                                wPx = Double.parseDouble(getResolutionPanel().getCWidth().getValue());
796
                        } catch (NumberFormatException ex) {
797
                                return;
798
                        }
799
                        data.setPxWidth(wPx);
800
                        data.setPxHeight(Math.round(wPx / data.getRatio()));
801
                        data.updateObservers();
802
                } else if (e.getSource() == getResolutionPanel().getCHeight().getDataInputField()) {
803
                        // Cambiamos hPx ==> wPx=rel*wPx & PS=hWC/hPx
804
                        double hPx = 0;
805
                        try {
806
                                hPx = Double.parseDouble(getResolutionPanel().getCHeight().getValue());
807
                        } catch (NumberFormatException ex) {
808
                                return;
809
                        }
810
                        data.setPxHeight(hPx);
811
                        data.setPxWidth(Math.round(Math.round(hPx * data.getRatio())));
812
                        data.updateObservers();
813
                }
814
                enableValueChangedEvent = true;
815
        }
816

    
817
        /**
818
         * Asigna el valor para la activaci?n y desactivaci?n del evento de cambio de valor en
819
         * las cajas de texto.
820
         * @param enableValueChangedEvent
821
         */
822
        public void setEnableValueChangedEvent(boolean enableValueChangedEvent) {
823
                this.enableValueChangedEvent = enableValueChangedEvent;
824
        }
825

    
826
        /*
827
         * (non-Javadoc)
828
         * @see org.gvsig.raster.IProcessActions#end(java.lang.Object)
829
         */
830
        public void end(Object params) {
831
                if(        params instanceof Object[] &&
832
                        ((Object[])params).length == 2 &&
833
                        ((Object[])params)[0] instanceof String &&
834
                        ((Object[])params)[1] instanceof Long) {
835

    
836
                        String fName = (String)((Object[])params)[0];
837
                        long milis = ((Long)((Object[])params)[1]).longValue();
838

    
839
                        EndInfoDialog.show(fName, milis);
840
                }
841
        }
842
        
843
        /**
844
         * Obtener la capa de un raster.
845
         * @return
846
         */
847
        public FLyrRasterSE getFLayer() {
848
                return fLayer;
849
        }
850
        
851
        /**
852
         * Obtiene la ultima herramienta seleccionada antes de cargar el recorte
853
         * @return
854
         */
855
        public String getLastTool() {
856
                return lastTool;
857
        }
858

    
859
        /**
860
         * Obtiene el nombre de la vista
861
         * @return
862
         */
863
        public String getViewName() {
864
                return viewName;
865
        }        
866

    
867
        /**
868
         * Establecer la capa para usarla en el recorte
869
         * @param fLayer
870
         */
871
        public void setLayer(FLyrRasterSE fLayer) {
872
                this.fLayer = fLayer;
873
                BaseView view = (BaseView) PluginServices.getMDIManager().getActiveWindow();
874
                viewName = PluginServices.getMDIManager().getWindowInfo(view).getTitle();
875
                mapControl = view.getMapControl();
876

    
877
                lastTool = mapControl.getCurrentTool();
878

    
879
                // Listener de eventos de movimiento que pone las coordenadas del rat?n en
880
                // la barra de estado
881
                StatusBarListener sbl = new StatusBarListener(mapControl);
882

    
883
                // Cortar Raster
884
                ClippingMouseViewListener clippingMouseViewListener = new ClippingMouseViewListener(mapControl, getClippingPanel(), data, fLayer);
885
                mapControl.addMapTool("cutRaster", new Behavior[] {
886
                                new RectangleBehavior(clippingMouseViewListener), new MouseMovementBehavior(sbl)
887
                        }
888
                );
889
                
890
                getSelectionPanel().setLayer(fLayer);
891

    
892
                // Obtener la extension completa de la capa
893

    
894
                if(fLayer instanceof IRasterGeoOperations && fLayer instanceof IRasterOperations) {
895
                        setAffineTransform(((IRasterGeoOperations)fLayer).getAffineTransform());
896
                        setDimension(new Dimension((int)((IRasterOperations)fLayer).getPxWidth(), (int)((IRasterOperations)fLayer).getPxHeight()));
897
                } else {
898
                        RasterToolsUtil.messageBoxError("Error obteniendo el extent.", this);
899
                        return;
900
                }
901

    
902
        }
903

    
904
        /**
905
         * Acciones que se realizan para seleccionar la tool CutRaster
906
         */
907
        public void selectToolButton() {
908
                // seleccionamos la vista de gvSIG
909
                com.iver.cit.gvsig.project.documents.view.gui.View theView = null;
910
                try {
911
                        IWindow[] allViews = PluginServices.getMDIManager().getAllWindows();
912
                        for (int i = 0; i < allViews.length; i++) {
913
                                if (allViews[i] instanceof com.iver.cit.gvsig.project.documents.view.gui.View
914
                                                && PluginServices.getMDIManager().getWindowInfo((View) allViews[i])
915
                                                                .getTitle().equals(viewName))
916
                                        theView = (com.iver.cit.gvsig.project.documents.view.gui.View) allViews[i];
917
                        }
918
                        if (theView == null)
919
                                return;
920
                } catch (ClassCastException ex) {
921
                        // RasterToolsUtil.messageBoxError("cant_get_view "), this, ex);
922
                        return;
923
                }
924
                MapControl m_MapControl = theView.getMapControl();
925

    
926
                // Listener de eventos de movimiento que pone las coordenadas del rat?n en
927
                // la barra de estado
928
                //StatusBarListener sbl = new StatusBarListener(m_MapControl);
929

    
930
                // Cortar Raster
931
                /*ClippingMouseViewListener clippingMouseViewListener = new ClippingMouseViewListener(m_MapControl, getClippingPanel(), data, getFLayer());
932
                m_MapControl.addMapTool("cutRaster", new Behavior[] {
933
                                new RectangleBehavior(clippingMouseViewListener), new MouseMovementBehavior(sbl)
934
                                }
935
                );*/
936

    
937
                m_MapControl.setTool("clipRaster");
938
        }
939

    
940
        /**
941
         * Obtiene el <code>MapControl</code> de gvSIG
942
         * @return <code>MapControl</code>
943
         */
944
        public MapControl getMapControl() {
945
                return mapControl;
946
        }
947

    
948

    
949
        public void rectangle(RectangleEvent event) throws BehaviorException {}
950
        public void interrupted() {}
951
}