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

History | View | Annotate | Download (54.9 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
164
  protected Time time;
165

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
397
  public ViewPort() {
398

    
399
  }
400

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

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

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

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

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

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

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

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

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

    
526
    return pScreen;
527
  }
528

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

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

    
562
    return toMapPoint(pScreen);
563
  }
564

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

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

    
601
    return dist;
602
  }
603

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

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

    
630
    return pWorld;
631
  }
632

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

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

    
648
    return convertToMapPoint(pScreen);
649
  }
650

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

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

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

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

    
708
    // Calcula la transformaci�n af�n
709
    calculateAffineTransform();
710

    
711
    // Lanzamos los eventos de extent cambiado
712
    callExtentChanged(getAdjustedExtent());
713
  }
714

    
715
  /**
716
   * <p>
717
   * Sets as envelope and adjusted envelope of this view port, the next.
718
   * Recalculating its parameters.
719
   * </p>
720
   * 
721
   * @see #getExtents()
722
   * @see #calculateAffineTransform()
723
   */
724
  public void setNextEnvelope() {
725
    this.updateDrawVersion();
726
    extentsHistory.put(extent);
727
    extent = extentsHistory.removeNext();
728

    
729
    // Calcula la transformaci�n af�n
730
    calculateAffineTransform();
731

    
732
    // Lanzamos los eventos de extent cambiado
733
    callExtentChanged(getAdjustedExtent());
734
  }
735

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

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

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

    
847
    if (this.extent != null && this.extent.equals(newExtent)) {
848
      return;
849
    }
850

    
851
    if (extent != null) {
852
      if (!extent.equals(extentsHistory.get())
853
          && !extent.equals(extentsHistory.getNext())) {
854
        extentsHistory.clear();
855
      }
856
      extentsHistory.put(extent);
857
    }
858

    
859
    this.updateDrawVersion();
860
    this.extent = newExtent;
861

    
862
    // Calcula la transformaci�n af�n
863
    calculateAffineTransform();
864
   
865

    
866
    // Lanzamos los eventos de extent cambiado
867
    callExtentChanged(getAdjustedExtent());
868
  }
869

    
870
  /**
871
   * <p>
872
   * Changes the <i>extent</i> and <i>adjusted extent</i> of this view port:<br>
873
   * <ul>
874
   * <li>Executes {@linkplain #calculateAffineTransform()}: getting the new
875
   * scale, adjusted extent, affine transformation between map and screen
876
   * coordinates, the real world coordinates equivalent to 1 pixel, and the real
877
   * world coordinates equivalent to 3 pixels.
878
   * <li>Notifies to all {@link ViewPortListener ViewPortListener} registered
879
   * that the extent has changed.
880
   * </ul>
881
   * </p>
882
   * 
883
   * @see #setEnvelope(Envelope)
884
   * @see #calculateAffineTransform()
885
   */
886
  public void refreshExtent() {
887
    // this.scale = scale;
888

    
889
    // Calcula la transformaci�n af�n
890
    calculateAffineTransform();
891

    
892
    // Lanzamos los eventos de extent cambiado
893
    callExtentChanged(getAdjustedExtent());
894
  }
895

    
896
  /**
897
   * <p>
898
   * Calculates and returns using the current projection of this view port, the
899
   * scale that is the extent in <i>screen coordinates</i> from the image in
900
   * <i>map coordinates</i>.
901
   * </p>
902
   * 
903
   * @return the scale <i>extent / image size</i> projected by this view port
904
   * @deprecated since 07/09/07, use {@linkplain MapContext#getScaleView()}
905
   */
906
  private double getScale() {
907

    
908
    double[] trans2Meter = MapContext.getDistanceTrans2Meter();
909
    if (proj == null) {
910
      double wmeters = ((getImageSize().width / this.getDPI()) * 0.0254);
911
      return (long) ((trans2Meter[getMapUnits()] * getAdjustedEnvelope()
912
          .getLength(0)) / wmeters);
913
    }
914
    else {
915
      return Math.round(proj.getScale(getAdjustedEnvelope().getMinimum(0)
916
          * trans2Meter[getMapUnits()], getAdjustedEnvelope().getMaximum(0)
917
          * trans2Meter[getMapUnits()], getImageSize().width, this.getDPI()));
918
    }
919

    
920
    /*
921
     * return proj.getScale(extent.getMinX(), extent.getMaxX(), imageSize.width,
922
     * dpi);
923
     */
924
  }
