Statistics
| Revision:

root / trunk / extensions / extRasterTools-SE / src / org / gvsig / rastertools / cutting / ui / listener / CuttingPanelListener.java @ 14092

History | View | Annotate | Download (28.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.cutting.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.EventObject;
32

    
33
import javax.swing.JOptionPane;
34

    
35
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
36
import org.gvsig.gui.beans.buttonspanel.ButtonsPanel;
37
import org.gvsig.gui.beans.buttonspanel.ButtonsPanelEvent;
38
import org.gvsig.gui.beans.buttonspanel.ButtonsPanelListener;
39
import org.gvsig.gui.beans.coordinatespanel.CoordinatesEvent;
40
import org.gvsig.gui.beans.coordinatespanel.CoordinatesListener;
41
import org.gvsig.gui.beans.coordinatespanel.CoordinatesPanel;
42
import org.gvsig.gui.beans.datainput.DataInputContainerListener;
43
import org.gvsig.gui.beans.incrementabletask.IncrementableTask;
44
import org.gvsig.gui.beans.table.models.CheckBoxModel;
45
import org.gvsig.raster.datastruct.Extent;
46
import org.gvsig.raster.util.RasterUtilities;
47
import org.gvsig.rastertools.IProcessActions;
48
import org.gvsig.rastertools.cutting.CuttingProcess;
49
import org.gvsig.rastertools.cutting.WriterBufferServer;
50
import org.gvsig.rastertools.cutting.panels.CuttingCoordinatesPanel;
51
import org.gvsig.rastertools.cutting.panels.CuttingOptionsPanel;
52
import org.gvsig.rastertools.cutting.panels.CuttingResolutionPanel;
53
import org.gvsig.rastertools.cutting.panels.CuttingSelectionPanel;
54
import org.gvsig.rastertools.cutting.ui.CuttingPanel;
55

    
56
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
57
import com.iver.andami.PluginServices;
58
import com.iver.andami.Utilities;
59
import com.iver.andami.messages.NotificationManager;
60
import com.iver.cit.gvsig.addlayer.fileopen.FileOpenWizard;
61
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
62
import com.iver.cit.gvsig.fmap.tools.BehaviorException;
63
import com.iver.cit.gvsig.fmap.tools.Events.RectangleEvent;
64
import com.iver.cit.gvsig.fmap.tools.Listeners.RectangleListener;
65
/**
66
 * <code>CuttingPanelListener</code> es una clase donde se recoger?n y
67
 * tratar?n todos los eventos del panel de recorte
68
 *
69
 * @version 19/04/2007
70
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
71
 */
72
public class CuttingPanelListener implements ActionListener, RectangleListener, ButtonsPanelListener, CoordinatesListener, DataInputContainerListener, IProcessActions {
73
  private Dimension       dim          = new Dimension();
74
  private AffineTransform at           = null;
75
  private CuttingPanel    cuttingPanel = null;
76
  private int             widthPx      = 0;
77
  private int             heightPx     = 0;
78

    
79
  /**
80
         * Crea un nuevo <code>CuttingPanelListener</code> con el
81
         * <code>CuttingPanel</code> asociado
82
         * @param panel
83
         */
84
        public CuttingPanelListener(CuttingPanel cuttingPanel) {
85
                this.cuttingPanel = cuttingPanel;
86
        }
87

    
88
  /**
89
         * Asigna la matriz de transformaci?n entre puntos en coordenadas del raster y
90
         * puntos en coordenadas reales.
91
         * @param AffineTransform
92
         */
93
  public void setAffineTransform(AffineTransform at) {
94
    this.at = at;
95
  }
96

    
97
  /**
98
   * Asigna la dimensi?n del raster
99
   * @param dim
100
   */
101
  public void setDimension(Dimension dim) {
102
    this.dim = dim;
103
  }
104

    
105
  /**
106
   * M?todo que se invoca cuando se disparan los eventos de los botones de
107
   * extensi?n completa o de seleccion de extensi?n con el rat?n
108
   */
109
  public void actionPerformed(ActionEvent e) {
110
    // Bot?n de selecci?n del extent completo
111
    // Modificamos las coordenadas reales y recalculamos las coordenadas pixel
112
    if (e.getSource() == getResolutionPanel().getButtonRestore()) {
113
      getCuttingPanel().restoreStatusText();
114
    }
115

    
116
    // Bot?n de selecci?n del extent completo
117
    // Modificamos las coordenadas reales y recalculamos las coordenadas pixel
118
    if (e.getSource() == getCoordinatesPanel().getButtonBarContainer().getButton(0)) {
119
      Point2D ulPx = new Point2D.Double(0, 0);
120
      Point2D lrPx = new Point2D.Double(dim.width, dim.height);
121

    
122
      double minX = Math.min(ulPx.getX(), lrPx.getX());
123
      double maxX = Math.max(ulPx.getX(), lrPx.getX());
124
      double minY = Math.min(ulPx.getY(), lrPx.getY());
125
      double maxY = Math.max(ulPx.getY(), lrPx.getY());
126

    
127
      //Convertimos nuevamente a coordenadas reales
128
      Point2D ulWc = new Point2D.Double();
129
      Point2D lrWc = new Point2D.Double();
130
      at.transform(new Point2D.Double(minX, minY), ulWc);
131
      at.transform(new Point2D.Double(maxX, maxY), lrWc);
132

    
133
      getCuttingPanel().setCoorRealFromDouble(ulWc.getX(), ulWc.getY(), lrWc.getX(), lrWc.getY(), 3);
134
      getCuttingPanel().setCoorPixelFromDouble(0, 0, dim.width - 1, dim.height - 1, 3);
135
      getCuttingPanel().setWidthText(Math.abs(maxX - minX), 0);
136
      getCuttingPanel().setHeightText(Math.abs(maxY - minY), 0);
137
      getCuttingPanel().setCellSizeText(((lrWc.getX() - ulWc.getX()) / dim.width), 4);
138
      getCuttingPanel().setRelWidthHeight((double) (dim.getWidth() / dim.getHeight()));
139
      getCuttingPanel().saveStatusText();
140

    
141
      return;
142
    }
143

    
144
    // Bot?n de selecci?n de la herramienta de seleccionar desde la vista
145
    if (e.getSource() == getCoordinatesPanel().getButtonBarContainer().getButton(1)) {
146
      getCuttingPanel().selectToolButton();
147
      return;
148
    }
149
  }
150

    
151
  /**
152
   * Al producirse un evento de perdida de foco o pulsaci?n de "enter" en un campo de texto de coordenadas
153
   * hay que asignar el nuevo valor introducido.
154
   * @param obj
155
   */
156
  private void eventJTextField(CoordinatesEvent e) {
157
    try {
158
            if (e.getSource() == getCoordinatesPanel().getCoordinatesPixel()) {
159
                                if (e.getName().equals("11"))
160
                                        getCuttingPanel().setCoorPixelFromDouble(
161
                                                        Double.valueOf(getCoordinatesPanel().getCoordinatesPixel().getValue11()).doubleValue(),
162
                                                        getCuttingPanel().getPxMinY(),
163
                                                        getCuttingPanel().getPxMaxX(),
164
                                                        getCuttingPanel().getPxMaxY(),
165
                                                        3);
166
                                if (e.getName().equals("12"))
167
                                        getCuttingPanel().setCoorPixelFromDouble(
168
                                                        getCuttingPanel().getPxMinX(),
169
                                                        Double.valueOf(getCoordinatesPanel().getCoordinatesPixel().getValue12()).doubleValue(),
170
                                                        getCuttingPanel().getPxMaxX(),
171
                                                        getCuttingPanel().getPxMaxY(),
172
                                                        3);
173
                                if (e.getName().equals("21"))
174
                                        getCuttingPanel().setCoorPixelFromDouble(
175
                                                        getCuttingPanel().getPxMinX(),
176
                                                        getCuttingPanel().getPxMinY(),
177
                                                        Double.valueOf(getCoordinatesPanel().getCoordinatesPixel().getValue21()).doubleValue(),
178
                                                        getCuttingPanel().getPxMaxY(),
179
                                                        3);
180
                                if (e.getName().equals("22"))
181
                                        getCuttingPanel().setCoorPixelFromDouble(
182
                                                        getCuttingPanel().getPxMinX(),
183
                                                        getCuttingPanel().getPxMinY(),
184
                                                        getCuttingPanel().getPxMaxX(),
185
                                                        Double.valueOf(getCoordinatesPanel().getCoordinatesPixel().getValue22()).doubleValue(),
186
                                                        3);
187
                        }
188

    
189
            if (e.getSource() == getCoordinatesPanel().getCoordinatesReales()) {
190
        Extent ex = getMapWindow();
191
        if (ex == null)
192
                return;
193

    
194
                                if (e.getName().equals("11"))
195
                                        getCuttingPanel().setCoorRealFromDouble(
196
                                                        Double.valueOf(getCoordinatesPanel().getCoordinatesReales().getValue11()).doubleValue(),
197
                                                        ex.getULY(),
198
                                                        ex.getLRX(),
199
                                                        ex.getLRY(),
200
                                                        6);
201
                                if (e.getName().equals("12"))
202
                                        getCuttingPanel().setCoorRealFromDouble(
203
                                                        ex.getULX(),
204
                                                        Double.valueOf(getCoordinatesPanel().getCoordinatesReales().getValue12()).doubleValue(),
205
                                                        ex.getLRX(),
206
                                                        ex.getLRY(),
207
                                                        6);
208
                                if (e.getName().equals("21"))
209
                                        getCuttingPanel().setCoorRealFromDouble(
210
                                                        ex.getULX(),
211
                                                        ex.getULY(),
212
                                                        Double.valueOf(getCoordinatesPanel().getCoordinatesReales().getValue21()).doubleValue(),
213
                                                        ex.getLRY(),
214
                                                        6);
215
                                if (e.getName().equals("22"))
216
                                        getCuttingPanel().setCoorRealFromDouble(
217
                                                        ex.getULX(),
218
                                                        ex.getULY(),
219
                                                        ex.getLRX(),
220
                                                        Double.valueOf(getCoordinatesPanel().getCoordinatesReales().getValue22()).doubleValue(),
221
                                                        6);
222
            }
223
                } catch (NumberFormatException ex1) {
224
                        // No hay valores parseables a decimal en las cajas de texto. No hacemos nada
225
                }
226
  }
227

    
228
  /**
229
   * Comprueba si todos los campos de coordenadas est?n llenos
230
   * @return true si todos los campos de coordenadas est?n llenos y false si hay
231
   *         alguno vacio.
232
   * @deprecated Ya no es necesario con el nuevo componente
233
   */
234
  private boolean isFieldsFill() {
235
    if (getCoordinatesPanel().getCoordinatesPixel().getValue11().equals("") ||
236
                    getCoordinatesPanel().getCoordinatesPixel().getValue12().equals("") ||
237
        getCoordinatesPanel().getCoordinatesPixel().getValue21().equals("") ||
238
        getCoordinatesPanel().getCoordinatesPixel().getValue22().equals("") ||
239
        getCoordinatesPanel().getCoordinatesReales().getValue11().equals("") ||
240
        getCoordinatesPanel().getCoordinatesReales().getValue12().equals("") ||
241
        getCoordinatesPanel().getCoordinatesReales().getValue21().equals("") ||
242
        getCoordinatesPanel().getCoordinatesReales().getValue22().equals(""))
243
      return false;
244
    return true;
245
  }
246

    
247
  /**
248
   * Obtiene un rectangulo con la ventana en pixeles. Estos datos son leidos desde el interfaz.
249
   * @return Rectangle2D
250
   */
251
  private Rectangle2D getPxWindow(){
252
    if (getCuttingPanel().getPxMinX() == 0
253
        && getCuttingPanel().getPxMinY() == 0
254
        && getCuttingPanel().getPxMaxX() == 0
255
        && getCuttingPanel().getPxMaxY() == 0)
256
      return null;
257
    return new Rectangle2D.Double(getCuttingPanel().getPxMinX(),
258
      getCuttingPanel().getPxMinY(),
259
      Math.abs(getCuttingPanel().getPxMaxX() - getCuttingPanel().getPxMinX()),
260
      Math.abs(getCuttingPanel().getPxMaxY() - getCuttingPanel().getPxMinY()));
261
  }
262

    
263
  /**
264
   * Obtiene un rectangulo con la ventana en coordenadas reales. Estos datos son leidos desde el interfaz.
265
   * @return Rectangle2D
266
   */
267
  private Extent getMapWindow(){
268
    if (getCuttingPanel().getULX() == 0
269
      && getCuttingPanel().getULY() == 0
270
      && getCuttingPanel().getLRX() == 0
271
      && getCuttingPanel().getLRY() == 0)
272
      return null;
273
    return new Extent(        getCuttingPanel().getULX(),
274
              getCuttingPanel().getULY(),
275
              getCuttingPanel().getLRX(),
276
              getCuttingPanel().getLRY());
277
  }
278

    
279
  /**
280
   * Recalcula el valor de los campos de coordenadas reales y pixel. Cuando modificamos alg?n campo
281
   * de las coordenadas reales se modifican los pixeles y viceversa.
282
   * @param modifyPx true si se ha modificado alg?n campo de coordenadas pixel y false si se ha modificado
283
   * alg?n campo de las coordenadas reales.
284
   */
285
  private void recalcCoordFields(boolean modifyPx) {
286
    if (isFieldsFill()) {
287
      try {
288
        if (modifyPx) {
289
          Rectangle2D pxWindow = getPxWindow();
290
          if (pxWindow == null)
291
            return;
292
          Point2D ulPx = new Point2D.Double(pxWindow.getMinX(), pxWindow.getMinY());
293
          Point2D lrPx = new Point2D.Double(pxWindow.getMaxX(), pxWindow.getMaxY());
294

    
295
          //Comprobamos si la selecci?n est? fuera del ?rea
296
          if(isOutside(ulPx, lrPx)) {
297
                  getCuttingPanel().setCoorPixelFromDouble(0, 0, 0, 0, 0);
298
                  getCuttingPanel().setWidthText(0, 0);
299
                  getCuttingPanel().setHeightText(0, 0);
300
                  getCuttingPanel().setCellSizeText(0, 0);
301
                  getCuttingPanel().setRelWidthHeight(0);
302
                  getCuttingPanel().setCoorRealFromDouble(0, 0, 0, 0, 0);
303
            return;
304
          }
305

    
306
          //Comprobamos que las esquinas no esten cambiadas de sitio
307
          if(ulPx.getX() > lrPx.getX()) {
308
            double ulTmp = ulPx.getX();
309
            ulPx.setLocation(lrPx.getX(), ulPx.getY());
310
            lrPx.setLocation(ulTmp, lrPx.getY());
311
          }
312
          if(ulPx.getY() > lrPx.getY()) {
313
            double ulTmp = ulPx.getY();
314
            ulPx.setLocation(ulPx.getX(), lrPx.getY());
315
            lrPx.setLocation(lrPx.getX(), ulTmp);
316
          }
317

    
318
          Point2D[] pointList = new Point2D[]{ulPx, lrPx};
319
          Point2D dim = new Point2D.Double(this.dim.width, this.dim.height);
320

    
321
          //Ajustamos los puntos al ?rea en pixeles del raster
322
          RasterUtilities.adjustToPixelSize(pointList, dim);
323

    
324
          Point2D ulWc = new Point2D.Double();
325
          Point2D lrWc = new Point2D.Double();
326
          at.transform(ulPx, ulWc);
327
          at.transform(new Point2D.Double(lrPx.getX(), lrPx.getY()), lrWc);
328

    
329
          getCuttingPanel().setCoorRealFromDouble(ulWc.getX(), ulWc.getY(), lrWc.getX(), lrWc.getY(), 3);
330
          getCuttingPanel().setCoorPixelFromDouble(ulPx.getX(), ulPx.getY(), lrPx.getX(), lrPx.getY(), 3);
331
          getCuttingPanel().setWidthText(Math.abs(ulPx.getX() - lrPx.getX()), 0);
332
          getCuttingPanel().setHeightText(Math.abs(ulPx.getY() - lrPx.getY()), 0);
333
          getCuttingPanel().setCellSizeText((Math.abs(lrWc.getX() - ulWc.getX()) / dim.getX()), 4);
334
          getCuttingPanel().setRelWidthHeight((double) (Math.abs(ulPx.getX() - lrPx.getX()) / Math.abs(ulPx.getY() - lrPx.getY())));
335
        } else {
336
          Extent mapWindow = getMapWindow();
337
          if (mapWindow == null)
338
            return;
339

    
340
          Point2D ulPx = new Point2D.Double(mapWindow.getULX(), mapWindow.getULY());
341
          Point2D lrPx = new Point2D.Double(mapWindow.getLRX(), mapWindow.getLRY());
342

    
343
          try {
344
            at.inverseTransform(ulPx, ulPx);
345
            at.inverseTransform(lrPx, lrPx);
346
          } catch (NoninvertibleTransformException e) {
347
            JOptionPane.showMessageDialog((Component) PluginServices.getMainFrame(), PluginServices.getText(this, "coordenadas_erroneas"));
348
            return;
349
          }
350

    
351
          Point2D[] pointList = new Point2D[]{ulPx, lrPx};
352
          Point2D dim = new Point2D.Double(this.dim.width, this.dim.height);
353

    
354
          //Comprobamos si la selecci?n est? fuera del ?rea
355
          if (isOutside(ulPx, lrPx)) {
356
                                                getCuttingPanel().setCoorPixelFromDouble(0, 0, 0, 0, 0);
357
                                                getCuttingPanel().setWidthText(0, 0);
358
                                                getCuttingPanel().setHeightText(0, 0);
359
                                                getCuttingPanel().setCellSizeText(0, 0);
360
                                                getCuttingPanel().setRelWidthHeight(0);
361
                                                getCuttingPanel().setCoorRealFromDouble(0, 0, 0, 0, 0);
362
                                                return;
363
                                        }
364
          // Ajustamos los puntos al ?rea en pixeles del raster
365
          RasterUtilities.adjustToPixelSize(pointList, dim);
366

    
367
          double minX = Math.min(ulPx.getX(), lrPx.getX());
368
          double maxX = Math.max(ulPx.getX(), lrPx.getX());
369
          double minY = Math.min(ulPx.getY(), lrPx.getY());
370
          double maxY = Math.max(ulPx.getY(), lrPx.getY());
371

    
372
          //Convertimos nuevamente a coordenadas reales
373
          Point2D ulWc = new Point2D.Double();
374
          Point2D lrWc = new Point2D.Double();
375
          at.transform(new Point2D.Double(minX, minY), ulWc);
376
          at.transform(new Point2D.Double(maxX, maxY), lrWc);
377

    
378
                                        getCuttingPanel().setCoorRealFromDouble(ulWc.getX(), ulWc.getY(), lrWc.getX(), lrWc.getY(), 3);
379
                                        getCuttingPanel().setCoorPixelFromDouble(minX, minY, maxX, maxY, 3);
380
                                        getCuttingPanel().setWidthText(Math.abs(ulPx.getX() - lrPx.getX()), 0);
381
                                        getCuttingPanel().setHeightText(Math.abs(ulPx.getY() - lrPx.getY()), 0);
382
                                        getCuttingPanel().setCellSizeText(((maxX - minX) / dim.getX()), 4);
383
                                        getCuttingPanel().setRelWidthHeight((double) (Math.abs(ulPx.getX() - lrPx.getX()) / Math.abs(ulPx.getY() - lrPx.getY())));
384
        }
385
      } catch (NumberFormatException ex) {
386
        return;
387
      }
388
    }
389
  }
390

    
391
  /**
392
   * Comprueba si la selecci?n del punto est? fuera del ?rea del raster.
393
   * @param ulPx Coordenada superior izquierda en pixeles
394
   * @param lrPx Corrdenada inferior derecha en pixeles
395
   * @return true si la selecci?n del punto est? fuera del raster y false si no lo est?
396
   */
397
  private boolean isOutside(Point2D ulPx, Point2D lrPx) {
398
    double minX = Math.min(ulPx.getX(), lrPx.getX());
399
    double minY = Math.min(ulPx.getY(), lrPx.getY());
400
    double maxX = Math.max(ulPx.getX(), lrPx.getX());
401
    double maxY = Math.max(ulPx.getY(), lrPx.getY());
402
    if (minX >= dim.width || minY >= dim.height || maxX < 0 || maxY < 0)
403
      return true;
404
    return false;
405
  }
406

    
407
  /**
408
   * Definir el ancho de la vista en pixeles
409
   * @param value
410
   */
411
  public void setWidthPx(int value) {
412
    widthPx = value;
413
  }
414

    
415
  /**
416
   * Obtener el ancho de la vista en pixeles
417
   * @return the widthPx
418
   */
419
  public int getWidthPx() {
420
    return widthPx;
421
  }
422

    
423
  /**
424
   * Definir el alto de la vista en pixeles
425
   * @param value
426
   */
427
  public void setHeightPx(int value) {
428
    heightPx = value;
429
  }
430

    
431
  /**
432
   * Obtener el alto de la vista en pixeles
433
   * @return the heightPx
434
   */
435
  public int getHeightPx() {
436
    return heightPx;
437
  }
438

    
439
  /**
440
   * Invocaci?n de los eventos de la ventana de <code>DefaultButtonsPanel</code>
441
   */
442
  public void actionButtonPressed(ButtonsPanelEvent e) {
443
    // Bot?n de Aceptar
444
    if (e.getButton() == ButtonsPanel.BUTTON_ACCEPT) {
445
      accept();
446
      close();
447
    }
448

    
449
    // Bot?n de Aplicar
450
    if (e.getButton() == ButtonsPanel.BUTTON_APPLY) {
451
      accept();
452
      getCuttingPanel().getOptionsPanel().setNewLayerText();
453
    }
454

    
455
    // Bot?n de Cerrar
456
    if (e.getButton() == ButtonsPanel.BUTTON_CANCEL) {
457
      close();
458
    }
459

    
460
    getCuttingPanel().getFLayer().getMapContext().invalidate();
461
  }
462

    
463
  /**
464
   * Cerrar la ventana del recorte
465
   */
466
  private void close() {
467
    try {
468
      if (getCuttingPanel().getLastTool() != null)
469
        getCuttingPanel().getMapControl().setTool(getCuttingPanel().getLastTool());
470
      PluginServices.getMDIManager().closeWindow(getCuttingPanel().getCuttingDialog());
471
    } catch (ArrayIndexOutOfBoundsException ex) {
472
      // Si la ventana no se puede eliminar no hacemos nada
473
    }
474
  }
475

    
476
  /**
477
   * Obtener el <code>CuttingPanel</code> asociado
478
   * @return CuttingPanel
479
   */
480
  private CuttingPanel getCuttingPanel() {
481
    return cuttingPanel;
482
  }
483
  
484
  private CuttingCoordinatesPanel getCoordinatesPanel() {
485
          return getCuttingPanel().getCoordinatesPanel();
486
  }
487

    
488
  private CuttingResolutionPanel getResolutionPanel() {
489
          return getCuttingPanel().getResolutionPanel();
490
  }
491

    
492
  private CuttingOptionsPanel getOptionsPanel() {
493
          return getCuttingPanel().getOptionsPanel();
494
  }
495

    
496
  private CuttingSelectionPanel getSelectionPanel() {
497
          return getCuttingPanel().getSelectionPanel();
498
  }
499

    
500
  /**
501
   * Acciones realizadas cuando se acepta en el dialogo. Se obtendr?n los datos
502
   * de recorte desde el dialogo, crearemos el objeto CuttingProcess que
503
   * gestiona el recortado, ajustamos el tama?o del grid de salida y procesamos.
504
   */
505
  private void accept() {
506
    // Controlamos las coordenadas del recorte que no se salgan de la imagen.
507
    // De ser as? mostramos un error
508
    CoordinatesPanel coordinatesReales = getCoordinatesPanel().getCoordinatesReales();
509
    double ulx = 0;
510
    double lrx = 0;
511
    double lry = 0;
512
    double uly = 0;
513
    try {
514
      ulx = Double.parseDouble(coordinatesReales.getValue11());
515
      lry = Double.parseDouble(coordinatesReales.getValue22());
516
      lrx = Double.parseDouble(coordinatesReales.getValue21());
517
      uly = Double.parseDouble(coordinatesReales.getValue12());
518
      Rectangle2D ext = getCuttingPanel().getFLayer().getFullExtent();
519
      if (ulx > ext.getMaxX() || lrx < ext.getMinX()
520
        || uly > ext.getMaxY() || lry < ext.getMinY()) {
521
        JOptionPane.showMessageDialog(
522
            (Component) PluginServices.getMainFrame(), PluginServices.getText(
523
                this, "coordenadas_erroneas"));
524
        return;
525
      }
526
    } catch (NumberFormatException e) {
527
      JOptionPane.showMessageDialog((Component) PluginServices.getMainFrame(),
528
          PluginServices.getText(this, "coordenadas_erroneas"));
529
      return;
530
    } catch (ExpansionFileReadException e) {
531
      NotificationManager.addError("Error dibujando", e);
532
    } catch (ReadDriverException e) {
533
      NotificationManager.addError("Error dibujando", e);
534
    }
535

    
536
    // Obtenemos las coordenadas del recorte
537
    CoordinatesPanel coordinatesPixel = getCoordinatesPanel().getCoordinatesPixel();
538
    int[] dValues = new int[4];
539
    try {
540
      dValues[0] = (int) Math.round(Double.valueOf(coordinatesPixel.getValue11()).doubleValue());
541
      dValues[1] = (int) Math.round(Double.valueOf(coordinatesPixel.getValue22()).doubleValue());
542
      dValues[2] = (int) Math.round(Double.valueOf(coordinatesPixel.getValue21()).doubleValue());
543
      dValues[3] = (int) Math.round(Double.valueOf(coordinatesPixel.getValue12()).doubleValue());
544
    } catch (NumberFormatException exc) {
545
      // Los valores de las cajas son incorrectos. Terminamos la funci?n
546
      return;
547
    }
548

    
549
    // Seleccionamos las bandas que se usaran en el recorte a partir de la tabla
550
    int countBands = 0;
551
    int rowCount = ((CheckBoxModel) getSelectionPanel().getTableContainer().getModel()).getRowCount();
552
    for (int iRow = 0; iRow < rowCount; iRow++)
553
      if ((((Boolean) ((CheckBoxModel) getSelectionPanel().getTableContainer().getModel()).getValueAt(iRow, 0))).booleanValue())
554
        countBands++;
555

    
556
    int[] drawableBands = new int[countBands];
557
    int i = 0;
558
    for (int iRow = 0; iRow < rowCount; iRow++) {
559
      if ((((Boolean) ((CheckBoxModel) getSelectionPanel().getTableContainer().getModel()).getValueAt(iRow, 0))).booleanValue())
560
        drawableBands[i++] = iRow;
561
    }
562

    
563
    /**
564
     * Donde se va a guardar el fichero
565
     */
566
    String path = FileOpenWizard.getLastPath();
567
    if (getOptionsPanel().getCbSaveFile().isSelected()) {
568
      path = FileOpenWizard.getLastPath();
569
    } else {
570
      path = Utilities.createTempDirectory();
571
    }
572

    
573
    String file = getOptionsPanel().getFilenameTextField().getText();
574
    if (file == "") file = "cutlayer";
575

    
576
    String filename = path + File.separator + file;
577

    
578
    /**
579
     * Preparacion para la generacion del proceso del recorte
580
     */
581
    if(((FLyrRasterSE) getCuttingPanel().getFLayer()) == null)
582
      return;
583

    
584
    WriterBufferServer dataWriter1 = new WriterBufferServer();
585

    
586
    AffineTransform transf = calcAffineTransform(ulx, uly, lrx, lry, getCuttingPanel().getWidthText(), getCuttingPanel().getHeightText());
587

    
588
    int interpMethod = getResolutionPanel().getSelectedInterpolationMethod();
589

    
590
    CuttingProcess cuttingProcess = new CuttingProcess(getCuttingPanel().getViewName(),
591
                    dValues, filename, dataWriter1, (FLyrRasterSE) getCuttingPanel().getFLayer());
592
    
593
    cuttingProcess.setLoadedInToc(getOptionsPanel().getCbLoadLayerInToc().isSelected());
594
    cuttingProcess.setDrawableBands(drawableBands);
595
    cuttingProcess.setOneLayerPerBand(getOptionsPanel().getCbOneLyrPerBand().isSelected());
596
    cuttingProcess.setInterpolationMethod(interpMethod);
597
    cuttingProcess.setAffineTransform(transf);
598

    
599
    cuttingProcess.setResolution((int) getCuttingPanel().getWidthText(),
600
                   (int) getCuttingPanel().getHeightText());
601
                cuttingProcess.setActions(this);
602
    IncrementableTask incrementableTask = new IncrementableTask(dataWriter1);
603
    cuttingProcess.setIncrementableTask(incrementableTask);
604
    incrementableTask.showWindow();
605
    cuttingProcess.start();
606
    incrementableTask.start();
607
  }
608

    
609
  /**
610
   * Calcula la matriz de transformaci?n que se usar? para el nuevo raster generado.
611
   * @param ulx Coordenada X real de la esquina superior izquierda
612
   * @param uly Coordenada Y real de la esquina superior izquierda
613
   * @param lrx Coordenada X real de la esquina inferior derecha
614
   * @param lry Coordenada Y real de la esquina inferior derecha
615
   * @param width Ancho en p?xeles del nuevo raster
616
   * @param height Alto en p?xeles del nuevo raster
617
   * @return Matriz de transformaci?n para el nuevo raster
618
   */
619
  private AffineTransform calcAffineTransform(double ulx, double uly, double lrx, double lry, double width, double height) {
620
    Point2D ul = new Point2D.Double(ulx, uly);
621
    Point2D lr = new Point2D.Double(lrx, lry);
622
    try {
623
      at.inverseTransform(ul, ul);
624
      at.inverseTransform(lr, lr);
625
    } catch (NoninvertibleTransformException e) {
626
      JOptionPane.showMessageDialog((Component) PluginServices.getMainFrame(), PluginServices.getText(this, "coordenadas_erroneas"));
627
      return new AffineTransform();
628
    }
629
    double w = Math.abs(lr.getX() - ul.getX());
630

    
631
    Point2D ur = new Point2D.Double(ul.getX() + w, ul.getY());
632
    Point2D ll = new Point2D.Double(lr.getX() - w, lr.getY() );
633
    
634
    //Obtenemos la georreferenciaci?n de las cuatro esquinas del nuevo raster
635
    at.transform(ul, ul);
636
    at.transform(ur, ur);
637
    at.transform(lr, lr);
638
    at.transform(ll, ll);
639

    
640
    double pixelSizeX = (ur.getX() - ul.getX()) / width;
641
    double pixelSizeY = (ll.getY() - ul.getY()) / height;
642
    double rotX = at.getShearX();
643
    double rotY = at.getShearY();
644
    return new AffineTransform(pixelSizeX, rotY, rotX, pixelSizeY, ulx, uly);
645
  }
646

    
647
  /*
648
   * (non-Javadoc)
649
   * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#cancelDrawing()
650
   */
651
  public boolean cancelDrawing() {
652
    return false;
653
  }
654

    
655
  /*
656
   * (non-Javadoc)
657
   * @see com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener#getCursor()
658
   */
659
  public Cursor getCursor() {
660
    return null;
661
  }
662

    
663
  /*
664
   * (non-Javadoc)
665
   * @see org.gvsig.gui.beans.coordinatespanel.CoordinatesListener#actionValueChanged(org.gvsig.gui.beans.coordinatespanel.CoordinatesEvent)
666
   */
667
        public void actionValueChanged(CoordinatesEvent e) {
668
                if (e.getSource() == getCoordinatesPanel().getCoordinatesPixel()) {
669
                        eventJTextField(e);
670
                        recalcCoordFields(true);
671
                }
672
                if (e.getSource() == getCoordinatesPanel().getCoordinatesReales()) {
673
                        eventJTextField(e);
674
                        recalcCoordFields(false);
675
                }
676
        }
677

    
678
        /*
679
         * (non-Javadoc)
680
         * @see org.gvsig.gui.beans.datainput.DataInputContainerListener#actionValueChanged(java.util.EventObject)
681
         */
682
        public void actionValueChanged(EventObject e) {
683
    if (e.getSource() == getResolutionPanel().getCCellSize()) {
684
      // Cambiamos PS ==> wPx=wWC/PS & hPx=wPx/rel
685
      double ps = 0;
686
      try {
687
        ps = Double.parseDouble(getResolutionPanel().getCCellSize().getValue());
688
      } catch (NumberFormatException ex) {
689
        return;
690
      }
691
      Extent mapWindow = getMapWindow();
692
      Rectangle2D pxWindow = getPxWindow();
693
      if (mapWindow == null || pxWindow == null)
694
        return;
695
      getCuttingPanel().setWidthText(mapWindow.width() / ps, 0);
696
      getCuttingPanel().setHeightText((mapWindow.width() / ps) / getCuttingPanel().getRelWidthHeight(), 0);
697
    }
698

    
699
    if (e.getSource() == getResolutionPanel().getCWidth()) {
700
      // Cambiamos wPx ==> hPx=wPx/rel & PS=wWC/wPx
701
      double wPx = 0;
702
      try {
703
        wPx = Double.parseDouble(getResolutionPanel().getCWidth().getValue());
704
      } catch (NumberFormatException ex) {
705
        return;
706
      }
707
      Extent mapWindow = getMapWindow();
708
      Rectangle2D pxWindow = getPxWindow();
709
      if (mapWindow == null || pxWindow == null)
710
        return;
711
      getCuttingPanel().setWidthText(wPx, 0);
712
      getCuttingPanel().setHeightText(wPx / getCuttingPanel().getRelWidthHeight(), 0);
713
      getCuttingPanel().setCellSizeText((mapWindow.width() / wPx), 4);
714
    }
715

    
716
    if (e.getSource() == getResolutionPanel().getCHeight()) {
717
      // Cambiamos hPx ==> wPx=rel*wPx & PS=hWC/hPx
718
      double hPx = 0;
719
      try {
720
        hPx = Double.parseDouble(getResolutionPanel().getCHeight().getValue());
721
      } catch (NumberFormatException ex) {
722
        return;
723
      }
724
      Extent mapWindow = getMapWindow();
725
      Rectangle2D pxWindow = getPxWindow();
726
      if (mapWindow == null || pxWindow == null)
727
        return;
728
      getCuttingPanel().setWidthText(hPx * getCuttingPanel().getRelWidthHeight(), 0);
729
      getCuttingPanel().setHeightText(hPx, 0);
730
      getCuttingPanel().setCellSizeText((mapWindow.height() / hPx), 4);
731
    }
732
  }
733
        
734
  public void rectangle(RectangleEvent event) throws BehaviorException {}
735

    
736
        /*
737
         * (non-Javadoc)
738
         * @see org.gvsig.rastertools.IProcessActions#end()
739
         */
740
        public void end(Object params) {
741
                if(getOptionsPanel() != null)
742
                        getOptionsPanel().setNewLayerText();
743
        }
744
        
745
        /*
746
         * (non-Javadoc)
747
         * @see org.gvsig.rastertools.IProcessActions#interrupted()
748
         */
749
        public void interrupted() {}
750
}