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 @ 43478

History | View | Annotate | Download (55.6 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
    try {
624
      at = trans.createInverse();
625
      at.transform(pScreen, pWorld);
626
    }
627
    catch (NoninvertibleTransformException e) {
628
      throw new RuntimeException("Non invertible transform Exception", e);
629
    }
630

    
631
    return pWorld;
632
  }
633

    
634
  public Point convertToMapPoint(Point2D pScreen) {
635
    Point2D p = toMapPoint(pScreen);
636
    try {
637
      return geomManager.createPoint(p.getX(), p.getY(),
638
          Geometry.SUBTYPES.GEOM2D);
639
    }
640
    catch (CreateGeometryException e) {
641
      // FIXME: Use a most especific exception.
642
      throw new RuntimeException(e);
643
    }
644
  }
645

    
646
  public Point convertToMapPoint(int x, int y) {
647
    Point2D pScreen = new Point2D.Double(x, y);
648

    
649
    return convertToMapPoint(pScreen);
650
  }
651

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

    
669
    double dist = 0;
670
    if (proj.isProjected()) {
671
      dist = pt1.distance(pt2);
672
      dist = dist * MapContext.getDistanceTrans2Meter()[getMapUnits()];
673
    }
674
    else {
675
      GeoCalc geocalc = new GeoCalc(proj);
676
      dist = geocalc.distanceVincenty(pt1, pt2);
677
    }
678
    return dist;
679
  }
680

    
681
  /**
682
   * <p>
683
   * Sets as extent and adjusted extent of this view port, the previous.
684
   * Recalculating its parameters.
685
   * </p>
686
   *
687
   * @see #getExtents()
688
   * @see #calculateAffineTransform()
689
   * @deprecated use {@link ViewPort#setPreviousEnvelope()}
690
   */
691
  public void setPreviousExtent() {
692
    setPreviousEnvelope();
693
  }
694

    
695
  /**
696
   * <p>
697
   * Sets as envelope and adjusted envelope of this view port, the previous.
698
   * Recalculating its parameters.
699
   * Stores the current extent in the next extents of the history.
700
   * </p>
701
   *
702
   * @see #getExtents()
703
   * @see #calculateAffineTransform()
704
   */
705
  public void setPreviousEnvelope() {
706
    this.updateDrawVersion();
707

    
708
//    extentsHistory.putNext(extent);
709
//    extent = extentsHistory.removePrev();
710
    extent = extentsHistory.setPreviousExtent();
711

    
712
    // Calcula la transformaci?n af?n
713
    calculateAffineTransform();
714

    
715
    // Lanzamos los eventos de extent cambiado
716
    callExtentChanged(getAdjustedExtent());
717
  }
718

    
719
  /**
720
   * <p>
721
   * Sets as envelope and adjusted envelope of this view port, the next.
722
   * Recalculating its parameters.
723
   * Stores the current extent in the previous extents of the history.
724
   * </p>
725
   *
726
   * @see #getExtents()
727
   * @see #calculateAffineTransform()
728
   */
729
  public void setNextEnvelope() {
730
    this.updateDrawVersion();
731

    
732
    extent = extentsHistory.setNextExtent();
733

    
734
    // Calcula la transformaci?n af?n
735
    calculateAffineTransform();
736

    
737
    // Lanzamos los eventos de extent cambiado
738
    callExtentChanged(getAdjustedExtent());
739
  }
740

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

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

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

    
853
    if (this.extent != null && this.extent.equals(newExtent)) {
854
      return;
855
    }
856

    
857
    this.updateDrawVersion();
858
    this.extent = newExtent;
859
    try {
860
        calculateAffineTransform();
861
    } catch(Exception ex) {
862
        this.extent = null;
863
        throw ex;
864
    }
865
    extentsHistory.put(extent);
866

    
867

    
868
    // Lanzamos los eventos de extent cambiado
869
    callExtentChanged(getAdjustedExtent());
870
  }
871

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

    
896
    // Calcula la transformaci?n af?n
897
    calculateAffineTransform();
898

    
899
    // Lanzamos los eventos de extent cambiado
900
    callExtentChanged(getAdjustedExtent());
901
  }