925

    
926
  /**
927
   * <p>
928
   * Affine transformation between <i>map 2D coordinates</i> to <i>screen 2D
929
   * coordinates</i> (pixels), preserving the "straightness" and "parallelism"
930
   * of the lines.
931
   * </p>
932
   * 
933
   * @return the affine transformation
934
   * @see #setAffineTransform(AffineTransform)
935
   * @see #calculateAffineTransform()
936
   */
937
  public AffineTransform getAffineTransform() {
938
    return trans;
939
  }
940

    
941
  /**
942
   * <p>
943
   * Returns the size of the image projected.
944
   * </p>
945
   * 
946
   * @return the image size
947
   * @see #setImageSize(Dimension)
948
   * @see #getImageHeight()
949
   * @see #getImageWidth()
950
   */
951
  public Dimension getImageSize() {
952
    return imageSize;
953
  }
954

    
955
  /**
956
   * <p>
957
   * Sets the size of the image projected, recalculating the parameters of this
958
   * view port.
959
   * </p>
960
   * 
961
   * @param imageSize the image size
962
   * @see #getImageSize()
963
   * @see #calculateAffineTransform()
964
   */
965
  public void setImageSize(Dimension imageSize) {
966

    
967
    if (this.imageSize == null || (!this.imageSize.equals(imageSize))) {
968
      this.updateDrawVersion();
969
      this.imageSize = imageSize;
970
      calculateAffineTransform();
971
    }
972
  }
973

    
974
  /**
975
   * <p>
976
   * Notifies to all view port listeners registered, that the adjusted extent of
977
   * this view port has changed.
978
   * </p>
979
   * 
980
   * @param newRect the new adjusted extend
981
   * @see #refreshExtent()
982
   * @see #setEnvelope(Envelope)
983
   * @see #setPreviousExtent()
984
   * @see ExtentEvent
985
   * @see ViewPortListener
986
   */
987
  protected void callExtentChanged(Envelope newRect) {
988
    ExtentEvent ev = ExtentEvent.createExtentEvent(newRect);
989

    
990
    for (int i = 0; i < listeners.size(); i++) {
991
      ViewPortListener listener = (ViewPortListener) listeners.get(i);
992
      listener.extentChanged(ev);
993
    }
994
  }
995

    
996
  /**
997
   * <p>
998
   * Notifies to all view port listeners registered, that the time of this view
999
   * port has changed.
1000
   * </p>
1001
   * 
1002
   * @param newTime the new time
1003
   * @see #refreshExtent()
1004
   * @see #setTime(Time)
1005
   * @see ExtentEvent
1006
   * @see ViewPortListener
1007
   */
1008
  protected void callTimeChanged(Time newTime) {
1009
    ExtentEvent viewPortEvent = new ExtentEvent(newTime);
1010

    
1011
    for (int i = 0; i < listeners.size(); i++) {
1012
      ViewPortListener listener = (ViewPortListener) listeners.get(i);
1013
      listener.extentChanged(viewPortEvent);
1014
    }
1015
  }
1016

    
1017
  /**
1018
   * <p>
1019
   * Notifies to all view port listeners registered, that the background color
1020
   * of this view port has changed.
1021
   * </p>
1022
   * 
1023
   * @param c the new background color
1024
   * @see #setBackColor(Color)
1025
   * @see ColorEvent
1026
   * @see ViewPortListener
1027
   */
1028
  private void callColorChanged(Color c) {
1029
    ColorEvent ce = ColorEvent.createColorEvent(c);
1030

    
1031
    for (int i = 0; i < listeners.size(); i++) {
1032
      ViewPortListener listener = (ViewPortListener) listeners.get(i);
1033
      listener.backColorChanged(ce);
1034
    }
1035
  }
