Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.mapcontext / org.gvsig.fmap.mapcontext.api / src / main / java / org / gvsig / fmap / mapcontext / ViewPort.java @ 44005

History | View | Annotate | Download (55.8 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.fmap.mapcontext;
25

    
26
import java.awt.Color;
27
import java.awt.Dimension;
28
import java.awt.Toolkit;
29
import java.awt.geom.AffineTransform;
30
import java.awt.geom.NoninvertibleTransformException;
31
import java.awt.geom.Point2D;
32
import java.awt.geom.Rectangle2D;
33
import java.util.ArrayList;
34
import java.util.Objects;
35

    
36
import org.cresques.cts.GeoCalc;
37
import org.cresques.cts.IProjection;
38
import org.gvsig.compat.CompatLocator;
39
import org.slf4j.Logger;
40
import org.slf4j.LoggerFactory;
41

    
42
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
43
import org.gvsig.fmap.geom.Geometry;
44
import org.gvsig.fmap.geom.GeometryLocator;
45
import org.gvsig.fmap.geom.GeometryManager;
46
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
47
import org.gvsig.fmap.geom.exception.CreateGeometryException;
48
import org.gvsig.fmap.geom.primitive.Envelope;
49
import org.gvsig.fmap.geom.primitive.Point;
50
import org.gvsig.fmap.mapcontext.events.ColorEvent;
51
import org.gvsig.fmap.mapcontext.events.ExtentEvent;
52
import org.gvsig.fmap.mapcontext.events.ProjectionEvent;
53
import org.gvsig.fmap.mapcontext.events.listeners.ViewPortListener;
54
import org.gvsig.timesupport.Time;
55
import org.gvsig.tools.ToolsLocator;
56
import org.gvsig.tools.dynobject.DynStruct;
57
import org.gvsig.tools.lang.Cloneable;
58
import org.gvsig.tools.persistence.PersistenceManager;
59
import org.gvsig.tools.persistence.Persistent;
60
import org.gvsig.tools.persistence.PersistentState;
61
import org.gvsig.tools.persistence.exception.PersistenceException;
62
import org.gvsig.tools.util.Callable;
63

    
64
/**
65
 * <p>
66
 * <code>ViewPort</code> class represents the logic needed to transform a
67
 * rectangular area of a map to the available area in screen to display it.
68
 * </p>
69
 * <p>
70
 * Includes an affine transformation, between the rectangular area selected of
71
 * the external map, in its own <i>map coordinates</i>, to the rectangular area
72
 * available of a view in <i>screen coordinates</i>.
73
 * </p>
74
 * <p>
75
 * Elements:
76
 * <ul>
77
 * <li><i>extent</i>: the area selected of the map, in <i>map coordinates</i>.
78
 * <li><i>imageSize</i>: width and height in pixels (<i>screen coordinates</i>)
79
 * of the area available in screen to display the area selected of the map.
80
 * <li><i>adjustedExtent</i>: the area selected must be an scale of
81
 * <i>imageSize</i>.<br>
82
 * This implies adapt the extent, preserving and centering it, and adding around
83
 * the needed area to fill all the image size. That added area will be extracted
84
 * from the original map, wherever exists, and filled with the background color
85
 * wherever not.
86
 * <li><i>scale</i>: the scale between the adjusted extent and the image size.
87
 * <li><i>backColor</i>: the default background color in the view, if there is
88
 * no map.
89
 * <li><i>trans</i>: the affine transformation.
90
 * <li><i>proj</i>: map projection used in this view.
91
 * <li><i>distanceUnits</i>: distance measurement units, of data in screen.
92
 * <li><i>mapUnits</i>: measurement units, of data in map.
93
 * <li><i>extents</i>: an {@link ExtentHistory ExtentHistory} with the last
94
 * previous extents.
95
 * <li><i>offset</i>: position in pixels of the available rectangular area,
96
 * where start drawing the map.
97
 * <li><i>dist1pixel</i>: the distance in <i>world coordinates</i> equivalent to
98
 * 1 pixel in the view with the current extent.
99
 * <li><i>dist3pixel</i>: the distance in <i>world coordinates</i> equivalent to
100
 * 3 pixels in the view with the current extent.
101
 * <li><i>listeners</i>: list with the {@link ViewPortListener ViewPortListener}
102
 * registered.
103
 * </ul>
104
 * </p>
105
 *
106
 * @author Vicente Caballero Navarro
107
 */
108
public class ViewPort implements Persistent, Cloneable {
109

    
110
  private static final String FIELD_DISTANCE_AREA = "distanceArea";
111

    
112
  private static final String FIELD_IMAGE_SIZE = "imageSize";
113

    
114
  private static final String FIELD_PROJ = "proj";
115

    
116
  private static final String FIELD_OFFSET = "offset";
117

    
118
  private static final String FIELD_MAP_UNITS = "mapUnits";
119

    
120
  private static final String FIELD_EXTENT = "extent";
121

    
122
  private static final String FIELD_EXTENTS = "extents";
123

    
124
  private static final String FIELD_DISTANCE_UNITS = "distanceUnits";
125

    
126
  private static final String FIELD_DIST3PIXEL = "dist3pixel";
127

    
128
  private static final String FIELD_DIST1PIXEL = "dist1pixel";
129

    
130
  private static final String FIELD_CLIP = "clip";
131

    
132
  private static final String FIELD_BACK_COLOR = "backColor";
133

    
134
  private static final String FIELD_ADJUSTED_EXTENT = "adjustedExtent";
135

    
136
  private static final GeometryManager geomManager = GeometryLocator
137
      .getGeometryManager();
138

    
139
  private static final Logger logger = LoggerFactory.getLogger(ViewPort.class);
140

    
141
  /**
142
   * <p>
143
   * Area selected by user using some tool.
144
   * </p>
145
   * <p>
146
   * When the zoom changes (for instance when using the zoom in or zoom out
147
   * tools, but also zooming to a selected feature or shape) the extent that
148
   * covers that area is the value returned by this method. It is not the actual
149
   * area shown in the view because it does not care about the aspect ratio of
150
   * the available area. However, any part of the real world contained in this
151
   * extent is shown in the view.
152
   * </p>
153
   * <p>
154
   * Probably this is not what you are looking for. If you are looking for the
155
   * complete extent currently shown, you must use
156
   * {@linkplain #getAdjustedExtent()} method which returns the extent that
157
   * contains this one but regarding the current view's aspect ratio.
158
   * </p>
159
   *
160
   * @see #getExtent()
161
   * @see #setEnvelope(Envelope)
162
   */
163
  protected Rectangle2D extent;
164

    
165
  protected Time time;
166

    
167
  /**
168
   * <p>
169
   * Location and dimensions of the extent adjusted to the image size.
170
   * </p>
171
   *
172
   * @see #getAdjustedExtent()
173
   */
174
  protected Rectangle2D adjustedExtent;
175

    
176
  /**
177
   * Draw version of the context. It's used for know when de componend has
178
   * changed any visualization property
179
   *
180
   * @see getDrawVersion
181
   * @see updateDrawVersion
182
   */
183
  private long drawVersion = 0L;
184

    
185
  /**
186
   * <p>
187
   * History with the last extents of the view.
188
   * </p>
189
   *
190
   * @see #setPreviousExtent()
191
   * @see #getExtents()
192
   */
193
  protected ExtentHistory extentsHistory = new ExtentHistory();
194

    
195
  /**
196
   * <p>
197
   * Size in <i>screen coordinates</i> of the rectangle where the image is
198
   * displayed.
199
   * </p>
200
   * <p>
201
   * Used by {@linkplain #calculateAffineTransform()} to calculate:<br>
202
   * <ul>
203
   * <li>The new {@link #scale scale} .
204
   * <li>The new {@link #adjustedExtent adjustableExtent} .
205
   * <li>The new {@link #trans trans} .
206
   * <li>The new real world coordinates equivalent to 1 pixel (
207
   * {@link #dist1pixel dist1pixel}) .
208
   * <li>The new real world coordinates equivalent to 3 pixels (
209
   * {@link #dist3pixel dist3pixel}) .
210
   * </ul>
211
   * </p>
212
   *
213
   * @see #getImageSize()
214
   * @see #getImageHeight()
215
   * @see #getImageWidth()
216
   * @see #setImageSize(Dimension)
217
   */
218
  private Dimension imageSize;
219

    
220
  /**
221
   * <p>
222
   * the affine transformation between the {@link #extent extent} in <i>map 2D
223
   * coordinates</i> to the image area in the screen, in <i>screen 2D
224
   * coordinates</i> (pixels).
225
   * </p>
226
   *
227
   * @see AffineTransform
228
   * @see #getAffineTransform()
229
   * @see #setAffineTransform(AffineTransform)
230
   * @see #calculateAffineTransform()
231
   */
232
  private AffineTransform trans = new AffineTransform();
233

    
234
  /**
235
   * <p>
236
   * Measurement unit used for measuring distances and displaying information.
237
   * </p>
238
   *
239
   * @see #getDistanceUnits()
240
   * @see #setDistanceUnits(int)
241
   */
242
  private int distanceUnits = 1;
243

    
244
  /**
245
   * <p>
246
   * Measurement unit used for measuring areas and displaying information.
247
   * </p>
248
   *
249
   * @see #getDistanceArea()
250
   * @see #setDistanceArea(int)
251
   */
252
  private int distanceArea = 1;
253

    
254
  /**
255
   * <p>
256
   * Measurement unit used by this view port for the map.
257
   * </p>
258
   *
259
   * @see #getMapUnits()
260
   * @see #setMapUnits(int)
261
   */
262
  private int mapUnits = 1;
263

    
264
  /**
265
   * <p>
266
   * Array with the {@link ViewPortListener ViewPortListener}s registered to
267
   * this view port.
268
   * </p>
269
   *
270
   * @see #addViewPortListener(ViewPortListener)
271
   * @see #removeViewPortListener(ViewPortListener)
272
   */
273
  private ArrayList listeners = new ArrayList();
274

    
275
  /**
276
   * <p>
277
   * The offset is the position where start drawing the map.
278
   * </p>
279
   * <p>
280
   * The offset of a <a href="http://www.gvsig.gva.es/">gvSIG</a>'s <i>View</i>
281
   * is always (0, 0) because the drawing area fits with the full window area.
282
   * But in a <a href="http://www.gvsig.gva.es/">gvSIG</a>'s <i>Layout</i> it's
283
   * up to the place where the <code>FFrameView</code> is located.
284
   * </p>
285
   *
286
   * @see #getOffset()
287
   * @see #setOffset(Point2D)
288
   */
289
  private Point2D offset = new Point2D.Double(0, 0);
290

    
291
  /**
292
   * <p>
293
   * Clipping area.
294
   * </p>
295
   */
296
  // private Rectangle2D clip;
297

    
298
  /**
299
   * <p>
300
   * Background color of this view.
301
   * </p>
302
   *
303
   * @see #getBackColor()
304
   * @see #setBackColor(Color)
305
   */
306
  private Color backColor = null; // Color.WHITE;
307

    
308
  /**
309
   * <p>
310
   * Information about the map projection used in this view.
311
   * </p>
312
   *
313
   * @see #getProjection()
314
   * @see #setProjection(IProjection)
315
   */
316
  private IProjection proj;
317

    
318
  /**
319
   * <p>
320
   * Represents the distance in <i>world coordinates</i> equivalent to 1 pixel
321
   * in the view with the current extent.
322
   * </p>
323
   *
324
   * @see #getDist1pixel()
325
   * @see #setDist1pixel(double)
326
   */
327
  private double dist1pixel;
328

    
329
  /**
330
   * <p>
331
   * Represents the distance in <i>world coordinates</i> equivalent to 3 pixels
332
   * in the view with the current extent.
333
   * </p>
334
   *
335
   * @see #getDist3pixel()
336
   * @see #setDist3pixel(double)
337
   */
338
  private double dist3pixel;
339

    
340
  /**
341
   * <p>
342
   * Ratio between the size of <code>imageSize</code> and <code>extent</code>: <br>
343
   * <i>
344
   *
345
   * <pre>
346
   * min{(imageSize.getHeight()/extent.getHeight(), imageSize.getWidth()/extent.getWidth())}
347
   * </pre>
348
   *
349
   * </i>
350
   * </p>
351
   */
352
  private double scale;
353

    
354
  /**
355
   * <p>
356
   * Clipping area.
357
   * </p>
358
   *
359
   * @see #setClipRect(Rectangle2D)
360
   */
361
  private Rectangle2D cliprect;
362

    
363
  /**
364
   * <p>
365
   * Enables or disables the <i>"adjustable extent"</i> mode.
366
   * </p>
367
   * <p>
368
   * When calculates the affine transform, if
369
   * <ul>
370
   * <li><i>enabled</i>: the new <code>adjustedExtent</code> will have the (X,
371
   * Y) coordinates of the <code>extent</code> and an area that will be an scale
372
   * of the image size. That area will have different height or width (not both)
373
   * of the extent according the least ratio (height or width) in
374
   *
375
   * <pre>
376
   * image.size/extent.size&quot;
377
   * </pre>.
378
   * <li><i>disabled</i>: the new <code>adjustedExtent</code> will be like
379
   * <code>extent</code>.
380
   * </ul>
381
   * </p>
382
   *
383
   * @see #setAdjustable(boolean)
384
   */
385
  private boolean adjustableExtent = true;
386

    
387
  /**
388
   * <p>
389
   * ViewPort resolution in <i>dots-per-inch</i>. Useful to calculate the
390
   * geographic scale of the view.
391
   * </p>
392
   *
393
   * @see Toolkit#getScreenResolution()
394
   * @see MapContext#getScaleView()
395
   */
396
  private Double dpi = null;
397

    
398
  public ViewPort() {
399

    
400
  }
401

    
402
  /**
403
   * <p>
404
   * Creates a new view port with the information of the projection in
405
   * <code>proj</code> argument, and default configuration:
406
   * </p>
407
   * <p>
408
   * <ul>
409
   * <li><i><code>distanceUnits</code></i> = meters
410
   * <li><i><code>mapUnits</code></i> = meters
411
   * <li><i><code>backColor</code></i> = <i>undefined</i>
412
   * <li><i><code>offset</code></i> = <code>new Point2D.Double(0, 0);</code>
413
   * </ul>
414
   * </p>
415
   *
416
   * @param proj information of the projection for this view port
417
   */
418
  public ViewPort(IProjection proj) {
419
    // Por defecto
420
    this.proj = proj;
421
  }
422

    
423
  /**
424
   * <p>
425
   * Changes the status of the <i>"adjustable extent"</i> option to enabled or
426
   * disabled.
427
   * </p>
428
   * <p>
429
   * If view port isn't adjustable, won't bear in mind the aspect ratio of the
430
   * available rectangular area to calculate the affine transform from the
431
   * original map in real coordinates. (Won't scale the image to adapt it to the
432
   * available rectangular area).
433
   * </p>
434
   *
435
   * @param boolean the boolean to be set
436
   */
437
  public void setAdjustable(boolean adjustable) {
438
    if (adjustable == adjustableExtent) {
439
      return;
440
    }
441
    adjustableExtent = adjustable;
442
    this.updateDrawVersion();
443
  }
444

    
445
  /**
446
   * <p>
447
   * Appends the specified {@link ViewPortListener ViewPortListener} listener if
448
   * weren't.
449
   * </p>
450
   *
451
   * @param arg0 the listener to add
452
   * @return <code>true</code> if has been added successfully
453
   * @see #removeViewPortListener(ViewPortListener)
454
   */
455
  public boolean addViewPortListener(ViewPortListener arg0) {
456
    if (!listeners.contains(arg0)) {
457
      return listeners.add(arg0);
458
    }
459
    return false;
460
  }
461

    
462
  /**
463
   * <p>
464
   * Removes the specified {@link ViewPortListener ViewPortListener} listener,
465
   * if existed.
466
   * </p>
467
   *
468
   * @param arg0 the listener to remove
469
   * @return <code>true</code> if the contained the specified listener.
470
   * @see #addViewPortListener(ViewPortListener)
471
   */
472
  public boolean removeViewPortListener(ViewPortListener arg0) {
473
    return listeners.remove(arg0);
474
  }
475

    
476
  /**
477
   * <p>
478
   * Converts and returns the distance <code>d</code>, that is in <i>map
479
   * coordinates</i> to <i>screen coordinates</i> using a <i>delta transform</i>
480
   * with the transformation affine information in the {@link #trans #trans}
481
   * attribute.
482
   * </p>
483
   *
484
   * @param d distance in <i>map coordinates</i>
485
   * @return distance equivalent in <i>screen coordinates</i>
486
   * @see #toMapDistance(int)
487
   * @see AffineTransform#deltaTransform(Point2D, Point2D)S
488
   */
489
  public int fromMapDistance(double d) {
490
    Point2D.Double pWorld = new Point2D.Double(1, 1);
491
    Point2D.Double pScreen = new Point2D.Double();
492

    
493
    try {
494
      trans.deltaTransform(pWorld, pScreen);
495
    }
496
    catch (Exception e) {
497
      System.err.print(e.getMessage());
498
    }
499

    
500
    return (int) (d * pScreen.x);
501
  }
502

    
503
  /**
504
   * <p>
505
   * Converts and returns the 2D point <code>(x,y)</code>, that is in <i>map
506
   * coordinates</i> to <i>screen coordinates</i> (pixels) using the affine
507
   * transformation in the {@link #trans #trans} attribute.
508
   * </p>
509
   *
510
   * @param x the <code>x</code> <i>map coordinate</i> of a 2D point
511
   * @param y the <code>y</code> <i>map coordinate</i> of a 2D point
512
   * @return 2D point equivalent in <i>screen coordinates</i> (pixels)
513
   * @see #fromMapPoint(Point2D)
514
   * @see AffineTransform#transform(Point2D, Point2D)
515
   */
516
  public Point2D fromMapPoint(double x, double y) {
517
    Point2D.Double pWorld = new Point2D.Double(x, y);
518
    Point2D.Double pScreen = new Point2D.Double();
519

    
520
    try {
521
      trans.transform(pWorld, pScreen);
522
    }
523
    catch (Exception e) {
524
      System.err.print(e.getMessage());
525
    }
526

    
527
    return pScreen;
528
  }
529

    
530
  /**
531
   * <p>
532
   * Converts and returns the 2D point argument, that is in <i>map
533
   * coordinates</i> to <i>screen coordinates</i> (pixels) using the affine
534
   * transformation in the {@link #trans #trans} attribute.
535
   * </p>
536
   *
537
   * @param point the 2D point in <i>map coordinates</i>
538
   * @return 2D point equivalent in <i>screen coordinates</i> (pixels)
539
   * @see #toMapPoint(Point2D)
540
   * @see #fromMapPoint(double, double)
541
   */
542
  public Point2D fromMapPoint(Point2D point) {
543
    return fromMapPoint(point.getX(), point.getY());
544
  }
545

    
546
  /**
547
   * <p>
548
   * Converts and returns the 2D point <code>(x,y)</code>, that is in <i>screen
549
   * coordinates</i> (pixels) to <i>map coordinates</i> using the affine
550
   * transformation in the {@link #trans #trans} attribute.
551
   * </p>
552
   *
553
   * @param x the <code>x</code> <i>screen coordinate</i> of a 2D point
554
   * @param y the <code>y</code> <i>screen coordinate</i> of a 2D point
555
   * @return 2D point equivalent in <i>map coordinates</i>
556
   * @see #toMapPoint(Point2D)
557
   * @see #fromMapPoint(double, double)
558
   * @deprecated use {@link #convertToMapPoint(int, int)}
559
   */
560
  public Point2D toMapPoint(int x, int y) {
561
    Point2D pScreen = new Point2D.Double(x, y);
562

    
563
    return toMapPoint(pScreen);
564
  }
565

    
566
  /**
567
   * <p>
568
   * Converts and returns the {@link Rectangle2D Rectangle2D}, that is in
569
   * <i>screen coordinates</i> (pixels) to <i>map coordinates</i> using
570
   * {@linkplain #toMapDistance(int)}, and {@linkplain #toMapPoint(int, int)}.
571
   * </p>
572
   *
573
   * @param r the 2D rectangle in <i>screen coordinates</i> (pixels)
574
   * @return 2D rectangle equivalent in <i>map coordinates</i>
575
   * @see #fromMapRectangle(Rectangle2D)
576
   * @see #toMapDistance(int)
577
   * @see #toMapPoint(int, int)
578
   */
579
  public Rectangle2D toMapRectangle(Rectangle2D r) {
580
    Rectangle2D rect = new Rectangle2D.Double();
581
    Point2D p1 = toMapPoint((int) r.getX(), (int) r.getY());
582
    Point2D p2 = toMapPoint((int) r.getMaxX(), (int) r.getMaxY());
583
    rect.setFrameFromDiagonal(p1, p2);
584
    return rect;
585
  }
586

    
587
  /**
588
   * <p>
589
   * Converts and returns the distance <code>d</code>, that is in <i>screen
590
   * coordinates</i> to <i>map coordinates</i> using the transformation affine
591
   * information in the {@link #trans #trans} attribute.
592
   * </p>
593
   *
594
   * @param d distance in pixels
595
   * @return distance equivalent in <i>map coordinates</i>
596
   * @see #fromMapDistance(double)
597
   * @see AffineTransform
598
   */
599
  public double toMapDistance(int d) {
600
    double dist = d / trans.getScaleX();
601

    
602
    return dist;
603
  }
604

    
605
  /**
606
   * <p>
607
   * Converts and returns the 2D point argument, that is in <i>screen
608
   * coordinates</i> (pixels) to <i>map coordinates</i> using the inverse affine
609
   * transformation of the {@link #trans #trans} attribute.
610
   * </p>
611
   *
612
   * @param pScreen the 2D point in <i>screen coordinates</i> (pixels)
613
   * @return 2D point equivalent in <i>map coordinates</i>
614
   * @see #toMapPoint(int, int)
615
   * @see AffineTransform#createInverse()
616
   * @see AffineTransform#transform(Point2D, Point2D)
617
   * @deprecated use {@link #convertToMapPoint(Point2D)}
618
   */
619
  public Point2D toMapPoint(Point2D pScreen) {
620
    Point2D.Double pWorld = new Point2D.Double();
621
    AffineTransform at;
622

    
623
    if( pScreen == null ) {
624
        return null;
625
    }
626
    try {
627
      at = trans.createInverse();
628
      at.transform(pScreen, pWorld);
629
    }
630
    catch (NoninvertibleTransformException e) {
631
      throw new RuntimeException("Non invertible transform Exception", e);
632
    }
633

    
634
    return pWorld;
635
  }
636

    
637
  public Point convertToMapPoint(Point2D pScreen) {
638
    Point2D p = toMapPoint(pScreen);
639
    try {
640
        Point point = geomManager.createPoint(
641
                p.getX(), 
642
                p.getY(),
643
                Geometry.SUBTYPES.GEOM2D
644
        );
645
        point.setProjection(this.getProjection());
646
        return point;
647
    }
648
    catch (CreateGeometryException e) {
649
      // FIXME: Use a most especific exception.
650
      throw new RuntimeException(e);
651
    }
652
  }
653

    
654
  public Point convertToMapPoint(int x, int y) {
655
    Point2D pScreen = new Point2D.Double(x, y);
656

    
657
    return convertToMapPoint(pScreen);
658
  }
659

    
660
  /**
661
   * <p>
662
   * Returns the real distance (in <i>world coordinates</i>) at the graphic
663
   * layers of two 2D points (in <i>map coordinates</i>) of the plane where is
664
   * selected the <i>extent</i>.
665
   * </p>
666
   * <p>
667
   * If the projection of this view is UTM, considers the Earth curvature.
668
   * </p>
669
   *
670
   * @param pt1 a 2D point in <i>map coordinates</i>
671
   * @param pt2 another 2D point in <i>map coordinates</i>
672
   * @return the distance in meters between the two points 2D
673
   * @see GeoCalcImpl#distanceVincenty(Point2D, Point2D)
674
   */
675
  public double distanceWorld(Point2D pt1, Point2D pt2) {
676

    
677
    double dist = 0;
678
    if (proj.isProjected()) {
679
      dist = pt1.distance(pt2);
680
      dist = dist * MapContext.getDistanceTrans2Meter()[getMapUnits()];
681
    }
682
    else {
683
      GeoCalc geocalc = new GeoCalc(proj);
684
      dist = geocalc.distanceVincenty(pt1, pt2);
685
    }
686
    return dist;
687
  }
688

    
689
  /**
690
   * <p>
691
   * Sets as extent and adjusted extent of this view port, the previous.
692
   * Recalculating its parameters.
693
   * </p>
694
   *
695
   * @see #getExtents()
696
   * @see #calculateAffineTransform()
697
   * @deprecated use {@link ViewPort#setPreviousEnvelope()}
698
   */
699
  public void setPreviousExtent() {
700
    setPreviousEnvelope();
701
  }
702

    
703
  /**
704
   * <p>
705
   * Sets as envelope and adjusted envelope of this view port, the previous.
706
   * Recalculating its parameters.
707
   * Stores the current extent in the next extents of the history.
708
   * </p>
709
   *
710
   * @see #getExtents()
711
   * @see #calculateAffineTransform()
712
   */
713
  public void setPreviousEnvelope() {
714
    this.updateDrawVersion();
715

    
716
//    extentsHistory.putNext(extent);
717
//    extent = extentsHistory.removePrev();
718
    extent = extentsHistory.setPreviousExtent();
719

    
720
    // Calcula la transformaci?n af?n
721
    calculateAffineTransform();
722

    
723
    // Lanzamos los eventos de extent cambiado
724
    callExtentChanged(getAdjustedExtent());
725
  }
726

    
727
  /**
728
   * <p>
729
   * Sets as envelope and adjusted envelope of this view port, the next.
730
   * Recalculating its parameters.
731
   * Stores the current extent in the previous extents of the history.
732
   * </p>
733
   *
734
   * @see #getExtents()
735
   * @see #calculateAffineTransform()
736
   */
737
  public void setNextEnvelope() {
738
    this.updateDrawVersion();
739

    
740
    extent = extentsHistory.setNextExtent();
741

    
742
    // Calcula la transformaci?n af?n
743
    calculateAffineTransform();
744

    
745
    // Lanzamos los eventos de extent cambiado
746
    callExtentChanged(getAdjustedExtent());
747
  }
748

    
749
  /**
750
   * <p>
751
   * Gets the area selected by user using some tool.
752
   * </p>
753
   * <p>
754
   * When the zoom changes (for instance using the <i>zoom in</i> or <i>zoom
755
   * out</i> tools, but also zooming to a selected feature or shape) the extent
756
   * that covers that area is the value returned by this method. It is not the
757
   * actual area shown because it doesn't care about the aspect ratio of the
758
   * image size of the view. However, any part of the real world contained in
759
   * this extent is shown in the view.
760
   * </p>
761
   * <p>
762
   * If you are looking for the complete extent currently shown, you must use
763
   * the {@linkplain #getAdjustedExtent()} method.
764
   * </p>
765
   *
766
   * @return the current extent
767
   * @see #setEnvelope(Envelope)
768
   * @see #getAdjustedExtent()
769
   * @see #setPreviousExtent()
770
   * @see #getExtents()
771
   * @deprecated use {@link ViewPort#getEnvelope()}
772
   */
773
  public Rectangle2D getExtent() {
774
    return extent;
775
  }
776

    
777
  /**
778
   * <p>
779
   * Gets the envelope selected by user using some tool.
780
   * </p>
781
   * <p>
782
   * When the zoom changes (for instance using the <i>zoom in</i> or <i>zoom
783
   * out</i> tools, but also zooming to a selected feature or shape) the
784
   * envelope that covers that area is the value returned by this method. It is
785
   * not the actual envelope shown because it doesn't care about the aspect
786
   * ratio of the image size of the view. However, any part of the real world
787
   * contained in this envelope is shown in the view.
788
   * </p>
789
   * <p>
790
   * If you are looking for the complete extent currently shown, you must use
791
   * the {@linkplain #getAdjustedEnvelope()} method.
792
   * </p>
793
   *
794
   * @return the current envelope
795
   * @see #setEnvelope(Envelope)
796
   * @see #getAdjustedEnvelope()
797
   * @see #setPreviousEnvelope()
798
   * @see #getEnvelopes()
799
   */
800
  public Envelope getEnvelope() {
801
    if (this.extent == null) {
802
      return null;
803
    }
804
    try {
805
      return geomManager.createEnvelope(extent.getMinX(), extent.getMinY(),
806
          extent.getMaxX(), extent.getMaxY(), SUBTYPES.GEOM2D);
807
      // This class has to use Envelope instead of Rectangle2D. This catch
808
      // will disappear
809
    }
810
    catch (CreateEnvelopeException e) {
811
      logger.error("Error creating the envelope");
812
    }
813
    return null;
814
  }
815

    
816
  /**
817
   * <p>
818
   * Changes the <i>extent</i> and <i>adjusted extent</i> of this view port:<br>
819
   * <ul>
820
   * <li>Stores the previous extent.
821
   * <li>Calculates the new extent using <code>r</code>:
822
   *
823
   * <pre>
824
   * extent = new Rectangle2D.Double(r.getMinX() - 0.1, r.getMinY() - 0.1,
825
   *     r.getWidth() + 0.2, r.getHeight() + 0.2);
826
   * </pre>
827
   * <li>Executes {@linkplain #calculateAffineTransform()}: getting the new
828
   * scale, adjusted extent, affine transformation between map and screen
829
   * coordinates, the real world coordinates equivalent to 1 pixel, and the real
830
   * world coordinates equivalent to 3 pixels.
831
   * <li>Notifies all {@link ViewPortListener ViewPortListener} registered that
832
   * the extent has changed.
833
   * </ul>
834
   * </p>
835
   *
836
   * @param r the new extent
837
   * @see #getExtent()
838
   * @see #getExtents()
839
   * @see #calculateAffineTransform()
840
   * @see #setPreviousExtent()
841
   * @see #clear()
842
   */
843
  public void setEnvelope(Envelope r) {
844
    Rectangle2D newExtent = null;
845
    // Esto comprueba que el extent no es de anchura o altura = "0"
846
    // y si es as? lo redimensiona.
847
    if (r != null) {
848
      if ((r.getMaximum(0) - r.getMinimum(0) == 0)
849
          || (r.getMaximum(1) - r.getMinimum(1) == 0)) {
850
        newExtent = new Rectangle2D.Double(r.getMinimum(0) - 0.1,
851
            r.getMinimum(1) - 0.1, r.getMaximum(0) - r.getMinimum(0) + 0.2,
852
            r.getMaximum(1) - r.getMinimum(1) + 0.2);
853
      }
854
      else {
855
        newExtent = new Rectangle2D.Double(r.getMinimum(0), r.getMinimum(1),
856
            Math.abs(r.getMaximum(0) - r.getMinimum(0)), Math.abs(r
857
                .getMaximum(1) - r.getMinimum(1)));
858
      }
859
    }
860

    
861
    if (this.extent != null && this.extent.equals(newExtent)) {
862
      return;
863
    }
864

    
865
    this.updateDrawVersion();
866
    this.extent = newExtent;
867
    try {
868
        calculateAffineTransform();
869
    } catch(Exception ex) {
870
        this.extent = null;
871
        throw ex;
872
    }
873
    extentsHistory.put(extent);
874

    
875

    
876
    // Lanzamos los eventos de extent cambiado
877
    callExtentChanged(getAdjustedExtent());
878
  }
879

    
880
  /**
881
   * <p>
882
   * Changes the <i>extent</i> and <i>adjusted extent</i> of this view port:<br>
883
   * <ul>
884
   * <li>Executes {@linkplain #calculateAffineTransform()}: getting the new
885
   * scale, adjusted extent, affine transformation between map and screen
886
   * coordinates, the real world coordinates equivalent to 1 pixel, and the real
887
   * world coordinates equivalent to 3 pixels.
888
   * <li>Notifies to all {@link ViewPortListener ViewPortListener} registered
889
   * that the extent has changed.
890
   * </ul>
891
   * </p>
892
   *
893
   * @see #setEnvelope(Envelope)
894
   * @see #calculateAffineTransform()
895
   */
896
  public void refreshExtent() {
897
    //Por compatibilidad con versiones anteriores a la introducci?n de las lista de zooms siguientes
898
    if (extentsHistory.getCurrent() == null) {
899
      extentsHistory.put(extent);
900
    } else {
901
      extent = extentsHistory.getCurrent();
902
    }
903

    
904
    // Calcula la transformaci?n af?n
905
    calculateAffineTransform();
906

    
907
    // Lanzamos los eventos de extent cambiado
908
    callExtentChanged(getAdjustedExtent());
909
  }
910

    
911
  /**
912
   * <p>
913
   * Calculates and returns using the current projection of this view port, the
914
   * scale that is the extent in <i>screen coordinates</i> from the image in
915
   * <i>map coordinates</i>.
916
   * </p>
917
   *
918
   * @return the scale <i>extent / image size</i> projected by this view port
919
   * @deprecated since 07/09/07, use {@linkplain MapContext#getScaleView()}
920
   */
921
  private double getScale() {
922

    
923
    double[] trans2Meter = MapContext.getDistanceTrans2Meter();
924
    if (proj == null) {
925
      double wmeters = ((getImageSize().width / this.getDPI()) * 0.0254);
926
      return (long) ((trans2Meter[getMapUnits()] * getAdjustedEnvelope()
927
          .getLength(0)) / wmeters);
928
    }
929
    else {
930
      return Math.round(proj.getScale(getAdjustedEnvelope().getMinimum(0)
931
          * trans2Meter[getMapUnits()], getAdjustedEnvelope().getMaximum(0)
932
          * trans2Meter[getMapUnits()], getImageSize().width, this.getDPI()));
933
    }
934

    
935
    /*
936
     * return proj.getScale(extent.getMinX(), extent.getMaxX(), imageSize.width,
937
     * dpi);
938
     */
939
  }
940

    
941
  /**
942
   * <p>
943
   * Affine transformation between <i>map 2D coordinates</i> to <i>screen 2D
944
   * coordinates</i> (pixels), preserving the "straightness" and "parallelism"
945
   * of the lines.
946
   * </p>
947
   *
948
   * @return the affine transformation
949
   * @see #setAffineTransform(AffineTransform)
950
   * @see #calculateAffineTransform()
951
   */
952
  public AffineTransform getAffineTransform() {
953
    return trans;
954
  }
955

    
956
  /**
957
   * <p>
958
   * Returns the size of the image projected.
959
   * </p>
960
   *
961
   * @return the image size
962
   * @see #setImageSize(Dimension)
963
   * @see #getImageHeight()
964
   * @see #getImageWidth()
965
   */
966
  public Dimension getImageSize() {
967
    return imageSize;
968
  }
969

    
970
  /**
971
   * <p>
972
   * Sets the size of the image projected, recalculating the parameters of this
973
   * view port.
974
   * </p>
975
   *
976
   * @param imageSize the image size
977
   * @see #getImageSize()
978
   * @see #calculateAffineTransform()
979
   */
980
  public void setImageSize(Dimension imageSize) {
981

    
982
    if (this.imageSize == null || (!this.imageSize.equals(imageSize))) {
983
      this.updateDrawVersion();
984
      this.imageSize = imageSize;
985
      calculateAffineTransform();
986
    }
987
  }
988

    
989
  /**
990
   * <p>
991
   * Notifies to all view port listeners registered, that the adjusted extent of
992
   * this view port has changed.
993
   * </p>
994
   *
995
   * @param newRect the new adjusted extend
996
   * @see #refreshExtent()
997
   * @see #setEnvelope(Envelope)
998
   * @see #setPreviousExtent()
999
   * @see ExtentEvent
1000
   * @see ViewPortListener
1001
   */
1002
  protected void callExtentChanged(Envelope newRect) {
1003
    ExtentEvent ev = ExtentEvent.createExtentEvent(newRect);
1004

    
1005
    for (int i = 0; i < listeners.size(); i++) {
1006
      ViewPortListener listener = (ViewPortListener) listeners.get(i);
1007
      listener.extentChanged(ev);
1008
    }
1009
  }
1010

    
1011
  /**
1012
   * <p>
1013
   * Notifies to all view port listeners registered, that the time of this view
1014
   * port has changed.
1015
   * </p>
1016
   *
1017
   * @param newTime the new time
1018
   * @see #refreshExtent()
1019
   * @see #setTime(Time)
1020
   * @see ExtentEvent
1021
   * @see ViewPortListener
1022
   */
1023
  protected void callTimeChanged(Time newTime) {
1024
    ExtentEvent viewPortEvent = new ExtentEvent(newTime);
1025

    
1026
    for (int i = 0; i < listeners.size(); i++) {
1027
      ViewPortListener listener = (ViewPortListener) listeners.get(i);
1028
      listener.extentChanged(viewPortEvent);
1029
    }
1030
  }
1031

    
1032
  /**
1033
   * <p>
1034
   * Notifies to all view port listeners registered, that the background color
1035
   * of this view port has changed.
1036
   * </p>
1037
   *
1038
   * @param c the new background color
1039
   * @see #setBackColor(Color)
1040
   * @see ColorEvent
1041
   * @see ViewPortListener
1042
   */
1043
  private void callColorChanged(Color c) {
1044
    ColorEvent ce = ColorEvent.createColorEvent(c);
1045

    
1046
    for (int i = 0; i < listeners.size(); i++) {
1047
      ViewPortListener listener = (ViewPortListener) listeners.get(i);
1048
      listener.backColorChanged(ce);
1049
    }
1050
  }
1051

    
1052
  /**
1053
   * <p>
1054
   * Notifies to all view port listeners registered, that the projection of this
1055
   * view port has changed.
1056
   * </p>
1057
   *
1058
   * @param projection the new projection
1059
   * @see #setProjection(IProjection)
1060
   * @see ProjectionEvent
1061
   * @see ViewPortListener
1062
   */
1063
  private void callProjectionChanged(IProjection projection) {
1064
    ProjectionEvent ev = ProjectionEvent.createProjectionEvent(projection);
1065

    
1066
    for (int i = 0; i < listeners.size(); i++) {
1067
      ViewPortListener listener = (ViewPortListener) listeners.get(i);
1068
      listener.projectionChanged(ev);
1069
    }
1070
  }
1071

    
1072
  /**
1073
   * <p>
1074
   * Calculates the affine transformation between the {@link #extent extent} in
1075
   * <i>map 2D coordinates</i> to the image area in the screen, in <i>screen 2D
1076
   * coordinates</i> (pixels).
1077
   * </p>
1078
   * <p>
1079
   * This process recalculates some parameters of this view port:<br>
1080
   * <ul>
1081
   * <li>The new {@link #scale scale} .
1082
   * <li>The new {@link #adjustedExtent adjustedExtent} .
1083
   * <li>The new {@link #trans trans} .
1084
   * <li>The new real world coordinates equivalent to 1 pixel (
1085
   * {@link #dist1pixel dist1pixel}) .
1086
   * <li>The new real world coordinates equivalent to 3 pixels (
1087
   * {@link #dist3pixel dist3pixel}) .
1088
   * </ul>
1089
   * </p>
1090
   *
1091
   * @see #getAffineTransform()
1092
   * @see #setAffineTransform(AffineTransform)
1093
   * @see #refreshExtent()
1094
   * @see #setEnvelope(Envelope)
1095
   * @see #setImageSize(Dimension)
1096
   * @see #setPreviousExtent()
1097
   * @see #createFromXML(XMLEntity)
1098
   * @see AffineTransform
1099
   */
1100
  private void calculateAffineTransform() {
1101
    if ((imageSize == null) || (extent == null) || (imageSize.width <= 0)
1102
        || (imageSize.height <= 0)) {
1103
      return;
1104
    }
1105

    
1106
    AffineTransform escalado = new AffineTransform();
1107
    AffineTransform translacion = new AffineTransform();
1108

    
1109
    double escalaX;
1110
    double escalaY;
1111

    
1112
    escalaX = imageSize.width / extent.getWidth();
1113
    escalaY = imageSize.height / extent.getHeight();
1114

    
1115
    double xCenter = extent.getCenterX();
1116
    double yCenter = extent.getCenterY();
1117
    double newHeight;
1118
    double newWidth;
1119

    
1120
    adjustedExtent = new Rectangle2D.Double();
1121

    
1122
    if (adjustableExtent) {
1123
      if (escalaX < escalaY) {
1124
        scale = escalaX;
1125
        newHeight = imageSize.height / scale;
1126
        adjustedExtent.setRect(xCenter - (extent.getWidth() / 2.0), yCenter
1127
            - (newHeight / 2.0), extent.getWidth(), newHeight);
1128
      }
1129
      else {
1130
        scale = escalaY;
1131
        newWidth = imageSize.width / scale;
1132
        adjustedExtent.setRect(xCenter - (newWidth / 2.0),
1133
            yCenter - (extent.getHeight() / 2.0), newWidth, extent.getHeight());
1134
      }
1135
      escalado.setToScale(scale, -scale);
1136
    }
1137
    else { // adjusted is same as extent
1138
      scale = escalaX;
1139
      adjustedExtent.setFrame(extent);
1140
      escalado.setToScale(escalaX, -escalaY);
1141
    }
1142
    Envelope env = getAdjustedExtent();
1143
    if (env == null) {
1144
      return;
1145
    }
1146
    translacion.setToTranslation(-env.getMinimum(0), -env.getMinimum(1)
1147
        - getAdjustedExtent().getLength(1));
1148

    
1149
    AffineTransform offsetTrans = new AffineTransform();
1150
    offsetTrans.setToTranslation(offset.getX(), offset.getY());
1151

    
1152
    trans.setToIdentity();
1153
    trans.concatenate(offsetTrans);
1154
    trans.concatenate(escalado);
1155

    
1156
    trans.concatenate(translacion);
1157

    
1158
    // Calculamos las distancias de 1 pixel y 3 pixel con esa
1159
    // transformaci?n
1160
    // de coordenadas, de forma que est?n precalculadas para cuando las
1161
    // necesitemos
1162
    AffineTransform at;
1163

    
1164
    try {
1165
      at = trans.createInverse();
1166

    
1167
      Point2D pPixel = new Point2D.Float(1, 1);
1168

    
1169
      Point2D.Float pProv = new Point2D.Float();
1170
      at.deltaTransform(pPixel, pProv);
1171

    
1172
      dist1pixel = pProv.x;
1173
      dist3pixel = 3 * pProv.x;
1174
    }
1175
    catch (NoninvertibleTransformException e) {
1176
      String msg = "Can't calculate affine transform for the view port." + "\n" +
1177
        "The extent can be out of range for this projection." + "\n" +
1178
        "transformada afin: " + Objects.toString(trans) + "\n" +
1179
        "extent: " + Objects.toString(extent) + "\n" +
1180
        "imageSize: " + Objects.toString(imageSize) + "\n" +
1181
        "projection: " + Objects.toString(proj) + "\n" +
1182
        e.getLocalizedMessage() 
1183
      ;
1184
      logger.error(msg, e);
1185
      trans.setToIdentity();
1186
      scale = 0;
1187
      adjustedExtent = null;
1188
      adjustableExtent = true;
1189
      throw new RuntimeException(msg, e);
1190
    }
1191
  }
1192

    
1193
  /**
1194
   * <p>
1195
   * Sets the offset.
1196
   * </p>
1197
   * <p>
1198
   * The offset is the position where start drawing the map.
1199
   * </p>
1200
   *
1201
   * @param p 2D point that represents the offset in pixels
1202
   * @see #getOffset()
1203
   */
1204
  public void setOffset(Point2D p) {
1205
    if (!offset.equals(p)) {
1206
      this.updateDrawVersion();
1207
      offset = p;
1208
    }
1209
  }
1210

    
1211
  /**
1212
   * <p>
1213
   * Gets the offset.
1214
   * </p>
1215
   * <p>
1216
   * The offset is the position where start drawing the map.
1217
   * </p>
1218
   *
1219
   * @return 2D point that represents the offset in pixels
1220
   * @see #setOffset(Point2D)
1221
   */
1222
  public Point2D getOffset() {
1223
    return offset;
1224
  }
1225

    
1226
  /**
1227
   * <p>
1228
   * Sets the background color.
1229
   * </p>
1230
   *
1231
   * @param c the new background color
1232
   * @see #getBackColor()
1233
   */
1234
  public void setBackColor(Color c) {
1235
    if (!c.equals(this.backColor)) {
1236
      this.updateDrawVersion();
1237
      backColor = c;
1238
      callColorChanged(backColor);
1239
    }
1240
  }
1241

    
1242
  /**
1243
   * <p>
1244
   * Gets the background color.
1245
   * </p>
1246
   *
1247
   * @return the background color of the view
1248
   * @see #setBackColor(Color)
1249
   */
1250
  public Color getBackColor() {
1251
    return backColor;
1252
  }
1253

    
1254
  /**
1255
   * <p>
1256
   * Returns the extent currently covered by the view adjusted (scaled) to the
1257
   * image size aspect.
1258
   * </p>
1259
   *
1260
   * @return extent of the view adjusted to the image size aspect
1261
   * @see #setAdjustable(boolean)
1262
   * @deprecated use {@link ViewPort#getAdjustedEnvelope()} instead
1263
   */
1264
  public Envelope getAdjustedExtent() {
1265
    return getAdjustedEnvelope();
1266
  }
1267

    
1268
  /**
1269
   * <p>
1270
   * Returns the envelope currently covered by the view adjusted (scaled) to the
1271
   * image size aspect.
1272
   * </p>
1273
   *
1274
   * @return envelope of the view adjusted to the image size aspect
1275
   * @see #setAdjustable(boolean)
1276
   */
1277
    public Envelope getAdjustedEnvelope() {
1278
        if (adjustedExtent == null) {
1279
            calculateAffineTransform();
1280
        }
1281
        if (cliprect != null) {
1282
            Rectangle2D r = adjustedExtent.createIntersection(cliprect);
1283
            try {
1284
                return geomManager.createEnvelope(r.getX(), r.getY(), r.getMaxX(), r.getMaxY(), SUBTYPES.GEOM2D);
1285
            } catch (CreateEnvelopeException e) {
1286
                e.printStackTrace();
1287
                logger.error("Error adjusting the extent", e);
1288
            }
1289
        }
1290
        if (adjustedExtent != null) {
1291
            try {
1292
                return geomManager.createEnvelope(adjustedExtent.getX(), adjustedExtent.getY(),
1293
                    adjustedExtent.getMaxX(), adjustedExtent.getMaxY(), SUBTYPES.GEOM2D);
1294
            } catch (CreateEnvelopeException e) {
1295
                e.printStackTrace();
1296
                logger.error("Error adjusting the extent", e);
1297
            }
1298
        }
1299
        return null;
1300
    }
1301

    
1302
  /**
1303
   * <p>
1304
   * Returns the measurement unit of this view port used for measuring distances
1305
   * and displaying information.
1306
   * </p>
1307
   *
1308
   * @return the measurement unit of this view used for measuring distances and
1309
   *         displaying information
1310
   * @see #setDistanceUnits(int)
1311
   */
1312
  public int getDistanceUnits() {
1313
    return distanceUnits;
1314
  }
1315

    
1316
  /**
1317
   * <p>
1318
   * Returns the measurement unit of this view port used for measuring areas and
1319
   * displaying information.
1320
   * </p>
1321
   *
1322
   * @return the measurement unit of this view used for measuring areas and
1323
   *         displaying information
1324
   * @see #setDistanceUnits(int)
1325
   */
1326
  public int getDistanceArea() {
1327
    return distanceArea;
1328
  }
1329

    
1330
  /**
1331
   * <p>
1332
   * Sets the measurement unit of this view port used for measuring distances
1333
   * and displaying information.
1334
   * </p>
1335
   *
1336
   * @param distanceUnits the measurement unit of this view used for measuring
1337
   *          distances and displaying information
1338
   * @see #getDistanceUnits()
1339
   */
1340
  public void setDistanceUnits(int distanceUnits) {
1341
    this.distanceUnits = distanceUnits;
1342
  }
1343

    
1344
  /**
1345
   * <p>
1346
   * Sets the measurement unit of this view port used for measuring areas and
1347
   * displaying information.
1348
   * </p>
1349
   *
1350
   * @param distanceUnits the measurement unit of this view used for measuring
1351
   *          areas and displaying information
1352
   * @see #getDistanceUnits()
1353
   */
1354
  public void setDistanceArea(int distanceArea) {
1355
    this.distanceArea = distanceArea;
1356
  }
1357

    
1358
  /**
1359
   * <p>
1360
   * Gets the measurement unit used by this view port for the map.
1361
   * </p>
1362
   *
1363
   * @return Returns the current map measure unit
1364
   * @see #setMapUnits(int)
1365
   */
1366
  public int getMapUnits() {
1367
    return mapUnits;
1368
  }
1369

    
1370
  /**
1371
   * <p>
1372
   * Sets the measurement unit used by this view port for the map.
1373
   * </p>
1374
   *
1375
   * @param mapUnits the new map measure unit
1376
   * @see #getMapUnits()
1377
   */
1378
  public void setMapUnits(int mapUnits) {
1379
    this.mapUnits = mapUnits;
1380
  }
1381

    
1382
  /**
1383
   * <p>
1384
   * Gets the width in <i>screen coordinates</i> of the rectangle where the
1385
   * image is displayed.
1386
   * </p>
1387
   * <p>
1388
   * Used by {@linkplain #calculateAffineTransform()} to calculate:<br>
1389
   * <ul>
1390
   * <li>The new {@link #scale scale} .
1391
   * <li>The new {@link #adjustedExtent adjustableExtent} .
1392
   * <li>The new {@link #trans trans} .
1393
   * <li>The new real world coordinates equivalent to 1 pixel (
1394
   * {@link #dist1pixel dist1pixel}) .
1395
   * <li>The new real world coordinates equivalent to 3 pixels (
1396
   * {@link #dist3pixel dist3pixel}) .
1397
   * </ul>
1398
   * </p>
1399
   *
1400
   * @see #getImageHeight()
1401
   * @see #getImageSize()
1402
   * @see #setImageSize(Dimension)
1403
   */
1404
  public int getImageWidth() {
1405
    return imageSize.width;
1406
  }
1407

    
1408
  /**
1409
   * <p>
1410
   * Gets the height in <i>screen coordinates</i> of the rectangle where the
1411
   * image is displayed.
1412
   * </p>
1413
   * <p>
1414
   * Used by {@linkplain #calculateAffineTransform()} to calculate:<br>
1415
   * <ul>
1416
   * <li>The new {@link #scale scale} .
1417
   * <li>The new {@link #adjustedExtent adjustableExtent} .
1418
   * <li>The new {@link #trans trans} .
1419
   * <li>The new real world coordinates equivalent to 1 pixel (
1420
   * {@link #dist1pixel dist1pixel}) .
1421
   * <li>The new real world coordinates equivalent to 3 pixels (
1422
   * {@link #dist3pixel dist3pixel}) .
1423
   * </ul>
1424
   * </p>
1425
   *
1426
   * @see #getImageWidth()
1427
   * @see #getImageSize()
1428
   * @see #setImageSize(Dimension)
1429
   */
1430
  public int getImageHeight() {
1431
    return imageSize.height;
1432
  }
1433

    
1434
  /**
1435
   * <p>
1436
   * Gets the distance in <i>world coordinates</i> equivalent to 1 pixel in the
1437
   * view with the current extent.
1438
   * </p>
1439
   *
1440
   * @return the distance
1441
   * @see #setDist1pixel(double)
1442
   */
1443
  public double getDist1pixel() {
1444
    return dist1pixel;
1445
  }
1446

    
1447
  /**
1448
   * <p>
1449
   * Sets the distance in <i>world coordinates</i> equivalent to 1 pixel in the
1450
   * view with the current extent.
1451
   * </p>
1452
   *
1453
   * @param dist1pixel the distance
1454
   * @see #getDist1pixel()
1455
   */
1456
  public void setDist1pixel(double dist1pixel) {
1457
    if (dist1pixel == this.dist1pixel) {
1458
      return;
1459
    }
1460
    this.updateDrawVersion();
1461
    this.dist1pixel = dist1pixel;
1462
  }
1463

    
1464
  /**
1465
   * <p>
1466
   * Gets the distance in <i>world coordinates</i> equivalent to 3 pixels in the
1467
   * view with the current extent.
1468
   * </p>
1469
   *
1470
   * @return the distance
1471
   * @see #setDist3pixel(double)
1472
   */
1473
  public double getDist3pixel() {
1474
    return dist3pixel;
1475
  }
1476

    
1477
  /**
1478
   * <p>
1479
   * Sets the distance in <i>world coordinates</i> equivalent to 3 pixels in the
1480
   * view with the current extent.
1481
   * </p>
1482
   *
1483
   * @param dist3pixel the distance
1484
   * @see #getDist3pixel()
1485
   */
1486
  public void setDist3pixel(double dist3pixel) {
1487
    if (this.dist3pixel == dist3pixel) {
1488
      return;
1489
    }
1490
    this.updateDrawVersion();
1491
    this.dist3pixel = dist3pixel;
1492
  }
1493

    
1494
  /**
1495
   * <p>
1496
   * Returns the last previous extents of this view port.
1497
   * </p>
1498
   *
1499
   * @return the last previous extents of this view port
1500
   * @see #setPreviousExtent()
1501
   * @deprecated use {@link ViewPort#getEnvelopes()}
1502
   */
1503
  public ExtentHistory getExtents() {
1504
    return getEnvelopes();
1505
  }
1506

    
1507
  /**
1508
   * <p>
1509
   * Returns the last previous extents of this view port.
1510
   * </p>
1511
   *
1512
   * @return the last previous extents of this view port
1513
   * @see #setPreviousExtent()
1514
   */
1515
  public ExtentHistory getEnvelopes() {
1516
    return extentsHistory;
1517
  }
1518

    
1519
  /**
1520
   * <p>
1521
   * Gets the projection used in this view port.
1522
   * </p>
1523
   *
1524
   * @return projection used in this view port
1525
   * @see #setProjection(IProjection)
1526
   */
1527
  public IProjection getProjection() {
1528
    return proj;
1529
  }
1530

    
1531
  /**
1532
   * <p>
1533
   * Sets the projection to this view port.
1534
   * </p>
1535
   *
1536
   * @param proj the new projection
1537
   * @see #getProjection()
1538
   */
1539
  public void setProjection(IProjection proj) {
1540
    if (this.proj == null || !this.proj.getAbrev().equals(proj.getAbrev())) {
1541
      this.updateDrawVersion();
1542
      this.proj = proj;
1543
      callProjectionChanged(proj);
1544
    }
1545
  }
1546

    
1547
  // -----------------------------------------------------------------------------------------------------------
1548
  // NOTA PARA DESARROLLADORES SOBRE EL M?TODO
1549
  // "public void setAffineTransform(AffineTransform at)"
1550
  // ==============================================================================================
1551
  // Only used for print, should be removed, redefining the {@link
1552
  // RasterAdapter RasterAdapter} interface,
1553
  // allowing it to receive a {@link ViewPortData ViewPortData} .
1554
  // -----------------------------------------------------------------------------------------------------------
1555

    
1556
  /**
1557
   * <p>
1558
   * Sets only the affine transform to this view port, without updating
1559
   * dependent attributes.
1560
   * </p>
1561
   * <p>
1562
   * <b><i>This method could be problematic!</i></b>
1563
   * </p>
1564
   *
1565
   * @param at the affine transform to set
1566
   * @see #getAffineTransform()
1567
   * @see #calculateAffineTransform()
1568
   */
1569
  public void setAffineTransform(AffineTransform at) {
1570
    this.trans = at;
1571
  }
1572

    
1573
  /**
1574
   * <p>
1575
   * Returns an XML entity that represents this view port instance:<br>
1576
   * <ul>
1577
   * <li>Properties:
1578
   * <ul>
1579
   * <li><i>className</i>: name of this class.
1580
   * <li>If defined, the adjusted extent:
1581
   * <ul>
1582
   * <li><i>adjustedExtentX</i>: X coordinate of the adjusted extent.
1583
   * <li><i>adjustedExtentY</i>: Y coordinate of the adjusted extent.
1584
   * <li><i>adjustedExtentW</i>: width of the adjusted extent.
1585
   * <li><i>adjustedExtentH</i>: height of the adjusted extent.
1586
   * </ul>
1587
   * <li>If defined, the background color:
1588
   * <ul>
1589
   * <li><i>backColor</i>: background color.
1590
   * </ul>
1591
   * <li>If defined, the clip:
1592
   * <ul>
1593
   * <li><i>clipX</i>: X coordinate of the clip.
1594
   * <li><i>clipY</i>: Y coordinate of clip.
1595
   * <li><i>clipW</i>: width of the clip.
1596
   * <li><i>clipH</i>: height of the clip.
1597
   * </ul>
1598
   * <li><i>dist1pixel</i>: the distance in world coordinates equivalent to 1
1599
   * pixel in the view.
1600
   * <li><i>dist3pixel</i>: the distance in world coordinates equivalent to 3
1601
   * pixels in the view.
1602
   * <li><i>distanceUnits</i>: the distance measurement unit.
1603
   * <li>If defined, the extent:
1604
   * <ul>
1605
   * <li><i>extentX</i>: X coordinate of the extent.
1606
   * <li><i>extentY</i>: Y coordinate of the extent.
1607
   * <li><i>extentW</i>: width of the extent.
1608
   * <li><i>extentH</i>: height of the extent.
1609
   * </ul>
1610
   * <li><i>mapUnits</i>: the map measurement unit.
1611
   * <li><i>offsetX</i>: X coordinate of the offset.
1612
   * <li><i>offsetY</i>: Y coordinate of the offset.
1613
   * <li>If defined, the projection:
1614
   * <ul>
1615
   * <li>If its defined, the projection:
1616
   * <ul>
1617
   * <li><i>proj</i>: the projection.</li>
1618
   * </ul>
1619
   * </ul>
1620
   * <li><i>scale</i>: ratio between the size of <code>imageSize</code> and
1621
   * <code>extent</code>.
1622
   * </ul>
1623
   * <li>Child branches:
1624
   * <ul>
1625
   * <li>XML entity of the internal {@link ExtentHistory ExtentHistory} .
1626
   * </ul>
1627
   * </ul>
1628
   *
1629
   * @return the XML entity
1630
   * @see #createFromXML(XMLEntity)
1631
   */
1632
  public void saveToState(PersistentState state) throws PersistenceException {
1633

    
1634
    state.set(FIELD_ADJUSTED_EXTENT, adjustedExtent);
1635
    state.set(FIELD_BACK_COLOR, backColor);
1636
    state.set(FIELD_CLIP, cliprect);
1637
    state.set(FIELD_DIST1PIXEL, dist1pixel);
1638
    state.set(FIELD_DIST3PIXEL, dist3pixel);
1639
    state.set(FIELD_DISTANCE_UNITS, distanceUnits);
1640
    state.set(FIELD_DISTANCE_AREA, distanceArea);
1641

    
1642
    state.set(FIELD_EXTENT, extent);
1643
    state.set(FIELD_EXTENTS, extentsHistory);
1644

    
1645
    state.set(FIELD_MAP_UNITS, mapUnits);
1646
    state.set(FIELD_OFFSET, offset);
1647

    
1648
    state.set(FIELD_PROJ, proj);
1649

    
1650
    state.set(FIELD_IMAGE_SIZE, imageSize);
1651
  }
1652

    
1653
  public void loadFromState(PersistentState state) throws PersistenceException {
1654

    
1655
    adjustedExtent = (Rectangle2D) state.get(FIELD_ADJUSTED_EXTENT);
1656
    backColor = (Color) state.get(FIELD_BACK_COLOR);
1657
    cliprect = (Rectangle2D) state.get(FIELD_CLIP);
1658
    dist1pixel = state.getDouble(FIELD_DIST1PIXEL);
1659
    dist3pixel = state.getDouble(FIELD_DIST3PIXEL);
1660
    distanceUnits = state.getInt(FIELD_DISTANCE_UNITS);
1661
    extentsHistory = (ExtentHistory) state.get(FIELD_EXTENTS);
1662
    extent = (Rectangle2D) state.get(FIELD_EXTENT);
1663
    mapUnits = state.getInt(FIELD_MAP_UNITS);
1664
    offset = (Point2D) state.get(FIELD_OFFSET);
1665
    proj = (IProjection) state.get(FIELD_PROJ);
1666
    imageSize = (Dimension) state.get(FIELD_IMAGE_SIZE);
1667
    distanceArea = state.getInt(FIELD_DISTANCE_AREA);
1668

    
1669
    refreshExtent();
1670
  }
1671

    
1672
  public static class RegisterPersistence implements Callable {
1673

    
1674
    public Object call() throws Exception {
1675
      PersistenceManager manager = ToolsLocator.getPersistenceManager();
1676
      if (manager.getDefinition("ViewPort") == null) {
1677
        DynStruct definition = manager.addDefinition(ViewPort.class,
1678
            "ViewPort", "ViewPort Persistence definition", null, null);
1679

    
1680
        definition.addDynFieldObject(FIELD_ADJUSTED_EXTENT)
1681
            .setClassOfValue(Rectangle2D.class).setMandatory(false);
1682

    
1683
        definition.addDynFieldObject(FIELD_BACK_COLOR)
1684
            .setClassOfValue(Color.class).setMandatory(false);
1685

    
1686
        definition.addDynFieldObject(FIELD_CLIP)
1687
            .setClassOfValue(Rectangle2D.class).setMandatory(false);
1688

    
1689
        definition.addDynFieldDouble(FIELD_DIST1PIXEL).setMandatory(true);
1690

    
1691
        definition.addDynFieldDouble(FIELD_DIST3PIXEL).setMandatory(true);
1692

    
1693
        definition.addDynFieldInt(FIELD_DISTANCE_UNITS).setMandatory(true);
1694

    
1695
        definition.addDynFieldInt(FIELD_DISTANCE_AREA).setMandatory(false);
1696

    
1697
        definition.addDynFieldObject(FIELD_EXTENT)
1698
            .setClassOfValue(Rectangle2D.class).setMandatory(false);
1699

    
1700
        definition.addDynFieldObject(FIELD_EXTENTS)
1701
            .setClassOfValue(ExtentHistory.class).setMandatory(true);
1702

    
1703
        definition.addDynFieldInt(FIELD_MAP_UNITS).setMandatory(true);
1704

    
1705
        definition.addDynFieldObject(FIELD_OFFSET)
1706
            .setClassOfValue(Point2D.class).setMandatory(false);
1707

    
1708
        definition.addDynFieldObject(FIELD_PROJ)
1709
            .setClassOfValue(IProjection.class).setMandatory(true);
1710

    
1711
        definition.addDynFieldObject(FIELD_IMAGE_SIZE)
1712
            .setClassOfValue(Dimension.class).setMandatory(false);
1713
      }
1714
      return Boolean.TRUE;
1715
    }
1716

    
1717
  }
1718

    
1719
  /**
1720
   * Clone the view port without clone the listeners nor the extent history.
1721
   *
1722
   * @return the cloned view port
1723
   */
1724
  public Object clone() throws CloneNotSupportedException {
1725

    
1726
    ViewPort clonedViewPort = (ViewPort) super.clone();
1727
    clonedViewPort.listeners = new ArrayList();
1728
    clonedViewPort.extentsHistory = new ExtentHistory();
1729

    
1730
    if (this.adjustedExtent != null) {
1731
      clonedViewPort.adjustedExtent = (Rectangle2D) this.adjustedExtent.clone();
1732
    }
1733

    
1734
    if (this.cliprect != null) {
1735
      clonedViewPort.cliprect = (Rectangle2D) this.cliprect.clone();
1736
    }
1737

    
1738
    if (this.extent != null) {
1739
      clonedViewPort.extent = (Rectangle2D) this.extent.clone();
1740
    }
1741
    if (this.imageSize != null) {
1742
      clonedViewPort.imageSize = (Dimension) this.imageSize.clone();
1743
    }
1744

    
1745
    if (this.offset != null) {
1746
      clonedViewPort.offset = (Point2D) this.offset.clone();
1747
    }
1748
    if (proj != null) {
1749
      clonedViewPort.proj = (IProjection) this.proj.clone();
1750
    }
1751

    
1752
    clonedViewPort.trans = (AffineTransform) this.trans.clone();
1753

    
1754
    return clonedViewPort;
1755
  }
1756

    
1757
  /**
1758
   * <p>
1759
   * Returns a <code>String</code> representation of the main values of this
1760
   * view port: <code>{@linkplain #extent}</code>,
1761
   * <code>{@linkplain #adjustedExtent}</code>,
1762
   * <code>{@linkplain #imageSize}</code>, <code>{@linkplain #scale}</code>, and
1763
   * <code>{@linkplain #trans}</code>.
1764
   * </p>
1765
   *
1766
   * @return a <code>string</code> representation of the main values of this
1767
   *         view port
1768
   */
1769
  public String toString() {
1770

    
1771
    String str;
1772
    str = "Datos del viewPort:\nExtent=" + extent + "\nadjustedExtent="
1773
        + adjustedExtent + "\nimageSize=" + imageSize + "\nescale=" + scale
1774
        + "\ntrans=" + trans;
1775

    
1776
    return str;
1777
  }
1778

    
1779
  /**
1780
   * <p>
1781
   * Sets the position and size of the clipping rectangle.
1782
   * </p>
1783
   *
1784
   * @param rectView the clipping rectangle to set
1785
   */
1786
  public void setClipRect(Rectangle2D rectView) {
1787
    this.updateDrawVersion();
1788
    cliprect = rectView;
1789
  }
1790

    
1791
  /**
1792
   * <p>
1793
   * Converts and returns the {@link Rectangle2D Rectangle2D}, that is in <i>map
1794
   * coordinates</i> to <i>screen coordinates</i> (pixels) using an <i>inverse
1795
   * transform</i> with the transformation affine information in the
1796
   * {@link #trans #trans} attribute.
1797
   * </p>
1798
   *
1799
   * @param r the 2D rectangle in <i>map coordinates</i>
1800
   * @return 2D rectangle equivalent in <i>screen coordinates</i> (pixels)
1801
   * @see #toMapRectangle(Rectangle2D)
1802
   * @see #fromMapDistance(double)
1803
   * @see #fromMapPoint(Point2D)
1804
   */
1805
  public Rectangle2D fromMapRectangle(Rectangle2D r) {
1806
    Rectangle2D rect = new Rectangle2D.Double();
1807
    Point2D p1 = fromMapPoint((int) r.getX(), (int) r.getY());
1808
    Point2D p2 = fromMapPoint((int) r.getMaxX(), (int) r.getMaxY());
1809
    rect.setFrameFromDiagonal(p1, p2);
1810
    return rect;
1811
  }
1812

    
1813
  /**
1814
   * <p>
1815
   * Recalculates the current <code>{@linkplain #extent}</code> using an scale.
1816
   * It's necessary execute {@linkplain #refreshExtent()} after.
1817
   * </p>
1818
   *
1819
   * @param s the scale to set
1820
   * @deprecated since 07/09/07, use {@linkplain MapContext#setScaleView(long)}
1821
   */
1822
  public void setScale(long s) {
1823
    double x = extent.getX();
1824
    double y = extent.getY();
1825
    double escalaX = imageSize.width / extent.getWidth();
1826
    // double w = imageSize.width / s;
1827
    // double h = imageSize.height / s;
1828
    double difw = escalaX / s;
1829

    
1830
    double x1 = (-x * difw) - x + extent.getWidth() / 2;
1831
    double y1 = (-y * difw) - y + extent.getHeight() / 2;
1832
    double w1 = extent.getWidth() * difw;
1833
    double h1 = extent.getHeight() * difw;
1834
    extent.setRect(-x1, -y1, w1, h1);
1835
  }
1836

    
1837
  public long getDrawVersion() {
1838
    return this.drawVersion;
1839
  }
1840

    
1841
  protected void updateDrawVersion() {
1842
    this.drawVersion++;
1843
  }
1844

    
1845
  public Time getTime() {
1846
    return time;
1847
  }
1848

    
1849
  public void setTime(Time time) {
1850
    this.time = time;
1851
    this.updateDrawVersion();
1852
    callTimeChanged(time);
1853
  }
1854

    
1855
  public double getDPI() {
1856
    if (this.dpi == null) {
1857
      return CompatLocator.getGraphicsUtils().getScreenDPI();
1858
    }
1859
    return this.dpi.doubleValue();
1860
  }
1861

    
1862
  public void setDPI(double dpi) {
1863
    this.dpi = new Double(dpi);
1864
  }
1865

    
1866
  public void setDPIToScreenDPI() {
1867
    this.dpi = null;
1868
  }
1869
}