902

    
903
  /**
904
   * <p>
905
   * Calculates and returns using the current projection of this view port, the
906
   * scale that is the extent in <i>screen coordinates</i> from the image in
907
   * <i>map coordinates</i>.
908
   * </p>
909
   *
910
   * @return the scale <i>extent / image size</i> projected by this view port
911
   * @deprecated since 07/09/07, use {@linkplain MapContext#getScaleView()}
912
   */
913
  private double getScale() {
914

    
915
    double[] trans2Meter = MapContext.getDistanceTrans2Meter();
916
    if (proj == null) {
917
      double wmeters = ((getImageSize().width / this.getDPI()) * 0.0254);
918
      return (long) ((trans2Meter[getMapUnits()] * getAdjustedEnvelope()
919
          .getLength(0)) / wmeters);
920
    }
921
    else {
922
      return Math.round(proj.getScale(getAdjustedEnvelope().getMinimum(0)
923
          * trans2Meter[getMapUnits()], getAdjustedEnvelope().getMaximum(0)
924
          * trans2Meter[getMapUnits()], getImageSize().width, this.getDPI()));
925
    }
926

    
927
    /*
928
     * return proj.getScale(extent.getMinX(), extent.getMaxX(), imageSize.width,
929
     * dpi);
930
     */
931
  }
932

    
933
  /**
934
   * <p>
935
   * Affine transformation between <i>map 2D coordinates</i> to <i>screen 2D
936
   * coordinates</i> (pixels), preserving the "straightness" and "parallelism"
937
   * of the lines.
938
   * </p>
939
   *
940
   * @return the affine transformation
941
   * @see #setAffineTransform(AffineTransform)
942
   * @see #calculateAffineTransform()
943
   */
944
  public AffineTransform getAffineTransform() {
945
    return trans;
946
  }
947

    
948
  /**
949
   * <p>
950
   * Returns the size of the image projected.
951
   * </p>
952
   *
953
   * @return the image size
954
   * @see #setImageSize(Dimension)
955
   * @see #getImageHeight()
956
   * @see #getImageWidth()
957
   */
958
  public Dimension getImageSize() {
959
    return imageSize;
960
  }
961

    
962
  /**
963
   * <p>
964
   * Sets the size of the image projected, recalculating the parameters of this
965
   * view port.
966
   * </p>
967
   *
968
   * @param imageSize the image size
969
   * @see #getImageSize()
970
   * @see #calculateAffineTransform()
971
   */
972
  public void setImageSize(Dimension imageSize) {
973

    
974
    if (this.imageSize == null || (!this.imageSize.equals(imageSize))) {
975
      this.updateDrawVersion();
976
      this.imageSize = imageSize;
977
      calculateAffineTransform();
978
    }
979
  }
980

    
981
  /**
982
   * <p>
983
   * Notifies to all view port listeners registered, that the adjusted extent of
984
   * this view port has changed.
985
   * </p>
986
   *
987
   * @param newRect the new adjusted extend
988
   * @see #refreshExtent()
989
   * @see #setEnvelope(Envelope)
990
   * @see #setPreviousExtent()
991
   * @see ExtentEvent
992
   * @see ViewPortListener
993
   */
994
  protected void callExtentChanged(Envelope newRect) {
995
    ExtentEvent ev = ExtentEvent.createExtentEvent(newRect);
996

    
997
    for (int i = 0; i < listeners.size(); i++) {
998
      ViewPortListener listener = (ViewPortListener) listeners.get(i);
999
      listener.extentChanged(ev);
1000
    }
1001
  }
1002

    
1003
  /**
1004
   * <p>
1005
   * Notifies to all view port listeners registered, that the time of this view
1006
   * port has changed.
1007
   * </p>
1008
   *
1009
   * @param newTime the new time
1010
   * @see #refreshExtent()
1011
   * @see #setTime(Time)
1012
   * @see ExtentEvent
1013
   * @see ViewPortListener
1014
   */
1015
  protected void callTimeChanged(Time newTime) {
1016
    ExtentEvent viewPortEvent = new ExtentEvent(newTime);
1017

    
1018
    for (int i = 0; i < listeners.size(); i++) {
1019
      ViewPortListener listener = (ViewPortListener) listeners.get(i);
1020
      listener.extentChanged(viewPortEvent);
1021
    }
1022
  }