1036

    
1037
  /**
1038
   * <p>
1039
   * Notifies to all view port listeners registered, that the projection of this
1040
   * view port has changed.
1041
   * </p>
1042
   * 
1043
   * @param projection the new projection
1044
   * @see #setProjection(IProjection)
1045
   * @see ProjectionEvent
1046
   * @see ViewPortListener
1047
   */
1048
  private void callProjectionChanged(IProjection projection) {
1049
    ProjectionEvent ev = ProjectionEvent.createProjectionEvent(projection);
1050

    
1051
    for (int i = 0; i < listeners.size(); i++) {
1052
      ViewPortListener listener = (ViewPortListener) listeners.get(i);
1053
      listener.projectionChanged(ev);
1054
    }
1055
  }
1056

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

    
1091
    AffineTransform escalado = new AffineTransform();
1092
    AffineTransform translacion = new AffineTransform();
1093

    
1094
    double escalaX;
1095
    double escalaY;
1096

    
1097
    escalaX = imageSize.width / extent.getWidth();
1098
    escalaY = imageSize.height / extent.getHeight();
1099

    
1100
    double xCenter = extent.getCenterX();
1101
    double yCenter = extent.getCenterY();
1102
    double newHeight;
1103
    double newWidth;
1104

    
1105
    adjustedExtent = new Rectangle2D.Double();
1106

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

    
1134
    AffineTransform offsetTrans = new AffineTransform();
1135
    offsetTrans.setToTranslation(offset.getX(), offset.getY());
1136

    
1137
    trans.setToIdentity();
1138
    trans.concatenate(offsetTrans);
1139
    trans.concatenate(escalado);
1140

    
1141
    trans.concatenate(translacion);
1142

    
1143
    // Calculamos las distancias de 1 pixel y 3 pixel con esa
1144
    // transformaci�n
1145
    // de coordenadas, de forma que est�n precalculadas para cuando las
1146
    // necesitemos
1147
    AffineTransform at;
1148

    
1149
    try {
1150
      at = trans.createInverse();
1151

    
1152
      Point2D pPixel = new Point2D.Float(1, 1);
1153

    
1154
      Point2D.Float pProv = new Point2D.Float();
1155
      at.deltaTransform(pPixel, pProv);
1156

    
1157
      dist1pixel = pProv.x;
1158
      dist3pixel = 3 * pProv.x;
1159
    }
1160
    catch (NoninvertibleTransformException e) {
1161
      System.err.println("transformada afin = " + trans.toString());
1162
      System.err.println("extent = " + extent.toString() + " imageSize= "
1163
          + imageSize.toString());
1164
      throw new RuntimeException("Non invertible transform Exception", e);
1165
    }
1166
  }
1167

    
1168
  /**
1169
   * <p>
1170
   * Sets the offset.
1171
   * </p>
1172
   * <p>
1173
   * The offset is the position where start drawing the map.
1174
   * </p>
1175
   * 
1176
   * @param p 2D point that represents the offset in pixels
1177
   * @see #getOffset()
1178
   */
1179
  public void setOffset(Point2D p) {
1180
    if (!offset.equals(p)) {
1181
      this.updateDrawVersion();
1182
      offset = p;
1183
    }
1184
  }
1185

    
1186
  /**
1187
   * <p>
1188
   * Gets the offset.
1189
   * </p>
1190
   * <p>
1191
   * The offset is the position where start drawing the map.
1192
   * </p>
1193
   * 
1194
   * @return 2D point that represents the offset in pixels
1195
   * @see #setOffset(Point2D)
1196
   */
1197
  public Point2D getOffset() {
1198
    return offset;
1199
  }
1200

    
1201
  /**
1202
   * <p>
1203
   * Sets the background color.
1204
   * </p>
1205
   * 
1206
   * @param c the new background color
1207
   * @see #getBackColor()
1208
   */
1209
  public void setBackColor(Color c) {
1210
    if (!c.equals(this.backColor)) {
1211
      this.updateDrawVersion();
1212
      backColor = c;
1213
      callColorChanged(backColor);
1214
    }
1215
  }