1023

    
1024
  /**
1025
   * <p>
1026
   * Notifies to all view port listeners registered, that the background color
1027
   * of this view port has changed.
1028
   * </p>
1029
   *
1030
   * @param c the new background color
1031
   * @see #setBackColor(Color)
1032
   * @see ColorEvent
1033
   * @see ViewPortListener
1034
   */
1035
  private void callColorChanged(Color c) {
1036
    ColorEvent ce = ColorEvent.createColorEvent(c);
1037

    
1038
    for (int i = 0; i < listeners.size(); i++) {
1039
      ViewPortListener listener = (ViewPortListener) listeners.get(i);
1040
      listener.backColorChanged(ce);
1041
    }
1042
  }
1043

    
1044
  /**
1045
   * <p>
1046
   * Notifies to all view port listeners registered, that the projection of this
1047
   * view port has changed.
1048
   * </p>
1049
   *
1050
   * @param projection the new projection
1051
   * @see #setProjection(IProjection)
1052
   * @see ProjectionEvent
1053
   * @see ViewPortListener
1054
   */
1055
  private void callProjectionChanged(IProjection projection) {
1056
    ProjectionEvent ev = ProjectionEvent.createProjectionEvent(projection);
1057

    
1058
    for (int i = 0; i < listeners.size(); i++) {
1059
      ViewPortListener listener = (ViewPortListener) listeners.get(i);
1060
      listener.projectionChanged(ev);
1061
    }
1062
  }
1063

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

    
1098
    AffineTransform escalado = new AffineTransform();
1099
    AffineTransform translacion = new AffineTransform();
1100

    
1101
    double escalaX;
1102
    double escalaY;
1103

    
1104
    escalaX = imageSize.width / extent.getWidth();
1105
    escalaY = imageSize.height / extent.getHeight();
1106

    
1107
    double xCenter = extent.getCenterX();
1108
    double yCenter = extent.getCenterY();
1109
    double newHeight;
1110
    double newWidth;
1111

    
1112
    adjustedExtent = new Rectangle2D.Double();
1113

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

    
1141
    AffineTransform offsetTrans = new AffineTransform();
1142
    offsetTrans.setToTranslation(offset.getX(), offset.getY());
1143

    
1144
    trans.setToIdentity();
1145
    trans.concatenate(offsetTrans);
1146
    trans.concatenate(escalado);
1147

    
1148
    trans.concatenate(translacion);
1149

    
1150
    // Calculamos las distancias de 1 pixel y 3 pixel con esa
1151
    // transformaci?n
1152
    // de coordenadas, de forma que est?n precalculadas para cuando las
1153
    // necesitemos
1154
    AffineTransform at;