1216

    
1217
  /**
1218
   * <p>
1219
   * Gets the background color.
1220
   * </p>
1221
   * 
1222
   * @return the background color of the view
1223
   * @see #setBackColor(Color)
1224
   */
1225
  public Color getBackColor() {
1226
    return backColor;
1227
  }
1228

    
1229
  /**
1230
   * <p>
1231
   * Returns the extent currently covered by the view adjusted (scaled) to the
1232
   * image size aspect.
1233
   * </p>
1234
   * 
1235
   * @return extent of the view adjusted to the image size aspect
1236
   * @see #setAdjustable(boolean)
1237
   * @deprecated use {@link ViewPort#getAdjustedEnvelope()} instead
1238
   */
1239
  public Envelope getAdjustedExtent() {
1240
    return getAdjustedEnvelope();
1241
  }
1242

    
1243
  /**
1244
   * <p>
1245
   * Returns the envelope currently covered by the view adjusted (scaled) to the
1246
   * image size aspect.
1247
   * </p>
1248
   * 
1249
   * @return envelope of the view adjusted to the image size aspect
1250
   * @see #setAdjustable(boolean)
1251
   */
1252
  public Envelope getAdjustedEnvelope() {
1253
    if (cliprect != null) {
1254
      Rectangle2D r = adjustedExtent.createIntersection(cliprect);
1255
      try {
1256
        return geomManager.createEnvelope(r.getX(), r.getY(), r.getMaxX(),
1257
            r.getMaxY(), SUBTYPES.GEOM2D);
1258
      }
1259
      catch (CreateEnvelopeException e) {
1260
        e.printStackTrace();
1261
        logger.error("Error adjusting the extent", e);
1262
      }
1263
    }
1264
    if (adjustedExtent != null) {
1265
      try {
1266
        return geomManager.createEnvelope(adjustedExtent.getX(),
1267
            adjustedExtent.getY(), adjustedExtent.getMaxX(),
1268
            adjustedExtent.getMaxY(), SUBTYPES.GEOM2D);
1269
      }
1270
      catch (CreateEnvelopeException e) {
1271
        e.printStackTrace();
1272
        logger.error("Error adjusting the extent", e);
1273
      }
1274
    }
1275
    return null;
1276
  }
1277

    
1278
  /**
1279
   * <p>
1280
   * Returns the measurement unit of this view port used for measuring distances
1281
   * and displaying information.
1282
   * </p>
1283
   * 
1284
   * @return the measurement unit of this view used for measuring distances and
1285
   *         displaying information
1286
   * @see #setDistanceUnits(int)
1287
   */
1288
  public int getDistanceUnits() {
1289
    return distanceUnits;
1290
  }
1291

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

    
1306
  /**
1307
   * <p>
1308
   * Sets the measurement unit of this view port used for measuring distances
1309
   * and displaying information.
1310
   * </p>
1311
   * 
1312
   * @param distanceUnits the measurement unit of this view used for measuring
1313
   *          distances and displaying information
1314
   * @see #getDistanceUnits()
1315
   */
1316
  public void setDistanceUnits(int distanceUnits) {
1317
    this.distanceUnits = distanceUnits;
1318
  }
1319

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

    
1334
  /**
1335
   * <p>
1336
   * Gets the measurement unit used by this view port for the map.
1337
   * </p>
1338
   * 
1339
   * @return Returns the current map measure unit
1340
   * @see #setMapUnits(int)
1341
   */
1342
  public int getMapUnits() {
1343
    return mapUnits;
1344
  }
1345

    
1346
  /**
1347
   * <p>
1348
   * Sets the measurement unit used by this view port for the map.
1349
   * </p>
1350
   * 
1351
   * @param mapUnits the new map measure unit
1352
   * @see #getMapUnits()
1353
   */
1354
  public void setMapUnits(int mapUnits) {
1355
    this.mapUnits = mapUnits;
1356
  }
1357

    
1358
  /**
1359
   * <p>
1360
   * Gets the width in <i>screen coordinates</i> of the rectangle where the
1361
   * image is displayed.
1362
   * </p>
1363
   * <p>
1364
   * Used by {@linkplain #calculateAffineTransform()} to calculate:<br>
1365
   * <ul>
1366
   * <li>The new {@link #scale scale} .
1367
   * <li>The new {@link #adjustedExtent adjustableExtent} .
1368
   * <li>The new {@link #trans trans} .
1369
   * <li>The new real world coordinates equivalent to 1 pixel (
1370
   * {@link #dist1pixel dist1pixel}) .
1371
   * <li>The new real world coordinates equivalent to 3 pixels (
1372
   * {@link #dist3pixel dist3pixel}) .
1373
   * </ul>
1374
   * </p>
1375
   * 
1376
   * @see #getImageHeight()
1377
   * @see #getImageSize()
1378
   * @see #setImageSize(Dimension)
1379
   */
1380
  public int getImageWidth() {
1381
    return imageSize.width;
1382
  }
1383

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

    
1410
  /**
1411
   * <p>
1412
   * Gets the distance in <i>world coordinates</i> equivalent to 1 pixel in the
1413
   * view with the current extent.
1414
   * </p>
1415
   * 
1416
   * @return the distance
1417
   * @see #setDist1pixel(double)
1418
   */
1419
  public double getDist1pixel() {
1420
    return dist1pixel;
1421
  }
1422

    
1423
  /**
1424
   * <p>
1425
   * Sets the distance in <i>world coordinates</i> equivalent to 1 pixel in the
1426
   * view with the current extent.
1427
   * </p>
1428
   * 
1429
   * @param dist1pixel the distance
1430
   * @see #getDist1pixel()
1431
   */
1432
  public void setDist1pixel(double dist1pixel) {
1433
    if (dist1pixel == this.dist1pixel) {
1434
      return;
1435
    }
1436
    this.updateDrawVersion();
1437
    this.dist1pixel = dist1pixel;
1438
  }
1439

    
1440
  /**
1441
   * <p>
1442
   * Gets the distance in <i>world coordinates</i> equivalent to 3 pixels in the
1443
   * view with the current extent.
1444
   * </p>
1445
   * 
1446
   * @return the distance
1447
   * @see #setDist3pixel(double)
1448
   */
1449
  public double getDist3pixel() {
1450
    return dist3pixel;
1451
  }
1452

    
1453
  /**
1454
   * <p>
1455
   * Sets the distance in <i>world coordinates</i> equivalent to 3 pixels in the
1456
   * view with the current extent.
1457
   * </p>
1458
   * 
1459
   * @param dist3pixel the distance
1460
   * @see #getDist3pixel()
1461
   */
1462
  public void setDist3pixel(double dist3pixel) {
1463
    if (this.dist3pixel == dist3pixel) {
1464
      return;
1465
    }
1466
    this.updateDrawVersion();
1467
    this.dist3pixel = dist3pixel;
1468
  }
1469

    
1470
  /**
1471
   * <p>
1472
   * Returns the last previous extents of this view port.
1473
   * </p>
1474
   * 
1475
   * @return the last previous extents of this view port
1476
   * @see #setPreviousExtent()
1477
   * @deprecated use {@link ViewPort#getEnvelopes()}
1478
   */
1479
  public ExtentHistory getExtents() {
1480
    return getEnvelopes();
1481
  }
1482

    
1483
  /**
1484
   * <p>
1485
   * Returns the last previous extents of this view port.
1486
   * </p>
1487
   * 
1488
   * @return the last previous extents of this view port
1489
   * @see #setPreviousExtent()
1490
   */
1491
  public ExtentHistory getEnvelopes() {
1492
    return extentsHistory;
1493
  }
1494

    
1495
  /**
1496
   * <p>
1497
   * Gets the projection used in this view port.
1498
   * </p>
1499
   * 
1500
   * @return projection used in this view port
1501
   * @see #setProjection(IProjection)
1502
   */
1503
  public IProjection getProjection() {
1504
    return proj;
1505
  }