1155

    
1156
    try {
1157
      at = trans.createInverse();
1158

    
1159
      Point2D pPixel = new Point2D.Float(1, 1);
1160

    
1161
      Point2D.Float pProv = new Point2D.Float();
1162
      at.deltaTransform(pPixel, pProv);
1163

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

    
1185
  /**
1186
   * <p>
1187
   * Sets the offset.
1188
   * </p>
1189
   * <p>
1190
   * The offset is the position where start drawing the map.
1191
   * </p>
1192
   *
1193
   * @param p 2D point that represents the offset in pixels
1194
   * @see #getOffset()
1195
   */
1196
  public void setOffset(Point2D p) {
1197
    if (!offset.equals(p)) {
1198
      this.updateDrawVersion();
1199
      offset = p;
1200
    }
1201
  }
1202

    
1203
  /**
1204
   * <p>
1205
   * Gets the offset.
1206
   * </p>
1207
   * <p>
1208
   * The offset is the position where start drawing the map.
1209
   * </p>
1210
   *
1211
   * @return 2D point that represents the offset in pixels
1212
   * @see #setOffset(Point2D)
1213
   */
1214
  public Point2D getOffset() {
1215
    return offset;
1216
  }
1217

    
1218
  /**
1219
   * <p>
1220
   * Sets the background color.
1221
   * </p>
1222
   *
1223
   * @param c the new background color
1224
   * @see #getBackColor()
1225
   */
1226
  public void setBackColor(Color c) {
1227
    if (!c.equals(this.backColor)) {
1228
      this.updateDrawVersion();
1229
      backColor = c;
1230
      callColorChanged(backColor);
1231
    }
1232
  }
1233

    
1234
  /**
1235
   * <p>
1236
   * Gets the background color.
1237
   * </p>
1238
   *
1239
   * @return the background color of the view
1240
   * @see #setBackColor(Color)
1241
   */
1242
  public Color getBackColor() {
1243
    return backColor;
1244
  }
1245

    
1246
  /**
1247
   * <p>
1248
   * Returns the extent currently covered by the view adjusted (scaled) to the
1249
   * image size aspect.
1250
   * </p>
1251
   *
1252
   * @return extent of the view adjusted to the image size aspect
1253
   * @see #setAdjustable(boolean)
1254
   * @deprecated use {@link ViewPort#getAdjustedEnvelope()} instead
1255
   */
1256
  public Envelope getAdjustedExtent() {
1257
    return getAdjustedEnvelope();
1258
  }
1259

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

    
1294
  /**
1295
   * <p>
1296
   * Returns the measurement unit of this view port used for measuring distances
1297
   * and displaying information.
1298
   * </p>
1299
   *
1300
   * @return the measurement unit of this view used for measuring distances and
1301
   *         displaying information
1302
   * @see #setDistanceUnits(int)
1303
   */
1304
  public int getDistanceUnits() {
1305
    return distanceUnits;
1306
  }
1307

    
1308
  /**
1309
   * <p>
1310
   * Returns the measurement unit of this view port used for measuring areas and
1311
   * displaying information.
1312
   * </p>
1313
   *
1314
   * @return the measurement unit of this view used for measuring areas and
1315
   *         displaying information
1316
   * @see #setDistanceUnits(int)
1317
   */
1318
  public int getDistanceArea() {
1319
    return distanceArea;
1320
  }
1321

    
1322
  /**
1323
   * <p>
1324
   * Sets the measurement unit of this view port used for measuring distances
1325
   * and displaying information.
1326
   * </p>
1327
   *
1328
   * @param distanceUnits the measurement unit of this view used for measuring
1329
   *          distances and displaying information
1330
   * @see #getDistanceUnits()
1331
   */
1332
  public void setDistanceUnits(int distanceUnits) {
1333
    this.distanceUnits = distanceUnits;
1334
  }
1335

    
1336
  /**
1337
   * <p>
1338
   * Sets the measurement unit of this view port used for measuring areas and
1339
   * displaying information.
1340
   * </p>
1341
   *
1342
   * @param distanceUnits the measurement unit of this view used for measuring
1343
   *          areas and displaying information
1344
   * @see #getDistanceUnits()
1345
   */
1346
  public void setDistanceArea(int distanceArea) {
1347
    this.distanceArea = distanceArea;
1348
  }
1349

    
1350
  /**
1351
   * <p>
1352
   * Gets the measurement unit used by this view port for the map.
1353
   * </p>
1354
   *
1355
   * @return Returns the current map measure unit
1356
   * @see #setMapUnits(int)
1357
   */
1358
  public int getMapUnits() {
1359
    return mapUnits;
1360
  }
1361

    
1362
  /**
1363
   * <p>
1364
   * Sets the measurement unit used by this view port for the map.
1365
   * </p>
1366
   *
1367
   * @param mapUnits the new map measure unit
1368
   * @see #getMapUnits()
1369
   */
1370
  public void setMapUnits(int mapUnits) {
1371
    this.mapUnits = mapUnits;
1372
  }
1373

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

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

    
1426
  /**
1427
   * <p>
1428
   * Gets the distance in <i>world coordinates</i> equivalent to 1 pixel in the
1429
   * view with the current extent.
1430
   * </p>
1431
   *
1432
   * @return the distance
1433
   * @see #setDist1pixel(double)
1434
   */
1435
  public double getDist1pixel() {
1436
    return dist1pixel;
1437
  }
1438

    
1439
  /**
1440
   * <p>
1441
   * Sets the distance in <i>world coordinates</i> equivalent to 1 pixel in the
1442
   * view with the current extent.
1443
   * </p>
1444
   *
1445
   * @param dist1pixel the distance
1446
   * @see #getDist1pixel()
1447
   */
1448
  public void setDist1pixel(double dist1pixel) {
1449
    if (dist1pixel == this.dist1pixel) {
1450
      return;
1451
    }
1452
    this.updateDrawVersion();
1453
    this.dist1pixel = dist1pixel;
1454
  }
1455

    
1456
  /**
1457
   * <p>
1458
   * Gets the distance in <i>world coordinates</i> equivalent to 3 pixels in the
1459
   * view with the current extent.
1460
   * </p>
1461
   *
1462
   * @return the distance
1463
   * @see #setDist3pixel(double)
1464
   */
1465
  public double getDist3pixel() {
1466
    return dist3pixel;
1467
  }
1468

    
1469
  /**
1470
   * <p>
1471
   * Sets the distance in <i>world coordinates</i> equivalent to 3 pixels in the
1472
   * view with the current extent.
1473
   * </p>
1474
   *
1475
   * @param dist3pixel the distance
1476
   * @see #getDist3pixel()
1477
   */
1478
  public void setDist3pixel(double dist3pixel) {
1479
    if (this.dist3pixel == dist3pixel) {
1480
      return;
1481
    }
1482
    this.updateDrawVersion();
1483
    this.dist3pixel = dist3pixel;
1484
  }
1485

    
1486
  /**
1487
   * <p>
1488
   * Returns the last previous extents of this view port.
1489
   * </p>
1490
   *
1491
   * @return the last previous extents of this view port
1492
   * @see #setPreviousExtent()
1493
   * @deprecated use {@link ViewPort#getEnvelopes()}
1494
   */
1495
  public ExtentHistory getExtents() {
1496
    return getEnvelopes();
1497
  }
1498

    
1499
  /**
1500
   * <p>
1501
   * Returns the last previous extents of this view port.
1502
   * </p>
1503
   *
1504
   * @return the last previous extents of this view port
1505
   * @see #setPreviousExtent()
1506
   */
1507
  public ExtentHistory getEnvelopes() {
1508
    return extentsHistory;
1509
  }
1510

    
1511
  /**
1512
   * <p>
1513
   * Gets the projection used in this view port.
1514
   * </p>
1515
   *
1516
   * @return projection used in this view port
1517
   * @see #setProjection(IProjection)
1518
   */
1519
  public IProjection getProjection() {
1520
    return proj;
1521
  }
1522

    
1523
  /**
1524
   * <p>
1525
   * Sets the projection to this view port.
1526
   * </p>
1527
   *
1528
   * @param proj the new projection
1529
   * @see #getProjection()
1530
   */
1531
  public void setProjection(IProjection proj) {
1532
    if (this.proj == null || !this.proj.getAbrev().equals(proj.getAbrev())) {
1533
      this.updateDrawVersion();
1534
      this.proj = proj;
1535
      callProjectionChanged(proj);
1536
    }
1537
  }
1538

    
1539
  // -----------------------------------------------------------------------------------------------------------
1540
  // NOTA PARA DESARROLLADORES SOBRE EL M?TODO
1541
  // "public void setAffineTransform(AffineTransform at)"
1542
  // ==============================================================================================
1543
  // Only used for print, should be removed, redefining the {@link
1544
  // RasterAdapter RasterAdapter} interface,
1545
  // allowing it to receive a {@link ViewPortData ViewPortData} .
1546
  // -----------------------------------------------------------------------------------------------------------
1547

    
1548
  /**
1549
   * <p>
1550
   * Sets only the affine transform to this view port, without updating
1551
   * dependent attributes.
1552
   * </p>
1553
   * <p>
1554
   * <b><i>This method could be problematic!</i></b>
1555
   * </p>
1556
   *
1557
   * @param at the affine transform to set
1558
   * @see #getAffineTransform()
1559
   * @see #calculateAffineTransform()
1560
   */
1561
  public void setAffineTransform(AffineTransform at) {
1562
    this.trans = at;
1563
  }
1564

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

    
1626
    state.set(FIELD_ADJUSTED_EXTENT, adjustedExtent);
1627
    state.set(FIELD_BACK_COLOR, backColor);
1628
    state.set(FIELD_CLIP, cliprect);
1629
    state.set(FIELD_DIST1PIXEL, dist1pixel);
1630
    state.set(FIELD_DIST3PIXEL, dist3pixel);
1631
    state.set(FIELD_DISTANCE_UNITS, distanceUnits);
1632
    state.set(FIELD_DISTANCE_AREA, distanceArea);
1633

    
1634
    state.set(FIELD_EXTENT, extent);
1635
    state.set(FIELD_EXTENTS, extentsHistory);
1636

    
1637
    state.set(FIELD_MAP_UNITS, mapUnits);
1638
    state.set(FIELD_OFFSET, offset);
1639

    
1640
    state.set(FIELD_PROJ, proj);
1641

    
1642
    state.set(FIELD_IMAGE_SIZE, imageSize);
1643
  }