1506

    
1507
  /**
1508
   * <p>
1509
   * Sets the projection to this view port.
1510
   * </p>
1511
   * 
1512
   * @param proj the new projection
1513
   * @see #getProjection()
1514
   */
1515
  public void setProjection(IProjection proj) {
1516
    if (this.proj == null || !this.proj.getAbrev().equals(proj.getAbrev())) {
1517
      this.updateDrawVersion();
1518
      this.proj = proj;
1519
      callProjectionChanged(proj);
1520
    }
1521
  }
1522

    
1523
  // -----------------------------------------------------------------------------------------------------------
1524
  // NOTA PARA DESARROLLADORES SOBRE EL M�TODO
1525
  // "public void setAffineTransform(AffineTransform at)"
1526
  // ==============================================================================================
1527
  // Only used for print, should be removed, redefining the {@link
1528
  // RasterAdapter RasterAdapter} interface,
1529
  // allowing it to receive a {@link ViewPortData ViewPortData} .
1530
  // -----------------------------------------------------------------------------------------------------------
1531

    
1532
  /**
1533
   * <p>
1534
   * Sets only the affine transform to this view port, without updating
1535
   * dependent attributes.
1536
   * </p>
1537
   * <p>
1538
   * <b><i>This method could be problematic!</i></b>
1539
   * </p>
1540
   * 
1541
   * @param at the affine transform to set
1542
   * @see #getAffineTransform()
1543
   * @see #calculateAffineTransform()
1544
   */
1545
  public void setAffineTransform(AffineTransform at) {
1546
    this.trans = at;
1547
  }
1548

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

    
1610
    state.set(FIELD_ADJUSTED_EXTENT, adjustedExtent);
1611
    state.set(FIELD_BACK_COLOR, backColor);
1612
    state.set(FIELD_CLIP, cliprect);
1613
    state.set(FIELD_DIST1PIXEL, dist1pixel);
1614
    state.set(FIELD_DIST3PIXEL, dist3pixel);
1615
    state.set(FIELD_DISTANCE_UNITS, distanceUnits);
1616
    state.set(FIELD_DISTANCE_AREA, distanceArea);
1617

    
1618
    state.set(FIELD_EXTENT, extent);
1619
    state.set(FIELD_EXTENTS, extentsHistory);
1620

    
1621
    state.set(FIELD_MAP_UNITS, mapUnits);
1622
    state.set(FIELD_OFFSET, offset);
1623

    
1624
    state.set(FIELD_PROJ, proj);
1625

    
1626
    state.set(FIELD_IMAGE_SIZE, imageSize);
1627
  }
1628

    
1629
  public void loadFromState(PersistentState state) throws PersistenceException {
1630

    
1631
    adjustedExtent = (Rectangle2D) state.get(FIELD_ADJUSTED_EXTENT);
1632
    backColor = (Color) state.get(FIELD_BACK_COLOR);
1633
    cliprect = (Rectangle2D) state.get(FIELD_CLIP);
1634
    dist1pixel = state.getDouble(FIELD_DIST1PIXEL);
1635
    dist3pixel = state.getDouble(FIELD_DIST3PIXEL);
1636
    distanceUnits = state.getInt(FIELD_DISTANCE_UNITS);
1637
    extentsHistory = (ExtentHistory) state.get(FIELD_EXTENTS);
1638
    extent = (Rectangle2D) state.get(FIELD_EXTENT);
1639
    mapUnits = state.getInt(FIELD_MAP_UNITS);
1640
    offset = (Point2D) state.get(FIELD_OFFSET);
1641
    proj = (IProjection) state.get(FIELD_PROJ);
1642
    imageSize = (Dimension) state.get(FIELD_IMAGE_SIZE);
1643
    distanceArea = state.getInt(FIELD_DISTANCE_AREA);
1644

    
1645
    refreshExtent();
1646
  }