1644

    
1645
  public void loadFromState(PersistentState state) throws PersistenceException {
1646

    
1647
    adjustedExtent = (Rectangle2D) state.get(FIELD_ADJUSTED_EXTENT);
1648
    backColor = (Color) state.get(FIELD_BACK_COLOR);
1649
    cliprect = (Rectangle2D) state.get(FIELD_CLIP);
1650
    dist1pixel = state.getDouble(FIELD_DIST1PIXEL);
1651
    dist3pixel = state.getDouble(FIELD_DIST3PIXEL);
1652
    distanceUnits = state.getInt(FIELD_DISTANCE_UNITS);
1653
    extentsHistory = (ExtentHistory) state.get(FIELD_EXTENTS);
1654
    extent = (Rectangle2D) state.get(FIELD_EXTENT);
1655
    mapUnits = state.getInt(FIELD_MAP_UNITS);
1656
    offset = (Point2D) state.get(FIELD_OFFSET);
1657
    proj = (IProjection) state.get(FIELD_PROJ);
1658
    imageSize = (Dimension) state.get(FIELD_IMAGE_SIZE);
1659
    distanceArea = state.getInt(FIELD_DISTANCE_AREA);
1660

    
1661
    refreshExtent();
1662
  }
1663

    
1664
  public static class RegisterPersistence implements Callable {
1665

    
1666
    public Object call() throws Exception {
1667
      PersistenceManager manager = ToolsLocator.getPersistenceManager();
1668
      if (manager.getDefinition("ViewPort") == null) {
1669
        DynStruct definition = manager.addDefinition(ViewPort.class,
1670
            "ViewPort", "ViewPort Persistence definition", null, null);
1671

    
1672
        definition.addDynFieldObject(FIELD_ADJUSTED_EXTENT)
1673
            .setClassOfValue(Rectangle2D.class).setMandatory(false);
1674

    
1675
        definition.addDynFieldObject(FIELD_BACK_COLOR)
1676
            .setClassOfValue(Color.class).setMandatory(false);
1677

    
1678
        definition.addDynFieldObject(FIELD_CLIP)
1679
            .setClassOfValue(Rectangle2D.class).setMandatory(false);
1680

    
1681
        definition.addDynFieldDouble(FIELD_DIST1PIXEL).setMandatory(true);
1682

    
1683
        definition.addDynFieldDouble(FIELD_DIST3PIXEL).setMandatory(true);
1684

    
1685
        definition.addDynFieldInt(FIELD_DISTANCE_UNITS).setMandatory(true);
1686

    
1687
        definition.addDynFieldInt(FIELD_DISTANCE_AREA).setMandatory(false);
1688

    
1689
        definition.addDynFieldObject(FIELD_EXTENT)
1690
            .setClassOfValue(Rectangle2D.class).setMandatory(false);
1691

    
1692
        definition.addDynFieldObject(FIELD_EXTENTS)
1693
            .setClassOfValue(ExtentHistory.class).setMandatory(true);
1694

    
1695
        definition.addDynFieldInt(FIELD_MAP_UNITS).setMandatory(true);
1696

    
1697
        definition.addDynFieldObject(FIELD_OFFSET)
1698
            .setClassOfValue(Point2D.class).setMandatory(false);
1699

    
1700
        definition.addDynFieldObject(FIELD_PROJ)
1701
            .setClassOfValue(IProjection.class).setMandatory(true);
1702

    
1703
        definition.addDynFieldObject(FIELD_IMAGE_SIZE)
1704
            .setClassOfValue(Dimension.class).setMandatory(false);
1705
      }
1706
      return Boolean.TRUE;
1707
    }
1708

    
1709
  }