1647

    
1648
  public static class RegisterPersistence implements Callable {
1649

    
1650
    public Object call() throws Exception {
1651
      PersistenceManager manager = ToolsLocator.getPersistenceManager();
1652
      if (manager.getDefinition("ViewPort") == null) {
1653
        DynStruct definition = manager.addDefinition(ViewPort.class,
1654
            "ViewPort", "ViewPort Persistence definition", null, null);
1655

    
1656
        definition.addDynFieldObject(FIELD_ADJUSTED_EXTENT)
1657
            .setClassOfValue(Rectangle2D.class).setMandatory(false);
1658

    
1659
        definition.addDynFieldObject(FIELD_BACK_COLOR)
1660
            .setClassOfValue(Color.class).setMandatory(false);
1661

    
1662
        definition.addDynFieldObject(FIELD_CLIP)
1663
            .setClassOfValue(Rectangle2D.class).setMandatory(false);
1664

    
1665
        definition.addDynFieldDouble(FIELD_DIST1PIXEL).setMandatory(true);
1666

    
1667
        definition.addDynFieldDouble(FIELD_DIST3PIXEL).setMandatory(true);
1668

    
1669
        definition.addDynFieldInt(FIELD_DISTANCE_UNITS).setMandatory(true);
1670

    
1671
        definition.addDynFieldInt(FIELD_DISTANCE_AREA).setMandatory(false);
1672

    
1673
        definition.addDynFieldObject(FIELD_EXTENT)
1674
            .setClassOfValue(Rectangle2D.class).setMandatory(false);
1675

    
1676
        definition.addDynFieldObject(FIELD_EXTENTS)
1677
            .setClassOfValue(ExtentHistory.class).setMandatory(true);
1678

    
1679
        definition.addDynFieldInt(FIELD_MAP_UNITS).setMandatory(true);
1680

    
1681
        definition.addDynFieldObject(FIELD_OFFSET)
1682
            .setClassOfValue(Point2D.class).setMandatory(false);
1683

    
1684
        definition.addDynFieldObject(FIELD_PROJ)
1685
            .setClassOfValue(IProjection.class).setMandatory(true);
1686

    
1687
        definition.addDynFieldObject(FIELD_IMAGE_SIZE)
1688
            .setClassOfValue(Dimension.class).setMandatory(false);
1689
      }
1690
      return Boolean.TRUE;
1691
    }
1692

    
1693
  }
1694

    
1695
  /**
1696
   * Clone the view port without clone the listeners nor the extent history.
1697
   * 
1698
   * @return the cloned view port
1699
   */
1700
  public Object clone() throws CloneNotSupportedException {
1701

    
1702
    ViewPort clonedViewPort = (ViewPort) super.clone();
1703
    clonedViewPort.listeners = new ArrayList();
1704
    clonedViewPort.extentsHistory = new ExtentHistory();
1705

    
1706
    if (this.adjustedExtent != null) {
1707
      clonedViewPort.adjustedExtent = (Rectangle2D) this.adjustedExtent.clone();
1708
    }
1709

    
1710
    if (this.cliprect != null) {
1711
      clonedViewPort.cliprect = (Rectangle2D) this.cliprect.clone();
1712
    }
1713

    
1714
    if (this.extent != null) {
1715
      clonedViewPort.extent = (Rectangle2D) this.extent.clone();
1716
    }
1717
    if (this.imageSize != null) {
1718
      clonedViewPort.imageSize = (Dimension) this.imageSize.clone();
1719
    }
1720

    
1721
    if (this.offset != null) {
1722
      clonedViewPort.offset = (Point2D) this.offset.clone();
1723
    }
1724
    if (proj != null) {
1725
      clonedViewPort.proj = (IProjection) this.proj.clone();
1726
    }
1727

    
1728
    clonedViewPort.trans = (AffineTransform) this.trans.clone();
1729

    
1730
    return clonedViewPort;
1731
  }
1732

    
1733
  /**
1734
   * <p>
1735
   * Returns a <code>String</code> representation of the main values of this
1736
   * view port: <code>{@linkplain #extent}</code>,
1737
   * <code>{@linkplain #adjustedExtent}</code>,
1738
   * <code>{@linkplain #imageSize}</code>, <code>{@linkplain #scale}</code>, and
1739
   * <code>{@linkplain #trans}</code>.
1740
   * </p>
1741
   * 
1742
   * @return a <code>string</code> representation of the main values of this
1743
   *         view port
1744
   */