1710

    
1711
  /**
1712
   * Clone the view port without clone the listeners nor the extent history.
1713
   *
1714
   * @return the cloned view port
1715
   */
1716
  public Object clone() throws CloneNotSupportedException {
1717

    
1718
    ViewPort clonedViewPort = (ViewPort) super.clone();
1719
    clonedViewPort.listeners = new ArrayList();
1720
    clonedViewPort.extentsHistory = new ExtentHistory();
1721

    
1722
    if (this.adjustedExtent != null) {
1723
      clonedViewPort.adjustedExtent = (Rectangle2D) this.adjustedExtent.clone();
1724
    }
1725

    
1726
    if (this.cliprect != null) {
1727
      clonedViewPort.cliprect = (Rectangle2D) this.cliprect.clone();
1728
    }
1729

    
1730
    if (this.extent != null) {
1731
      clonedViewPort.extent = (Rectangle2D) this.extent.clone();
1732
    }
1733
    if (this.imageSize != null) {
1734
      clonedViewPort.imageSize = (Dimension) this.imageSize.clone();
1735
    }
1736

    
1737
    if (this.offset != null) {
1738
      clonedViewPort.offset = (Point2D) this.offset.clone();
1739
    }
1740
    if (proj != null) {
1741
      clonedViewPort.proj = (IProjection) this.proj.clone();
1742
    }
1743

    
1744
    clonedViewPort.trans = (AffineTransform) this.trans.clone();
1745

    
1746
    return clonedViewPort;
1747
  }