1745
  public String toString() {
1746

    
1747
    String str;
1748
    str = "Datos del viewPort:\nExtent=" + extent + "\nadjustedExtent="
1749
        + adjustedExtent + "\nimageSize=" + imageSize + "\nescale=" + scale
1750
        + "\ntrans=" + trans;
1751

    
1752
    return str;
1753
  }
1754

    
1755
  /**
1756
   * <p>
1757
   * Sets the position and size of the clipping rectangle.
1758
   * </p>
1759
   * 
1760
   * @param rectView the clipping rectangle to set
1761
   */
1762
  public void setClipRect(Rectangle2D rectView) {
1763
    this.updateDrawVersion();
1764
    cliprect = rectView;
1765
  }
1766

    
1767
  /**
1768
   * <p>
1769
   * Converts and returns the {@link Rectangle2D Rectangle2D}, that is in <i>map
1770
   * coordinates</i> to <i>screen coordinates</i> (pixels) using an <i>inverse
1771
   * transform</i> with the transformation affine information in the
1772
   * {@link #trans #trans} attribute.
1773
   * </p>
1774
   * 
1775
   * @param r the 2D rectangle in <i>map coordinates</i>
1776
   * @return 2D rectangle equivalent in <i>screen coordinates</i> (pixels)
1777
   * @see #toMapRectangle(Rectangle2D)
1778
   * @see #fromMapDistance(double)
1779
   * @see #fromMapPoint(Point2D)
1780
   */
1781
  public Rectangle2D fromMapRectangle(Rectangle2D r) {
1782
    Rectangle2D rect = new Rectangle2D.Double();
1783
    Point2D p1 = fromMapPoint((int) r.getX(), (int) r.getY());
1784
    Point2D p2 = fromMapPoint((int) r.getMaxX(), (int) r.getMaxY());
1785
    rect.setFrameFromDiagonal(p1, p2);
1786
    return rect;
1787
  }
1788

    
1789
  /**
1790
   * <p>
1791
   * Recalculates the current <code>{@linkplain #extent}</code> using an scale.
1792
   * It's necessary execute {@linkplain #refreshExtent()} after.
1793
   * </p>
1794
   * 
1795
   * @param s the scale to set
1796
   * @deprecated since 07/09/07, use {@linkplain MapContext#setScaleView(long)}
1797
   */
1798
  public void setScale(long s) {
1799
    double x = extent.getX();
1800
    double y = extent.getY();
1801
    double escalaX = imageSize.width / extent.getWidth();
1802
    // double w = imageSize.width / s;
1803
    // double h = imageSize.height / s;
1804
    double difw = escalaX / s;
1805

    
1806
    double x1 = (-x * difw) - x + extent.getWidth() / 2;
1807
    double y1 = (-y * difw) - y + extent.getHeight() / 2;
1808
    double w1 = extent.getWidth() * difw;
1809
    double h1 = extent.getHeight() * difw;
1810
    extent.setRect(-x1, -y1, w1, h1);
1811
  }
1812

    
1813
  public long getDrawVersion() {
1814
    return this.drawVersion;
1815
  }
1816

    
1817
  protected void updateDrawVersion() {
1818
    this.drawVersion++;
1819
  }
1820

    
1821
  public Time getTime() {
1822
    return time;
1823
  }
1824

    
1825
  public void setTime(Time time) {
1826
    this.time = time;
1827
    this.updateDrawVersion();
1828
    callTimeChanged(time);
1829
  }
1830

    
1831
  public double getDPI() {
1832
    if (this.dpi == null) {
1833
      return CompatLocator.getGraphicsUtils().getScreenDPI();
1834
    }
1835
    return this.dpi.doubleValue();
1836
  }
1837

    
1838
  public void setDPI(double dpi) {
1839
    this.dpi = new Double(dpi);
1840
  }
1841

    
1842
  public void setDPIToScreenDPI() {
1843
    this.dpi = null;
1844
  }
1845
}