1748

    
1749
  /**
1750
   * <p>
1751
   * Returns a <code>String</code> representation of the main values of this
1752
   * view port: <code>{@linkplain #extent}</code>,
1753
   * <code>{@linkplain #adjustedExtent}</code>,
1754
   * <code>{@linkplain #imageSize}</code>, <code>{@linkplain #scale}</code>, and
1755
   * <code>{@linkplain #trans}</code>.
1756
   * </p>
1757
   *
1758
   * @return a <code>string</code> representation of the main values of this
1759
   *         view port
1760
   */
1761
  public String toString() {
1762

    
1763
    String str;
1764
    str = "Datos del viewPort:\nExtent=" + extent + "\nadjustedExtent="
1765
        + adjustedExtent + "\nimageSize=" + imageSize + "\nescale=" + scale
1766
        + "\ntrans=" + trans;
1767

    
1768
    return str;
1769
  }
1770

    
1771
  /**
1772
   * <p>
1773
   * Sets the position and size of the clipping rectangle.
1774
   * </p>
1775
   *
1776
   * @param rectView the clipping rectangle to set
1777
   */
1778
  public void setClipRect(Rectangle2D rectView) {
1779
    this.updateDrawVersion();
1780
    cliprect = rectView;
1781
  }
1782

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

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

    
1822
    double x1 = (-x * difw) - x + extent.getWidth() / 2;
1823
    double y1 = (-y * difw) - y + extent.getHeight() / 2;
1824
    double w1 = extent.getWidth() * difw;
1825
    double h1 = extent.getHeight() * difw;
1826
    extent.setRect(-x1, -y1, w1, h1);
1827
  }
1828

    
1829
  public long getDrawVersion() {
1830
    return this.drawVersion;
1831
  }
1832

    
1833
  protected void updateDrawVersion() {
1834
    this.drawVersion++;
1835
  }
1836

    
1837
  public Time getTime() {
1838
    return time;
1839
  }
1840

    
1841
  public void setTime(Time time) {
1842
    this.time = time;
1843
    this.updateDrawVersion();
1844
    callTimeChanged(time);
1845
  }
1846

    
1847
  public double getDPI() {
1848
    if (this.dpi == null) {
1849
      return CompatLocator.getGraphicsUtils().getScreenDPI();
1850
    }
1851
    return this.dpi.doubleValue();
1852
  }
1853

    
1854
  public void setDPI(double dpi) {
1855
    this.dpi = new Double(dpi);
1856
  }
1857

    
1858
  public void setDPIToScreenDPI() {
1859
    this.dpi = null;
1860
  }
1861
}